blob: 9615a3cf57db98d1a75efcfbf809dbed0607f046 [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"
15#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000016#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000017#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000018#include "clang/AST/CXXInheritance.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000020#include "clang/AST/ExprCXX.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000021#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000022#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000023#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000024#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000025#include "llvm/Support/Compiler.h"
26#include <algorithm>
Torok Edwindb714922009-08-24 13:25:12 +000027#include <cstdio>
Douglas Gregor5251f1b2008-10-21 16:13:35 +000028
29namespace clang {
30
31/// GetConversionCategory - Retrieve the implicit conversion
32/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000033ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000034GetConversionCategory(ImplicitConversionKind Kind) {
35 static const ImplicitConversionCategory
36 Category[(int)ICK_Num_Conversion_Kinds] = {
37 ICC_Identity,
38 ICC_Lvalue_Transformation,
39 ICC_Lvalue_Transformation,
40 ICC_Lvalue_Transformation,
41 ICC_Qualification_Adjustment,
42 ICC_Promotion,
43 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000044 ICC_Promotion,
45 ICC_Conversion,
46 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000047 ICC_Conversion,
48 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000052 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000053 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000054 ICC_Conversion
55 };
56 return Category[(int)Kind];
57}
58
59/// GetConversionRank - Retrieve the implicit conversion rank
60/// corresponding to the given implicit conversion kind.
61ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
62 static const ImplicitConversionRank
63 Rank[(int)ICK_Num_Conversion_Kinds] = {
64 ICR_Exact_Match,
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Promotion,
70 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000071 ICR_Promotion,
72 ICR_Conversion,
73 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000074 ICR_Conversion,
75 ICR_Conversion,
76 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000079 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000080 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000081 ICR_Conversion
82 };
83 return Rank[(int)Kind];
84}
85
86/// GetImplicitConversionName - Return the name of this kind of
87/// implicit conversion.
88const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
89 static const char* Name[(int)ICK_Num_Conversion_Kinds] = {
90 "No conversion",
91 "Lvalue-to-rvalue",
92 "Array-to-pointer",
93 "Function-to-pointer",
94 "Qualification",
95 "Integral promotion",
96 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +000097 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +000098 "Integral conversion",
99 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000100 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000101 "Floating-integral conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000102 "Complex-real conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000103 "Pointer conversion",
104 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000105 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000106 "Compatible-types conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000107 "Derived-to-base conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000108 };
109 return Name[Kind];
110}
111
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000112/// StandardConversionSequence - Set the standard conversion
113/// sequence to the identity conversion.
114void StandardConversionSequence::setAsIdentityConversion() {
115 First = ICK_Identity;
116 Second = ICK_Identity;
117 Third = ICK_Identity;
118 Deprecated = false;
119 ReferenceBinding = false;
120 DirectBinding = false;
Sebastian Redlf69a94a2009-03-29 22:46:24 +0000121 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000122 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000123}
124
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000125/// getRank - Retrieve the rank of this standard conversion sequence
126/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
127/// implicit conversions.
128ImplicitConversionRank StandardConversionSequence::getRank() const {
129 ImplicitConversionRank Rank = ICR_Exact_Match;
130 if (GetConversionRank(First) > Rank)
131 Rank = GetConversionRank(First);
132 if (GetConversionRank(Second) > Rank)
133 Rank = GetConversionRank(Second);
134 if (GetConversionRank(Third) > Rank)
135 Rank = GetConversionRank(Third);
136 return Rank;
137}
138
139/// isPointerConversionToBool - Determines whether this conversion is
140/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000141/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000142/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000143bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000144 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
145 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
146
147 // Note that FromType has not necessarily been transformed by the
148 // array-to-pointer or function-to-pointer implicit conversions, so
149 // check for their presence as well as checking whether FromType is
150 // a pointer.
151 if (ToType->isBooleanType() &&
Douglas Gregor033f56d2008-12-23 00:53:59 +0000152 (FromType->isPointerType() || FromType->isBlockPointerType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000153 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
154 return true;
155
156 return false;
157}
158
Douglas Gregor5c407d92008-10-23 00:40:37 +0000159/// isPointerConversionToVoidPointer - Determines whether this
160/// conversion is a conversion of a pointer to a void pointer. This is
161/// used as part of the ranking of standard conversion sequences (C++
162/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000163bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000164StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000165isPointerConversionToVoidPointer(ASTContext& Context) const {
Douglas Gregor5c407d92008-10-23 00:40:37 +0000166 QualType FromType = QualType::getFromOpaquePtr(FromTypePtr);
167 QualType ToType = QualType::getFromOpaquePtr(ToTypePtr);
168
169 // Note that FromType has not necessarily been transformed by the
170 // array-to-pointer implicit conversion, so check for its presence
171 // and redo the conversion to get a pointer.
172 if (First == ICK_Array_To_Pointer)
173 FromType = Context.getArrayDecayedType(FromType);
174
175 if (Second == ICK_Pointer_Conversion)
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000176 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000182/// DebugPrint - Print this standard conversion sequence to standard
183/// error. Useful for debugging overloading issues.
184void StandardConversionSequence::DebugPrint() const {
185 bool PrintedSomething = false;
186 if (First != ICK_Identity) {
187 fprintf(stderr, "%s", GetImplicitConversionName(First));
188 PrintedSomething = true;
189 }
190
191 if (Second != ICK_Identity) {
192 if (PrintedSomething) {
193 fprintf(stderr, " -> ");
194 }
195 fprintf(stderr, "%s", GetImplicitConversionName(Second));
Douglas Gregor2fe98832008-11-03 19:09:14 +0000196
197 if (CopyConstructor) {
198 fprintf(stderr, " (by copy constructor)");
199 } else if (DirectBinding) {
200 fprintf(stderr, " (direct reference binding)");
201 } else if (ReferenceBinding) {
202 fprintf(stderr, " (reference binding)");
203 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000204 PrintedSomething = true;
205 }
206
207 if (Third != ICK_Identity) {
208 if (PrintedSomething) {
209 fprintf(stderr, " -> ");
210 }
211 fprintf(stderr, "%s", GetImplicitConversionName(Third));
212 PrintedSomething = true;
213 }
214
215 if (!PrintedSomething) {
216 fprintf(stderr, "No conversions required");
217 }
218}
219
220/// DebugPrint - Print this user-defined conversion sequence to standard
221/// error. Useful for debugging overloading issues.
222void UserDefinedConversionSequence::DebugPrint() const {
223 if (Before.First || Before.Second || Before.Third) {
224 Before.DebugPrint();
225 fprintf(stderr, " -> ");
226 }
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000227 fprintf(stderr, "'%s'", ConversionFunction->getNameAsString().c_str());
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000228 if (After.First || After.Second || After.Third) {
229 fprintf(stderr, " -> ");
230 After.DebugPrint();
231 }
232}
233
234/// DebugPrint - Print this implicit conversion sequence to standard
235/// error. Useful for debugging overloading issues.
236void ImplicitConversionSequence::DebugPrint() const {
237 switch (ConversionKind) {
238 case StandardConversion:
239 fprintf(stderr, "Standard conversion: ");
240 Standard.DebugPrint();
241 break;
242 case UserDefinedConversion:
243 fprintf(stderr, "User-defined conversion: ");
244 UserDefined.DebugPrint();
245 break;
246 case EllipsisConversion:
247 fprintf(stderr, "Ellipsis conversion");
248 break;
249 case BadConversion:
250 fprintf(stderr, "Bad conversion");
251 break;
252 }
253
254 fprintf(stderr, "\n");
255}
256
257// IsOverload - Determine whether the given New declaration is an
258// overload of the Old declaration. This routine returns false if New
259// and Old cannot be overloaded, e.g., if they are functions with the
260// same signature (C++ 1.3.10) or if the Old declaration isn't a
261// function (or overload set). When it does return false and Old is an
262// OverloadedFunctionDecl, MatchedDecl will be set to point to the
Mike Stump11289f42009-09-09 15:08:12 +0000263// FunctionDecl that New cannot be overloaded with.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000264//
265// Example: Given the following input:
266//
267// void f(int, float); // #1
268// void f(int, int); // #2
269// int f(int, int); // #3
270//
271// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000272// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000273//
274// When we process #2, Old is a FunctionDecl for #1. By comparing the
275// parameter types, we see that #1 and #2 are overloaded (since they
276// have different signatures), so this routine returns false;
277// MatchedDecl is unchanged.
278//
279// When we process #3, Old is an OverloadedFunctionDecl containing #1
280// and #2. We compare the signatures of #3 to #1 (they're overloaded,
281// so we do nothing) and then #3 to #2. Since the signatures of #3 and
282// #2 are identical (return types of functions are not part of the
283// signature), IsOverload returns false and MatchedDecl will be set to
284// point to the FunctionDecl for #2.
285bool
Mike Stump11289f42009-09-09 15:08:12 +0000286Sema::IsOverload(FunctionDecl *New, Decl* OldD,
287 OverloadedFunctionDecl::function_iterator& MatchedDecl) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000288 if (OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(OldD)) {
289 // Is this new function an overload of every function in the
290 // overload set?
291 OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
292 FuncEnd = Ovl->function_end();
293 for (; Func != FuncEnd; ++Func) {
294 if (!IsOverload(New, *Func, MatchedDecl)) {
295 MatchedDecl = Func;
296 return false;
297 }
298 }
299
300 // This function overloads every function in the overload set.
301 return true;
Douglas Gregorad3f2fc2009-06-25 22:08:12 +0000302 } else if (FunctionTemplateDecl *Old = dyn_cast<FunctionTemplateDecl>(OldD))
303 return IsOverload(New, Old->getTemplatedDecl(), MatchedDecl);
304 else if (FunctionDecl* Old = dyn_cast<FunctionDecl>(OldD)) {
Douglas Gregor23061de2009-06-24 16:50:40 +0000305 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
Mike Stump11289f42009-09-09 15:08:12 +0000306 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
307
Douglas Gregor23061de2009-06-24 16:50:40 +0000308 // C++ [temp.fct]p2:
309 // A function template can be overloaded with other function templates
310 // and with normal (non-template) functions.
311 if ((OldTemplate == 0) != (NewTemplate == 0))
312 return true;
313
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000314 // Is the function New an overload of the function Old?
315 QualType OldQType = Context.getCanonicalType(Old->getType());
316 QualType NewQType = Context.getCanonicalType(New->getType());
317
318 // Compare the signatures (C++ 1.3.10) of the two functions to
319 // determine whether they are overloads. If we find any mismatch
320 // in the signature, they are overloads.
321
322 // If either of these functions is a K&R-style function (no
323 // prototype), then we consider them to have matching signatures.
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000324 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
325 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000326 return false;
327
Douglas Gregor23061de2009-06-24 16:50:40 +0000328 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
329 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000330
331 // The signature of a function includes the types of its
332 // parameters (C++ 1.3.10), which includes the presence or absence
333 // of the ellipsis; see C++ DR 357).
334 if (OldQType != NewQType &&
335 (OldType->getNumArgs() != NewType->getNumArgs() ||
336 OldType->isVariadic() != NewType->isVariadic() ||
337 !std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
338 NewType->arg_type_begin())))
339 return true;
340
Douglas Gregor23061de2009-06-24 16:50:40 +0000341 // C++ [temp.over.link]p4:
Mike Stump11289f42009-09-09 15:08:12 +0000342 // The signature of a function template consists of its function
Douglas Gregor23061de2009-06-24 16:50:40 +0000343 // signature, its return type and its template parameter list. The names
344 // of the template parameters are significant only for establishing the
Mike Stump11289f42009-09-09 15:08:12 +0000345 // relationship between the template parameters and the rest of the
Douglas Gregor23061de2009-06-24 16:50:40 +0000346 // signature.
347 //
348 // We check the return type and template parameter lists for function
349 // templates first; the remaining checks follow.
350 if (NewTemplate &&
Mike Stump11289f42009-09-09 15:08:12 +0000351 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
352 OldTemplate->getTemplateParameters(),
Douglas Gregor23061de2009-06-24 16:50:40 +0000353 false, false, SourceLocation()) ||
354 OldType->getResultType() != NewType->getResultType()))
355 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000356
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000357 // If the function is a class member, its signature includes the
358 // cv-qualifiers (if any) on the function itself.
359 //
360 // As part of this, also check whether one of the member functions
361 // is static, in which case they are not overloads (C++
362 // 13.1p2). While not part of the definition of the signature,
363 // this check is important to determine whether these functions
364 // can be overloaded.
365 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
366 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
Mike Stump11289f42009-09-09 15:08:12 +0000367 if (OldMethod && NewMethod &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000368 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb81897c2008-11-21 15:36:28 +0000369 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000370 return true;
371
372 // The signatures match; this is not an overload.
373 return false;
374 } else {
375 // (C++ 13p1):
376 // Only function declarations can be overloaded; object and type
377 // declarations cannot be overloaded.
378 return false;
379 }
380}
381
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000382/// TryImplicitConversion - Attempt to perform an implicit conversion
383/// from the given expression (Expr) to the given type (ToType). This
384/// function returns an implicit conversion sequence that can be used
385/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000386///
387/// void f(float f);
388/// void g(int i) { f(i); }
389///
390/// this routine would produce an implicit conversion sequence to
391/// describe the initialization of f from i, which will be a standard
392/// conversion sequence containing an lvalue-to-rvalue conversion (C++
393/// 4.1) followed by a floating-integral conversion (C++ 4.9).
394//
395/// Note that this routine only determines how the conversion can be
396/// performed; it does not actually perform the conversion. As such,
397/// it will not produce any diagnostics if no conversion is available,
398/// but will instead return an implicit conversion sequence of kind
399/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000400///
401/// If @p SuppressUserConversions, then user-defined conversions are
402/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000403/// If @p AllowExplicit, then explicit user-defined conversions are
404/// permitted.
Sebastian Redl42e92c42009-04-12 17:16:29 +0000405/// If @p ForceRValue, then overloading is performed as if From was an rvalue,
406/// no matter its actual lvalueness.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000407/// If @p UserCast, the implicit conversion is being done for a user-specified
408/// cast.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000409ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000410Sema::TryImplicitConversion(Expr* From, QualType ToType,
411 bool SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +0000412 bool AllowExplicit, bool ForceRValue,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000413 bool InOverloadResolution,
414 bool UserCast) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000415 ImplicitConversionSequence ICS;
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000416 OverloadCandidateSet Conversions;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000417 OverloadingResult UserDefResult = OR_Success;
Anders Carlsson228eea32009-08-28 15:33:32 +0000418 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard))
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000419 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000420 else if (getLangOptions().CPlusPlus &&
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000421 (UserDefResult = IsUserDefinedConversion(From, ToType,
422 ICS.UserDefined,
Fariborz Jahanian19c73282009-09-15 00:10:11 +0000423 Conversions,
Sebastian Redl42e92c42009-04-12 17:16:29 +0000424 !SuppressUserConversions, AllowExplicit,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +0000425 ForceRValue, UserCast)) == OR_Success) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000426 ICS.ConversionKind = ImplicitConversionSequence::UserDefinedConversion;
Douglas Gregor05379422008-11-03 17:51:48 +0000427 // C++ [over.ics.user]p4:
428 // A conversion of an expression of class type to the same class
429 // type is given Exact Match rank, and a conversion of an
430 // expression of class type to a base class of that type is
431 // given Conversion rank, in spite of the fact that a copy
432 // constructor (i.e., a user-defined conversion function) is
433 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000434 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000435 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000436 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000437 = Context.getCanonicalType(From->getType().getUnqualifiedType());
438 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
439 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000440 // Turn this into a "standard" conversion sequence, so that it
441 // gets ranked with standard conversion sequences.
Douglas Gregor05379422008-11-03 17:51:48 +0000442 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
443 ICS.Standard.setAsIdentityConversion();
444 ICS.Standard.FromTypePtr = From->getType().getAsOpaquePtr();
445 ICS.Standard.ToTypePtr = ToType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000446 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000447 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000448 ICS.Standard.Second = ICK_Derived_To_Base;
449 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000450 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000451
452 // C++ [over.best.ics]p4:
453 // However, when considering the argument of a user-defined
454 // conversion function that is a candidate by 13.3.1.3 when
455 // invoked for the copying of the temporary in the second step
456 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
457 // 13.3.1.6 in all cases, only standard conversion sequences and
458 // ellipsis conversion sequences are allowed.
459 if (SuppressUserConversions &&
460 ICS.ConversionKind == ImplicitConversionSequence::UserDefinedConversion)
461 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000462 } else {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000463 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000464 if (UserDefResult == OR_Ambiguous) {
465 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
466 Cand != Conversions.end(); ++Cand)
467 ICS.ConversionFunctionSet.push_back(Cand->Function);
468 }
469 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000470
471 return ICS;
472}
473
474/// IsStandardConversion - Determines whether there is a standard
475/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
476/// expression From to the type ToType. Standard conversion sequences
477/// only consider non-class types; for conversions that involve class
478/// types, use TryImplicitConversion. If a conversion exists, SCS will
479/// contain the standard conversion sequence required to perform this
480/// conversion and this routine will return true. Otherwise, this
481/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000482bool
483Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000484 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000485 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000486 QualType FromType = From->getType();
487
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000488 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000489 SCS.setAsIdentityConversion();
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000490 SCS.Deprecated = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000491 SCS.IncompatibleObjC = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000492 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000493 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000494
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000495 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000496 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000497 if (FromType->isRecordType() || ToType->isRecordType()) {
498 if (getLangOptions().CPlusPlus)
499 return false;
500
Mike Stump11289f42009-09-09 15:08:12 +0000501 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000502 }
503
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000504 // The first conversion can be an lvalue-to-rvalue conversion,
505 // array-to-pointer conversion, or function-to-pointer conversion
506 // (C++ 4p1).
507
Mike Stump11289f42009-09-09 15:08:12 +0000508 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000509 // An lvalue (3.10) of a non-function, non-array type T can be
510 // converted to an rvalue.
511 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000512 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000513 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000514 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000515 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000516
517 // If T is a non-class type, the type of the rvalue is the
518 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000519 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
520 // just strip the qualifiers because they don't matter.
521
522 // FIXME: Doesn't see through to qualifiers behind a typedef!
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 Gregor26bee0b2008-10-31 16:23:19 +0000680 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000681 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
682 FromType = ToType;
683 CanonFrom = CanonTo;
684 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000685 }
686
687 // If we have not converted the argument type to the parameter type,
688 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000689 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000690 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000691
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000692 SCS.ToTypePtr = FromType.getAsOpaquePtr();
693 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000694}
695
696/// IsIntegralPromotion - Determines whether the conversion from the
697/// expression From (whose potentially-adjusted type is FromType) to
698/// ToType is an integral promotion (C++ 4.5). If so, returns true and
699/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000700bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000701 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000702 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000703 if (!To) {
704 return false;
705 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000706
707 // An rvalue of type char, signed char, unsigned char, short int, or
708 // unsigned short int can be converted to an rvalue of type int if
709 // int can represent all the values of the source type; otherwise,
710 // the source rvalue can be converted to an rvalue of type unsigned
711 // int (C++ 4.5p1).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000712 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000713 if (// We can promote any signed, promotable integer type to an int
714 (FromType->isSignedIntegerType() ||
715 // We can promote any unsigned integer type whose size is
716 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000717 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000718 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000719 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000720 }
721
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000722 return To->getKind() == BuiltinType::UInt;
723 }
724
725 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
726 // can be converted to an rvalue of the first of the following types
727 // that can represent all the values of its underlying type: int,
728 // unsigned int, long, or unsigned long (C++ 4.5p2).
729 if ((FromType->isEnumeralType() || FromType->isWideCharType())
730 && ToType->isIntegerType()) {
731 // Determine whether the type we're converting from is signed or
732 // unsigned.
733 bool FromIsSigned;
734 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall9dd450b2009-09-21 23:43:11 +0000735 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000736 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
737 FromIsSigned = UnderlyingType->isSignedIntegerType();
738 } else {
739 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
740 FromIsSigned = true;
741 }
742
743 // The types we'll try to promote to, in the appropriate
744 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000745 QualType PromoteTypes[6] = {
746 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000747 Context.LongTy, Context.UnsignedLongTy ,
748 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000749 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000750 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000751 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
752 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000753 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000754 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
755 // We found the type that we can promote to. If this is the
756 // type we wanted, we have a promotion. Otherwise, no
757 // promotion.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000758 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000759 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
760 }
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.
John McCall8ccfcb52009-09-24 19:53:00 +0000866 if (CanonToPointee.getQualifiers() == 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(
878 Context.getQualifiedType(CanonToPointee.getUnqualifiedType(), Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +0000879}
880
Mike Stump11289f42009-09-09 15:08:12 +0000881static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +0000882 bool InOverloadResolution,
883 ASTContext &Context) {
884 // Handle value-dependent integral null pointer constants correctly.
885 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
886 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
887 Expr->getType()->isIntegralType())
888 return !InOverloadResolution;
889
Douglas Gregor56751b52009-09-25 04:25:58 +0000890 return Expr->isNullPointerConstant(Context,
891 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
892 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +0000893}
Mike Stump11289f42009-09-09 15:08:12 +0000894
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000895/// IsPointerConversion - Determines whether the conversion of the
896/// expression From, which has the (possibly adjusted) type FromType,
897/// can be converted to the type ToType via a pointer conversion (C++
898/// 4.10). If so, returns true and places the converted type (that
899/// might differ from ToType in its cv-qualifiers at some level) into
900/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +0000901///
Douglas Gregora29dc052008-11-27 01:19:21 +0000902/// This routine also supports conversions to and from block pointers
903/// and conversions with Objective-C's 'id', 'id<protocols...>', and
904/// pointers to interfaces. FIXME: Once we've determined the
905/// appropriate overloading rules for Objective-C, we may want to
906/// split the Objective-C checks into a different routine; however,
907/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +0000908/// conversions, so for now they live here. IncompatibleObjC will be
909/// set if the conversion is an allowed Objective-C conversion that
910/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000911bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000912 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +0000913 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +0000914 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +0000915 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +0000916 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
917 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000918
Mike Stump11289f42009-09-09 15:08:12 +0000919 // Conversion from a null pointer constant to any Objective-C pointer type.
920 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000921 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +0000922 ConvertedType = ToType;
923 return true;
924 }
925
Douglas Gregor231d1c62008-11-27 00:15:41 +0000926 // Blocks: Block pointers can be converted to void*.
927 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000928 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000929 ConvertedType = ToType;
930 return true;
931 }
932 // Blocks: A null pointer constant can be converted to a block
933 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +0000934 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000935 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000936 ConvertedType = ToType;
937 return true;
938 }
939
Sebastian Redl576fd422009-05-10 18:38:11 +0000940 // If the left-hand-side is nullptr_t, the right side can be a null
941 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +0000942 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000943 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +0000944 ConvertedType = ToType;
945 return true;
946 }
947
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000948 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000949 if (!ToTypePtr)
950 return false;
951
952 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +0000953 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000954 ConvertedType = ToType;
955 return true;
956 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000957
Douglas Gregor237f96c2008-11-26 23:31:11 +0000958 // Beyond this point, both types need to be pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000959 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +0000960 if (!FromTypePtr)
961 return false;
962
963 QualType FromPointeeType = FromTypePtr->getPointeeType();
964 QualType ToPointeeType = ToTypePtr->getPointeeType();
965
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000966 // An rvalue of type "pointer to cv T," where T is an object type,
967 // can be converted to an rvalue of type "pointer to cv void" (C++
968 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +0000969 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000970 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +0000971 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000972 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000973 return true;
974 }
975
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000976 // When we're overloading in C, we allow a special kind of pointer
977 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +0000978 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000979 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000980 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000981 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +0000982 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000983 return true;
984 }
985
Douglas Gregor5c407d92008-10-23 00:40:37 +0000986 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +0000987 //
Douglas Gregor5c407d92008-10-23 00:40:37 +0000988 // An rvalue of type "pointer to cv D," where D is a class type,
989 // can be converted to an rvalue of type "pointer to cv B," where
990 // B is a base class (clause 10) of D. If B is an inaccessible
991 // (clause 11) or ambiguous (10.2) base class of D, a program that
992 // necessitates this conversion is ill-formed. The result of the
993 // conversion is a pointer to the base class sub-object of the
994 // derived class object. The null pointer value is converted to
995 // the null pointer value of the destination type.
996 //
Douglas Gregor39c16d42008-10-24 04:54:22 +0000997 // Note that we do not check for ambiguity or inaccessibility
998 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000999 if (getLangOptions().CPlusPlus &&
1000 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001001 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001002 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001003 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001004 ToType, Context);
1005 return true;
1006 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001007
Douglas Gregora119f102008-12-19 19:13:09 +00001008 return false;
1009}
1010
1011/// isObjCPointerConversion - Determines whether this is an
1012/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1013/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001014bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001015 QualType& ConvertedType,
1016 bool &IncompatibleObjC) {
1017 if (!getLangOptions().ObjC1)
1018 return false;
1019
Steve Naroff7cae42b2009-07-10 23:34:53 +00001020 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001021 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001022 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001023 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001024
Steve Naroff7cae42b2009-07-10 23:34:53 +00001025 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001026 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001027 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001028 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001029 ConvertedType = ToType;
1030 return true;
1031 }
1032 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001033 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001034 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001035 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001036 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001037 ConvertedType = ToType;
1038 return true;
1039 }
1040 // Objective C++: We're able to convert from a pointer to an
1041 // interface to a pointer to a different interface.
1042 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1043 ConvertedType = ToType;
1044 return true;
1045 }
1046
1047 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1048 // Okay: this is some kind of implicit downcast of Objective-C
1049 // interfaces, which is permitted. However, we're going to
1050 // complain about it.
1051 IncompatibleObjC = true;
1052 ConvertedType = FromType;
1053 return true;
1054 }
Mike Stump11289f42009-09-09 15:08:12 +00001055 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001056 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001057 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001058 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001059 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001060 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001061 ToPointeeType = ToBlockPtr->getPointeeType();
1062 else
Douglas Gregora119f102008-12-19 19:13:09 +00001063 return false;
1064
Douglas Gregor033f56d2008-12-23 00:53:59 +00001065 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001066 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001067 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001068 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001069 FromPointeeType = FromBlockPtr->getPointeeType();
1070 else
Douglas Gregora119f102008-12-19 19:13:09 +00001071 return false;
1072
Douglas Gregora119f102008-12-19 19:13:09 +00001073 // If we have pointers to pointers, recursively check whether this
1074 // is an Objective-C conversion.
1075 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1076 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1077 IncompatibleObjC)) {
1078 // We always complain about this conversion.
1079 IncompatibleObjC = true;
1080 ConvertedType = ToType;
1081 return true;
1082 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001083 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001084 // differences in the argument and result types are in Objective-C
1085 // pointer conversions. If so, we permit the conversion (but
1086 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001087 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001088 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001089 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001090 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001091 if (FromFunctionType && ToFunctionType) {
1092 // If the function types are exactly the same, this isn't an
1093 // Objective-C pointer conversion.
1094 if (Context.getCanonicalType(FromPointeeType)
1095 == Context.getCanonicalType(ToPointeeType))
1096 return false;
1097
1098 // Perform the quick checks that will tell us whether these
1099 // function types are obviously different.
1100 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1101 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1102 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1103 return false;
1104
1105 bool HasObjCConversion = false;
1106 if (Context.getCanonicalType(FromFunctionType->getResultType())
1107 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1108 // Okay, the types match exactly. Nothing to do.
1109 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1110 ToFunctionType->getResultType(),
1111 ConvertedType, IncompatibleObjC)) {
1112 // Okay, we have an Objective-C pointer conversion.
1113 HasObjCConversion = true;
1114 } else {
1115 // Function types are too different. Abort.
1116 return false;
1117 }
Mike Stump11289f42009-09-09 15:08:12 +00001118
Douglas Gregora119f102008-12-19 19:13:09 +00001119 // Check argument types.
1120 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1121 ArgIdx != NumArgs; ++ArgIdx) {
1122 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1123 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1124 if (Context.getCanonicalType(FromArgType)
1125 == Context.getCanonicalType(ToArgType)) {
1126 // Okay, the types match exactly. Nothing to do.
1127 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1128 ConvertedType, IncompatibleObjC)) {
1129 // Okay, we have an Objective-C pointer conversion.
1130 HasObjCConversion = true;
1131 } else {
1132 // Argument types are too different. Abort.
1133 return false;
1134 }
1135 }
1136
1137 if (HasObjCConversion) {
1138 // We had an Objective-C conversion. Allow this pointer
1139 // conversion, but complain about it.
1140 ConvertedType = ToType;
1141 IncompatibleObjC = true;
1142 return true;
1143 }
1144 }
1145
Sebastian Redl72b597d2009-01-25 19:43:20 +00001146 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001147}
1148
Douglas Gregor39c16d42008-10-24 04:54:22 +00001149/// CheckPointerConversion - Check the pointer conversion from the
1150/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001151/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001152/// conversions for which IsPointerConversion has already returned
1153/// true. It returns true and produces a diagnostic if there was an
1154/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001155bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
1156 CastExpr::CastKind &Kind) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001157 QualType FromType = From->getType();
1158
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001159 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1160 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001161 QualType FromPointeeType = FromPtrType->getPointeeType(),
1162 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001163
Douglas Gregor39c16d42008-10-24 04:54:22 +00001164 if (FromPointeeType->isRecordType() &&
1165 ToPointeeType->isRecordType()) {
1166 // We must have a derived-to-base conversion. Check an
1167 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001168 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1169 From->getExprLoc(),
1170 From->getSourceRange()))
1171 return true;
1172
1173 // The conversion was successful.
1174 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001175 }
1176 }
Mike Stump11289f42009-09-09 15:08:12 +00001177 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001178 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001179 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001180 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001181 // Objective-C++ conversions are always okay.
1182 // FIXME: We should have a different class of conversions for the
1183 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001184 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001185 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001186
Steve Naroff7cae42b2009-07-10 23:34:53 +00001187 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001188 return false;
1189}
1190
Sebastian Redl72b597d2009-01-25 19:43:20 +00001191/// IsMemberPointerConversion - Determines whether the conversion of the
1192/// expression From, which has the (possibly adjusted) type FromType, can be
1193/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1194/// If so, returns true and places the converted type (that might differ from
1195/// ToType in its cv-qualifiers at some level) into ConvertedType.
1196bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001197 QualType ToType,
1198 bool InOverloadResolution,
1199 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001200 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001201 if (!ToTypePtr)
1202 return false;
1203
1204 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001205 if (From->isNullPointerConstant(Context,
1206 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1207 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001208 ConvertedType = ToType;
1209 return true;
1210 }
1211
1212 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001213 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001214 if (!FromTypePtr)
1215 return false;
1216
1217 // A pointer to member of B can be converted to a pointer to member of D,
1218 // where D is derived from B (C++ 4.11p2).
1219 QualType FromClass(FromTypePtr->getClass(), 0);
1220 QualType ToClass(ToTypePtr->getClass(), 0);
1221 // FIXME: What happens when these are dependent? Is this function even called?
1222
1223 if (IsDerivedFrom(ToClass, FromClass)) {
1224 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1225 ToClass.getTypePtr());
1226 return true;
1227 }
1228
1229 return false;
1230}
1231
1232/// CheckMemberPointerConversion - Check the member pointer conversion from the
1233/// expression From to the type ToType. This routine checks for ambiguous or
1234/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1235/// for which IsMemberPointerConversion has already returned true. It returns
1236/// true and produces a diagnostic if there was an error, or returns false
1237/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001238bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Anders Carlssond7923c62009-08-22 23:33:40 +00001239 CastExpr::CastKind &Kind) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001240 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001241 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001242 if (!FromPtrType) {
1243 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001244 assert(From->isNullPointerConstant(Context,
1245 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001246 "Expr must be null pointer constant!");
1247 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001248 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001249 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001250
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001251 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001252 assert(ToPtrType && "No member pointer cast has a target type "
1253 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001254
Sebastian Redled8f2002009-01-28 18:33:18 +00001255 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1256 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001257
Sebastian Redled8f2002009-01-28 18:33:18 +00001258 // FIXME: What about dependent types?
1259 assert(FromClass->isRecordType() && "Pointer into non-class.");
1260 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001261
Douglas Gregor36d1b142009-10-06 17:59:45 +00001262 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1263 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001264 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1265 assert(DerivationOkay &&
1266 "Should not have been called if derivation isn't OK.");
1267 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001268
Sebastian Redled8f2002009-01-28 18:33:18 +00001269 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1270 getUnqualifiedType())) {
1271 // Derivation is ambiguous. Redo the check to find the exact paths.
1272 Paths.clear();
1273 Paths.setRecordingPaths(true);
1274 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1275 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1276 (void)StillOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001277
Sebastian Redled8f2002009-01-28 18:33:18 +00001278 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1279 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1280 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1281 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001282 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001283
Douglas Gregor89ee6822009-02-28 01:32:25 +00001284 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001285 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1286 << FromClass << ToClass << QualType(VBase, 0)
1287 << From->getSourceRange();
1288 return true;
1289 }
1290
Anders Carlssond7923c62009-08-22 23:33:40 +00001291 // Must be a base to derived member conversion.
1292 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001293 return false;
1294}
1295
Douglas Gregor9a657932008-10-21 23:43:52 +00001296/// IsQualificationConversion - Determines whether the conversion from
1297/// an rvalue of type FromType to ToType is a qualification conversion
1298/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001299bool
1300Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001301 FromType = Context.getCanonicalType(FromType);
1302 ToType = Context.getCanonicalType(ToType);
1303
1304 // If FromType and ToType are the same type, this is not a
1305 // qualification conversion.
1306 if (FromType == ToType)
1307 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001308
Douglas Gregor9a657932008-10-21 23:43:52 +00001309 // (C++ 4.4p4):
1310 // A conversion can add cv-qualifiers at levels other than the first
1311 // in multi-level pointers, subject to the following rules: [...]
1312 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001313 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001314 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001315 // Within each iteration of the loop, we check the qualifiers to
1316 // determine if this still looks like a qualification
1317 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001318 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001319 // until there are no more pointers or pointers-to-members left to
1320 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001321 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001322
1323 // -- for every j > 0, if const is in cv 1,j then const is in cv
1324 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001325 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001326 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001327
Douglas Gregor9a657932008-10-21 23:43:52 +00001328 // -- if the cv 1,j and cv 2,j are different, then const is in
1329 // every cv for 0 < k < j.
1330 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001331 && !PreviousToQualsIncludeConst)
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 // Keep track of whether all prior cv-qualifiers in the "to" type
1335 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001336 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001337 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001338 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001339
1340 // We are left with FromType and ToType being the pointee types
1341 // after unwrapping the original FromType and ToType the same number
1342 // of types. If we unwrapped any pointers, and if FromType and
1343 // ToType have the same unqualified type (since we checked
1344 // qualifiers above), then this is a qualification conversion.
1345 return UnwrappedAnyPointer &&
1346 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1347}
1348
Douglas Gregor05155d82009-08-21 23:19:43 +00001349/// \brief Given a function template or function, extract the function template
1350/// declaration (if any) and the underlying function declaration.
1351template<typename T>
1352static void GetFunctionAndTemplate(AnyFunctionDecl Orig, T *&Function,
1353 FunctionTemplateDecl *&FunctionTemplate) {
1354 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(Orig);
1355 if (FunctionTemplate)
1356 Function = cast<T>(FunctionTemplate->getTemplatedDecl());
1357 else
1358 Function = cast<T>(Orig);
1359}
1360
Douglas Gregor576e98c2009-01-30 23:27:23 +00001361/// Determines whether there is a user-defined conversion sequence
1362/// (C++ [over.ics.user]) that converts expression From to the type
1363/// ToType. If such a conversion exists, User will contain the
1364/// user-defined conversion sequence that performs such a conversion
1365/// and this routine will return true. Otherwise, this routine returns
1366/// false and User is unspecified.
1367///
1368/// \param AllowConversionFunctions true if the conversion should
1369/// consider conversion functions at all. If false, only constructors
1370/// will be considered.
1371///
1372/// \param AllowExplicit true if the conversion should consider C++0x
1373/// "explicit" conversion functions as well as non-explicit conversion
1374/// functions (C++0x [class.conv.fct]p2).
Sebastian Redl42e92c42009-04-12 17:16:29 +00001375///
1376/// \param ForceRValue true if the expression should be treated as an rvalue
1377/// for overload resolution.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001378/// \param UserCast true if looking for user defined conversion for a static
1379/// cast.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001380Sema::OverloadingResult Sema::IsUserDefinedConversion(
1381 Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001382 UserDefinedConversionSequence& User,
Fariborz Jahanian19c73282009-09-15 00:10:11 +00001383 OverloadCandidateSet& CandidateSet,
Douglas Gregor576e98c2009-01-30 23:27:23 +00001384 bool AllowConversionFunctions,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001385 bool AllowExplicit, bool ForceRValue,
1386 bool UserCast) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001387 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001388 if (CXXRecordDecl *ToRecordDecl
Douglas Gregor89ee6822009-02-28 01:32:25 +00001389 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1390 // C++ [over.match.ctor]p1:
1391 // When objects of class type are direct-initialized (8.5), or
1392 // copy-initialized from an expression of the same or a
1393 // derived class type (8.5), overload resolution selects the
1394 // constructor. [...] For copy-initialization, the candidate
1395 // functions are all the converting constructors (12.3.1) of
1396 // that class. The argument list is the expression-list within
1397 // the parentheses of the initializer.
Mike Stump11289f42009-09-09 15:08:12 +00001398 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001399 = Context.DeclarationNames.getCXXConstructorName(
1400 Context.getCanonicalType(ToType).getUnqualifiedType());
1401 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001402 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001403 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001404 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001405 // Find the constructor (which may be a template).
1406 CXXConstructorDecl *Constructor = 0;
1407 FunctionTemplateDecl *ConstructorTmpl
1408 = dyn_cast<FunctionTemplateDecl>(*Con);
1409 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001410 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001411 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1412 else
1413 Constructor = cast<CXXConstructorDecl>(*Con);
Mike Stump11289f42009-09-09 15:08:12 +00001414
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001415 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001416 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001417 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001418 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001419 1, CandidateSet,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001420 /*SuppressUserConversions=*/!UserCast,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001421 ForceRValue);
1422 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001423 // Allow one user-defined conversion when user specifies a
1424 // From->ToType conversion via an static cast (c-style, etc).
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001425 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001426 /*SuppressUserConversions=*/!UserCast,
1427 ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001428 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001429 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001430 }
1431 }
1432
Douglas Gregor576e98c2009-01-30 23:27:23 +00001433 if (!AllowConversionFunctions) {
1434 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001435 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1436 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001437 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001438 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001439 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001440 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001441 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001442 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1443 // Add all of the conversion functions as candidates.
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001444 OverloadedFunctionDecl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001445 = FromRecordDecl->getVisibleConversionFunctions();
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001446 for (OverloadedFunctionDecl::function_iterator Func
1447 = Conversions->function_begin();
1448 Func != Conversions->function_end(); ++Func) {
1449 CXXConversionDecl *Conv;
1450 FunctionTemplateDecl *ConvTemplate;
1451 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1452 if (ConvTemplate)
1453 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1454 else
1455 Conv = dyn_cast<CXXConversionDecl>(*Func);
1456
1457 if (AllowExplicit || !Conv->isExplicit()) {
1458 if (ConvTemplate)
1459 AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1460 CandidateSet);
1461 else
1462 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1463 }
1464 }
1465 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001466 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001467
1468 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001469 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001470 case OR_Success:
1471 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001472 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001473 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1474 // C++ [over.ics.user]p1:
1475 // If the user-defined conversion is specified by a
1476 // constructor (12.3.1), the initial standard conversion
1477 // sequence converts the source type to the type required by
1478 // the argument of the constructor.
1479 //
1480 // FIXME: What about ellipsis conversions?
1481 QualType ThisType = Constructor->getThisType(Context);
1482 User.Before = Best->Conversions[0].Standard;
1483 User.ConversionFunction = Constructor;
1484 User.After.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00001485 User.After.FromTypePtr
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001486 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001487 User.After.ToTypePtr = ToType.getAsOpaquePtr();
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001488 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001489 } else if (CXXConversionDecl *Conversion
1490 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1491 // C++ [over.ics.user]p1:
1492 //
1493 // [...] If the user-defined conversion is specified by a
1494 // conversion function (12.3.2), the initial standard
1495 // conversion sequence converts the source type to the
1496 // implicit object parameter of the conversion function.
1497 User.Before = Best->Conversions[0].Standard;
1498 User.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00001499
1500 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001501 // The second standard conversion sequence converts the
1502 // result of the user-defined conversion to the target type
1503 // for the sequence. Since an implicit conversion sequence
1504 // is an initialization, the special rules for
1505 // initialization by user-defined conversion apply when
1506 // selecting the best user-defined conversion for a
1507 // user-defined conversion sequence (see 13.3.3 and
1508 // 13.3.3.1).
1509 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001510 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001511 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001512 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001513 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001514 }
Mike Stump11289f42009-09-09 15:08:12 +00001515
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001516 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001517 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001518 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001519 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001520 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001521
1522 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001523 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001524 }
1525
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001526 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001527}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001528
1529bool
1530Sema::DiagnoseAmbiguousUserDefinedConversion(Expr *From, QualType ToType) {
1531 ImplicitConversionSequence ICS;
1532 OverloadCandidateSet CandidateSet;
1533 OverloadingResult OvResult =
1534 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1535 CandidateSet, true, false, false);
1536 if (OvResult != OR_Ambiguous)
1537 return false;
1538 Diag(From->getSourceRange().getBegin(),
1539 diag::err_typecheck_ambiguous_condition)
1540 << From->getType() << ToType << From->getSourceRange();
1541 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1542 return true;
1543}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001544
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001545/// CompareImplicitConversionSequences - Compare two implicit
1546/// conversion sequences to determine whether one is better than the
1547/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001548ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001549Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1550 const ImplicitConversionSequence& ICS2)
1551{
1552 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1553 // conversion sequences (as defined in 13.3.3.1)
1554 // -- a standard conversion sequence (13.3.3.1.1) is a better
1555 // conversion sequence than a user-defined conversion sequence or
1556 // an ellipsis conversion sequence, and
1557 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1558 // conversion sequence than an ellipsis conversion sequence
1559 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001560 //
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001561 if (ICS1.ConversionKind < ICS2.ConversionKind)
1562 return ImplicitConversionSequence::Better;
1563 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1564 return ImplicitConversionSequence::Worse;
1565
1566 // Two implicit conversion sequences of the same form are
1567 // indistinguishable conversion sequences unless one of the
1568 // following rules apply: (C++ 13.3.3.2p3):
1569 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1570 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
Mike Stump11289f42009-09-09 15:08:12 +00001571 else if (ICS1.ConversionKind ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001572 ImplicitConversionSequence::UserDefinedConversion) {
1573 // User-defined conversion sequence U1 is a better conversion
1574 // sequence than another user-defined conversion sequence U2 if
1575 // they contain the same user-defined conversion function or
1576 // constructor and if the second standard conversion sequence of
1577 // U1 is better than the second standard conversion sequence of
1578 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001579 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001580 ICS2.UserDefined.ConversionFunction)
1581 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1582 ICS2.UserDefined.After);
1583 }
1584
1585 return ImplicitConversionSequence::Indistinguishable;
1586}
1587
1588/// CompareStandardConversionSequences - Compare two standard
1589/// conversion sequences to determine whether one is better than the
1590/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001591ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001592Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1593 const StandardConversionSequence& SCS2)
1594{
1595 // Standard conversion sequence S1 is a better conversion sequence
1596 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1597
1598 // -- S1 is a proper subsequence of S2 (comparing the conversion
1599 // sequences in the canonical form defined by 13.3.3.1.1,
1600 // excluding any Lvalue Transformation; the identity conversion
1601 // sequence is considered to be a subsequence of any
1602 // non-identity conversion sequence) or, if not that,
1603 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1604 // Neither is a proper subsequence of the other. Do nothing.
1605 ;
1606 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1607 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001608 (SCS1.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001609 SCS1.Third == ICK_Identity))
1610 // SCS1 is a proper subsequence of SCS2.
1611 return ImplicitConversionSequence::Better;
1612 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1613 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001614 (SCS2.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001615 SCS2.Third == ICK_Identity))
1616 // SCS2 is a proper subsequence of SCS1.
1617 return ImplicitConversionSequence::Worse;
1618
1619 // -- the rank of S1 is better than the rank of S2 (by the rules
1620 // defined below), or, if not that,
1621 ImplicitConversionRank Rank1 = SCS1.getRank();
1622 ImplicitConversionRank Rank2 = SCS2.getRank();
1623 if (Rank1 < Rank2)
1624 return ImplicitConversionSequence::Better;
1625 else if (Rank2 < Rank1)
1626 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001627
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001628 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1629 // are indistinguishable unless one of the following rules
1630 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001631
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001632 // A conversion that is not a conversion of a pointer, or
1633 // pointer to member, to bool is better than another conversion
1634 // that is such a conversion.
1635 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1636 return SCS2.isPointerConversionToBool()
1637 ? ImplicitConversionSequence::Better
1638 : ImplicitConversionSequence::Worse;
1639
Douglas Gregor5c407d92008-10-23 00:40:37 +00001640 // C++ [over.ics.rank]p4b2:
1641 //
1642 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001643 // conversion of B* to A* is better than conversion of B* to
1644 // void*, and conversion of A* to void* is better than conversion
1645 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001646 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001647 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001648 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001649 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001650 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1651 // Exactly one of the conversion sequences is a conversion to
1652 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001653 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1654 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001655 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1656 // Neither conversion sequence converts to a void pointer; compare
1657 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001658 if (ImplicitConversionSequence::CompareKind DerivedCK
1659 = CompareDerivedToBaseConversions(SCS1, SCS2))
1660 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001661 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1662 // Both conversion sequences are conversions to void
1663 // pointers. Compare the source types to determine if there's an
1664 // inheritance relationship in their sources.
1665 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1666 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1667
1668 // Adjust the types we're converting from via the array-to-pointer
1669 // conversion, if we need to.
1670 if (SCS1.First == ICK_Array_To_Pointer)
1671 FromType1 = Context.getArrayDecayedType(FromType1);
1672 if (SCS2.First == ICK_Array_To_Pointer)
1673 FromType2 = Context.getArrayDecayedType(FromType2);
1674
Mike Stump11289f42009-09-09 15:08:12 +00001675 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001676 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001677 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001678 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001679
1680 if (IsDerivedFrom(FromPointee2, FromPointee1))
1681 return ImplicitConversionSequence::Better;
1682 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1683 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001684
1685 // Objective-C++: If one interface is more specific than the
1686 // other, it is the better one.
John McCall9dd450b2009-09-21 23:43:11 +00001687 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1688 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001689 if (FromIface1 && FromIface1) {
1690 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1691 return ImplicitConversionSequence::Better;
1692 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1693 return ImplicitConversionSequence::Worse;
1694 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001695 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001696
1697 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1698 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001699 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001700 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001701 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001702
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001703 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001704 // C++0x [over.ics.rank]p3b4:
1705 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1706 // implicit object parameter of a non-static member function declared
1707 // without a ref-qualifier, and S1 binds an rvalue reference to an
1708 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001709 // FIXME: We don't know if we're dealing with the implicit object parameter,
1710 // or if the member function in this case has a ref qualifier.
1711 // (Of course, we don't have ref qualifiers yet.)
1712 if (SCS1.RRefBinding != SCS2.RRefBinding)
1713 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1714 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001715
1716 // C++ [over.ics.rank]p3b4:
1717 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1718 // which the references refer are the same type except for
1719 // top-level cv-qualifiers, and the type to which the reference
1720 // initialized by S2 refers is more cv-qualified than the type
1721 // to which the reference initialized by S1 refers.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001722 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1723 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001724 T1 = Context.getCanonicalType(T1);
1725 T2 = Context.getCanonicalType(T2);
1726 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1727 if (T2.isMoreQualifiedThan(T1))
1728 return ImplicitConversionSequence::Better;
1729 else if (T1.isMoreQualifiedThan(T2))
1730 return ImplicitConversionSequence::Worse;
1731 }
1732 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001733
1734 return ImplicitConversionSequence::Indistinguishable;
1735}
1736
1737/// CompareQualificationConversions - Compares two standard conversion
1738/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001739/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1740ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001741Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001742 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001743 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001744 // -- S1 and S2 differ only in their qualification conversion and
1745 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1746 // cv-qualification signature of type T1 is a proper subset of
1747 // the cv-qualification signature of type T2, and S1 is not the
1748 // deprecated string literal array-to-pointer conversion (4.2).
1749 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1750 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1751 return ImplicitConversionSequence::Indistinguishable;
1752
1753 // FIXME: the example in the standard doesn't use a qualification
1754 // conversion (!)
1755 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1756 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1757 T1 = Context.getCanonicalType(T1);
1758 T2 = Context.getCanonicalType(T2);
1759
1760 // If the types are the same, we won't learn anything by unwrapped
1761 // them.
1762 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1763 return ImplicitConversionSequence::Indistinguishable;
1764
Mike Stump11289f42009-09-09 15:08:12 +00001765 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001766 = ImplicitConversionSequence::Indistinguishable;
1767 while (UnwrapSimilarPointerTypes(T1, T2)) {
1768 // Within each iteration of the loop, we check the qualifiers to
1769 // determine if this still looks like a qualification
1770 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001771 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001772 // until there are no more pointers or pointers-to-members left
1773 // to unwrap. This essentially mimics what
1774 // IsQualificationConversion does, but here we're checking for a
1775 // strict subset of qualifiers.
1776 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1777 // The qualifiers are the same, so this doesn't tell us anything
1778 // about how the sequences rank.
1779 ;
1780 else if (T2.isMoreQualifiedThan(T1)) {
1781 // T1 has fewer qualifiers, so it could be the better sequence.
1782 if (Result == ImplicitConversionSequence::Worse)
1783 // Neither has qualifiers that are a subset of the other's
1784 // qualifiers.
1785 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001786
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001787 Result = ImplicitConversionSequence::Better;
1788 } else if (T1.isMoreQualifiedThan(T2)) {
1789 // T2 has fewer qualifiers, so it could be the better sequence.
1790 if (Result == ImplicitConversionSequence::Better)
1791 // Neither has qualifiers that are a subset of the other's
1792 // qualifiers.
1793 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001794
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001795 Result = ImplicitConversionSequence::Worse;
1796 } else {
1797 // Qualifiers are disjoint.
1798 return ImplicitConversionSequence::Indistinguishable;
1799 }
1800
1801 // If the types after this point are equivalent, we're done.
1802 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1803 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001804 }
1805
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001806 // Check that the winning standard conversion sequence isn't using
1807 // the deprecated string literal array to pointer conversion.
1808 switch (Result) {
1809 case ImplicitConversionSequence::Better:
1810 if (SCS1.Deprecated)
1811 Result = ImplicitConversionSequence::Indistinguishable;
1812 break;
1813
1814 case ImplicitConversionSequence::Indistinguishable:
1815 break;
1816
1817 case ImplicitConversionSequence::Worse:
1818 if (SCS2.Deprecated)
1819 Result = ImplicitConversionSequence::Indistinguishable;
1820 break;
1821 }
1822
1823 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001824}
1825
Douglas Gregor5c407d92008-10-23 00:40:37 +00001826/// CompareDerivedToBaseConversions - Compares two standard conversion
1827/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00001828/// various kinds of derived-to-base conversions (C++
1829/// [over.ics.rank]p4b3). As part of these checks, we also look at
1830/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001831ImplicitConversionSequence::CompareKind
1832Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1833 const StandardConversionSequence& SCS2) {
1834 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1835 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1836 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1837 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1838
1839 // Adjust the types we're converting from via the array-to-pointer
1840 // conversion, if we need to.
1841 if (SCS1.First == ICK_Array_To_Pointer)
1842 FromType1 = Context.getArrayDecayedType(FromType1);
1843 if (SCS2.First == ICK_Array_To_Pointer)
1844 FromType2 = Context.getArrayDecayedType(FromType2);
1845
1846 // Canonicalize all of the types.
1847 FromType1 = Context.getCanonicalType(FromType1);
1848 ToType1 = Context.getCanonicalType(ToType1);
1849 FromType2 = Context.getCanonicalType(FromType2);
1850 ToType2 = Context.getCanonicalType(ToType2);
1851
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001852 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00001853 //
1854 // If class B is derived directly or indirectly from class A and
1855 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001856 //
1857 // For Objective-C, we let A, B, and C also be Objective-C
1858 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001859
1860 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00001861 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00001862 SCS2.Second == ICK_Pointer_Conversion &&
1863 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1864 FromType1->isPointerType() && FromType2->isPointerType() &&
1865 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001866 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001867 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001868 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001869 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001870 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001871 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001872 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001873 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001874
John McCall9dd450b2009-09-21 23:43:11 +00001875 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1876 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1877 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
1878 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001879
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001880 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00001881 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1882 if (IsDerivedFrom(ToPointee1, ToPointee2))
1883 return ImplicitConversionSequence::Better;
1884 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1885 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001886
1887 if (ToIface1 && ToIface2) {
1888 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1889 return ImplicitConversionSequence::Better;
1890 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1891 return ImplicitConversionSequence::Worse;
1892 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001893 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001894
1895 // -- conversion of B* to A* is better than conversion of C* to A*,
1896 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1897 if (IsDerivedFrom(FromPointee2, FromPointee1))
1898 return ImplicitConversionSequence::Better;
1899 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1900 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00001901
Douglas Gregor237f96c2008-11-26 23:31:11 +00001902 if (FromIface1 && FromIface2) {
1903 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1904 return ImplicitConversionSequence::Better;
1905 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1906 return ImplicitConversionSequence::Worse;
1907 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001908 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001909 }
1910
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001911 // Compare based on reference bindings.
1912 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1913 SCS1.Second == ICK_Derived_To_Base) {
1914 // -- binding of an expression of type C to a reference of type
1915 // B& is better than binding an expression of type C to a
1916 // reference of type A&,
1917 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1918 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1919 if (IsDerivedFrom(ToType1, ToType2))
1920 return ImplicitConversionSequence::Better;
1921 else if (IsDerivedFrom(ToType2, ToType1))
1922 return ImplicitConversionSequence::Worse;
1923 }
1924
Douglas Gregor2fe98832008-11-03 19:09:14 +00001925 // -- binding of an expression of type B to a reference of type
1926 // A& is better than binding an expression of type C to a
1927 // reference of type A&,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001928 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1929 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1930 if (IsDerivedFrom(FromType2, FromType1))
1931 return ImplicitConversionSequence::Better;
1932 else if (IsDerivedFrom(FromType1, FromType2))
1933 return ImplicitConversionSequence::Worse;
1934 }
1935 }
1936
1937
1938 // FIXME: conversion of A::* to B::* is better than conversion of
1939 // A::* to C::*,
1940
1941 // FIXME: conversion of B::* to C::* is better than conversion of
1942 // A::* to C::*, and
1943
Douglas Gregor2fe98832008-11-03 19:09:14 +00001944 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1945 SCS1.Second == ICK_Derived_To_Base) {
1946 // -- conversion of C to B is better than conversion of C to A,
1947 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1948 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1949 if (IsDerivedFrom(ToType1, ToType2))
1950 return ImplicitConversionSequence::Better;
1951 else if (IsDerivedFrom(ToType2, ToType1))
1952 return ImplicitConversionSequence::Worse;
1953 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001954
Douglas Gregor2fe98832008-11-03 19:09:14 +00001955 // -- conversion of B to A is better than conversion of C to A.
1956 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1957 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1958 if (IsDerivedFrom(FromType2, FromType1))
1959 return ImplicitConversionSequence::Better;
1960 else if (IsDerivedFrom(FromType1, FromType2))
1961 return ImplicitConversionSequence::Worse;
1962 }
1963 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001964
Douglas Gregor5c407d92008-10-23 00:40:37 +00001965 return ImplicitConversionSequence::Indistinguishable;
1966}
1967
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001968/// TryCopyInitialization - Try to copy-initialize a value of type
1969/// ToType from the expression From. Return the implicit conversion
1970/// sequence required to pass this argument, which may be a bad
1971/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00001972/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redl42e92c42009-04-12 17:16:29 +00001973/// do not permit any user-defined conversion sequences. If @p ForceRValue,
1974/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump11289f42009-09-09 15:08:12 +00001975ImplicitConversionSequence
1976Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson20d13322009-08-27 17:37:39 +00001977 bool SuppressUserConversions, bool ForceRValue,
1978 bool InOverloadResolution) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001979 if (ToType->isReferenceType()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001980 ImplicitConversionSequence ICS;
Mike Stump11289f42009-09-09 15:08:12 +00001981 CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00001982 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00001983 SuppressUserConversions,
1984 /*AllowExplicit=*/false,
1985 ForceRValue,
1986 &ICS);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001987 return ICS;
1988 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001989 return TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00001990 SuppressUserConversions,
1991 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00001992 ForceRValue,
1993 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001994 }
1995}
1996
Sebastian Redl42e92c42009-04-12 17:16:29 +00001997/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
1998/// the expression @p From. Returns true (and emits a diagnostic) if there was
1999/// an error, returns false if the initialization succeeded. Elidable should
2000/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2001/// differently in C++0x for this case.
Mike Stump11289f42009-09-09 15:08:12 +00002002bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002003 const char* Flavor, bool Elidable) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002004 if (!getLangOptions().CPlusPlus) {
2005 // In C, argument passing is the same as performing an assignment.
2006 QualType FromType = From->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002007
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002008 AssignConvertType ConvTy =
2009 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00002010 if (ConvTy != Compatible &&
2011 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2012 ConvTy = Compatible;
Mike Stump11289f42009-09-09 15:08:12 +00002013
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002014 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
2015 FromType, From, Flavor);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002016 }
Sebastian Redl42e92c42009-04-12 17:16:29 +00002017
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002018 if (ToType->isReferenceType())
Anders Carlsson271e3a42009-08-27 17:30:43 +00002019 return CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002020 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002021 /*SuppressUserConversions=*/false,
2022 /*AllowExplicit=*/false,
2023 /*ForceRValue=*/false);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002024
Sebastian Redl42e92c42009-04-12 17:16:29 +00002025 if (!PerformImplicitConversion(From, ToType, Flavor,
2026 /*AllowExplicit=*/false, Elidable))
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002027 return false;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002028 if (!DiagnoseAmbiguousUserDefinedConversion(From, ToType))
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002029 return Diag(From->getSourceRange().getBegin(),
2030 diag::err_typecheck_convert_incompatible)
2031 << ToType << From->getType() << Flavor << From->getSourceRange();
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002032 return true;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002033}
2034
Douglas Gregor436424c2008-11-18 23:14:02 +00002035/// TryObjectArgumentInitialization - Try to initialize the object
2036/// parameter of the given member function (@c Method) from the
2037/// expression @p From.
2038ImplicitConversionSequence
2039Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
2040 QualType ClassType = Context.getTypeDeclType(Method->getParent());
John McCall8ccfcb52009-09-24 19:53:00 +00002041 QualType ImplicitParamType
2042 = Context.getCVRQualifiedType(ClassType, Method->getTypeQualifiers());
Douglas Gregor436424c2008-11-18 23:14:02 +00002043
2044 // Set up the conversion sequence as a "bad" conversion, to allow us
2045 // to exit early.
2046 ImplicitConversionSequence ICS;
2047 ICS.Standard.setAsIdentityConversion();
2048 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2049
2050 // We need to have an object of class type.
2051 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002052 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002053 FromType = PT->getPointeeType();
2054
2055 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002056
2057 // The implicit object parmeter is has the type "reference to cv X",
2058 // where X is the class of which the function is a member
2059 // (C++ [over.match.funcs]p4). However, when finding an implicit
2060 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002061 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002062 // (C++ [over.match.funcs]p5). We perform a simplified version of
2063 // reference binding here, that allows class rvalues to bind to
2064 // non-constant references.
2065
2066 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2067 // with the implicit object parameter (C++ [over.match.funcs]p5).
2068 QualType FromTypeCanon = Context.getCanonicalType(FromType);
2069 if (ImplicitParamType.getCVRQualifiers() != FromType.getCVRQualifiers() &&
2070 !ImplicitParamType.isAtLeastAsQualifiedAs(FromType))
2071 return ICS;
2072
2073 // Check that we have either the same type or a derived type. It
2074 // affects the conversion rank.
2075 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2076 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
2077 ICS.Standard.Second = ICK_Identity;
2078 else if (IsDerivedFrom(FromType, ClassType))
2079 ICS.Standard.Second = ICK_Derived_To_Base;
2080 else
2081 return ICS;
2082
2083 // Success. Mark this as a reference binding.
2084 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2085 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2086 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2087 ICS.Standard.ReferenceBinding = true;
2088 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002089 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002090 return ICS;
2091}
2092
2093/// PerformObjectArgumentInitialization - Perform initialization of
2094/// the implicit object parameter for the given Method with the given
2095/// expression.
2096bool
2097Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002098 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002099 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002100 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002101
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002102 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002103 FromRecordType = PT->getPointeeType();
2104 DestType = Method->getThisType(Context);
2105 } else {
2106 FromRecordType = From->getType();
2107 DestType = ImplicitParamRecordType;
2108 }
2109
Mike Stump11289f42009-09-09 15:08:12 +00002110 ImplicitConversionSequence ICS
Douglas Gregor436424c2008-11-18 23:14:02 +00002111 = TryObjectArgumentInitialization(From, Method);
2112 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2113 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002114 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002115 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002116
Douglas Gregor436424c2008-11-18 23:14:02 +00002117 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002118 CheckDerivedToBaseConversion(FromRecordType,
2119 ImplicitParamRecordType,
Douglas Gregor436424c2008-11-18 23:14:02 +00002120 From->getSourceRange().getBegin(),
2121 From->getSourceRange()))
2122 return true;
2123
Mike Stump11289f42009-09-09 15:08:12 +00002124 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson4f4aab22009-08-07 18:45:49 +00002125 /*isLvalue=*/true);
Douglas Gregor436424c2008-11-18 23:14:02 +00002126 return false;
2127}
2128
Douglas Gregor5fb53972009-01-14 15:45:31 +00002129/// TryContextuallyConvertToBool - Attempt to contextually convert the
2130/// expression From to bool (C++0x [conv]p3).
2131ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002132 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002133 // FIXME: Are these flags correct?
2134 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002135 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002136 /*ForceRValue=*/false,
2137 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002138}
2139
2140/// PerformContextuallyConvertToBool - Perform a contextual conversion
2141/// of the expression From to bool (C++0x [conv]p3).
2142bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2143 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2144 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2145 return false;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002146
2147 if (!DiagnoseAmbiguousUserDefinedConversion(From, Context.BoolTy))
2148 return Diag(From->getSourceRange().getBegin(),
2149 diag::err_typecheck_bool_condition)
2150 << From->getType() << From->getSourceRange();
2151 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002152}
2153
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002154/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002155/// candidate functions, using the given function call arguments. If
2156/// @p SuppressUserConversions, then don't allow user-defined
2157/// conversions via constructors or conversion operators.
Sebastian Redl42e92c42009-04-12 17:16:29 +00002158/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2159/// hacky way to implement the overloading rules for elidable copy
2160/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregorcabea402009-09-22 15:41:20 +00002161///
2162/// \para PartialOverloading true if we are performing "partial" overloading
2163/// based on an incomplete set of function arguments. This feature is used by
2164/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002165void
2166Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002167 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002168 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002169 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002170 bool ForceRValue,
2171 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002172 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002173 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002174 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002175 assert(!isa<CXXConversionDecl>(Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002176 "Use AddConversionCandidate for conversion functions");
Mike Stump11289f42009-09-09 15:08:12 +00002177 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002178 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002179
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002180 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002181 if (!isa<CXXConstructorDecl>(Method)) {
2182 // If we get here, it's because we're calling a member function
2183 // that is named without a member access expression (e.g.,
2184 // "this->f") that was either written explicitly or created
2185 // implicitly. This can happen with a qualified call to a member
2186 // function, e.g., X::f(). We use a NULL object as the implied
2187 // object argument (C++ [over.call.func]p3).
Mike Stump11289f42009-09-09 15:08:12 +00002188 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002189 SuppressUserConversions, ForceRValue);
2190 return;
2191 }
2192 // We treat a constructor like a non-member function, since its object
2193 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002194 }
2195
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002196 if (!CandidateSet.isNewCandidate(Function))
2197 return;
2198
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002199 // Add this candidate
2200 CandidateSet.push_back(OverloadCandidate());
2201 OverloadCandidate& Candidate = CandidateSet.back();
2202 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002203 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002204 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002205 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002206
2207 unsigned NumArgsInProto = Proto->getNumArgs();
2208
2209 // (C++ 13.3.2p2): A candidate function having fewer than m
2210 // parameters is viable only if it has an ellipsis in its parameter
2211 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002212 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2213 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002214 Candidate.Viable = false;
2215 return;
2216 }
2217
2218 // (C++ 13.3.2p2): A candidate function having more than m parameters
2219 // is viable only if the (m+1)st parameter has a default argument
2220 // (8.3.6). For the purposes of overload resolution, the
2221 // parameter list is truncated on the right, so that there are
2222 // exactly m parameters.
2223 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002224 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002225 // Not enough arguments.
2226 Candidate.Viable = false;
2227 return;
2228 }
2229
2230 // Determine the implicit conversion sequences for each of the
2231 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002232 Candidate.Conversions.resize(NumArgs);
2233 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2234 if (ArgIdx < NumArgsInProto) {
2235 // (C++ 13.3.2p3): for F to be a viable function, there shall
2236 // exist for each argument an implicit conversion sequence
2237 // (13.3.3.1) that converts that argument to the corresponding
2238 // parameter of F.
2239 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002240 Candidate.Conversions[ArgIdx]
2241 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002242 SuppressUserConversions, ForceRValue,
2243 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002244 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002245 == ImplicitConversionSequence::BadConversion) {
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002246 // 13.3.3.1-p10 If several different sequences of conversions exist that
2247 // each convert the argument to the parameter type, the implicit conversion
2248 // sequence associated with the parameter is defined to be the unique conversion
2249 // sequence designated the ambiguous conversion sequence. For the purpose of
2250 // ranking implicit conversion sequences as described in 13.3.3.2, the ambiguous
2251 // conversion sequence is treated as a user-defined sequence that is
2252 // indistinguishable from any other user-defined conversion sequence
Fariborz Jahanian91ae9fd2009-09-29 17:31:54 +00002253 if (!Candidate.Conversions[ArgIdx].ConversionFunctionSet.empty()) {
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002254 Candidate.Conversions[ArgIdx].ConversionKind =
2255 ImplicitConversionSequence::UserDefinedConversion;
Fariborz Jahanian91ae9fd2009-09-29 17:31:54 +00002256 // Set the conversion function to one of them. As due to ambiguity,
2257 // they carry the same weight and is needed for overload resolution
2258 // later.
2259 Candidate.Conversions[ArgIdx].UserDefined.ConversionFunction =
2260 Candidate.Conversions[ArgIdx].ConversionFunctionSet[0];
2261 }
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002262 else {
2263 Candidate.Viable = false;
2264 break;
2265 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002266 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002267 } else {
2268 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2269 // argument for which there is no corresponding parameter is
2270 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002271 Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002272 = ImplicitConversionSequence::EllipsisConversion;
2273 }
2274 }
2275}
2276
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002277/// \brief Add all of the function declarations in the given function set to
2278/// the overload canddiate set.
2279void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2280 Expr **Args, unsigned NumArgs,
2281 OverloadCandidateSet& CandidateSet,
2282 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002283 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002284 FEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00002285 F != FEnd; ++F) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002286 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2287 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2288 AddMethodCandidate(cast<CXXMethodDecl>(FD),
2289 Args[0], Args + 1, NumArgs - 1,
2290 CandidateSet, SuppressUserConversions);
2291 else
2292 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2293 SuppressUserConversions);
2294 } else {
2295 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2296 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2297 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
2298 AddMethodTemplateCandidate(FunTmpl,
Douglas Gregor89026b52009-06-30 23:57:56 +00002299 /*FIXME: explicit args */false, 0, 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002300 Args[0], Args + 1, NumArgs - 1,
2301 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002302 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002303 else
2304 AddTemplateOverloadCandidate(FunTmpl,
2305 /*FIXME: explicit args */false, 0, 0,
2306 Args, NumArgs, CandidateSet,
2307 SuppressUserConversions);
2308 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002309 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002310}
2311
Douglas Gregor436424c2008-11-18 23:14:02 +00002312/// AddMethodCandidate - Adds the given C++ member function to the set
2313/// of candidate functions, using the given function call arguments
2314/// and the object argument (@c Object). For example, in a call
2315/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2316/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2317/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002318/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2319/// a slightly hacky way to implement the overloading rules for elidable copy
2320/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002321void
Douglas Gregor436424c2008-11-18 23:14:02 +00002322Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2323 Expr **Args, unsigned NumArgs,
2324 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002325 bool SuppressUserConversions, bool ForceRValue) {
2326 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002327 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002328 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002329 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor436424c2008-11-18 23:14:02 +00002330 "Use AddConversionCandidate for conversion functions");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002331 assert(!isa<CXXConstructorDecl>(Method) &&
2332 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002333
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002334 if (!CandidateSet.isNewCandidate(Method))
2335 return;
2336
Douglas Gregor436424c2008-11-18 23:14:02 +00002337 // Add this candidate
2338 CandidateSet.push_back(OverloadCandidate());
2339 OverloadCandidate& Candidate = CandidateSet.back();
2340 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002341 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002342 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002343
2344 unsigned NumArgsInProto = Proto->getNumArgs();
2345
2346 // (C++ 13.3.2p2): A candidate function having fewer than m
2347 // parameters is viable only if it has an ellipsis in its parameter
2348 // list (8.3.5).
2349 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2350 Candidate.Viable = false;
2351 return;
2352 }
2353
2354 // (C++ 13.3.2p2): A candidate function having more than m parameters
2355 // is viable only if the (m+1)st parameter has a default argument
2356 // (8.3.6). For the purposes of overload resolution, the
2357 // parameter list is truncated on the right, so that there are
2358 // exactly m parameters.
2359 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2360 if (NumArgs < MinRequiredArgs) {
2361 // Not enough arguments.
2362 Candidate.Viable = false;
2363 return;
2364 }
2365
2366 Candidate.Viable = true;
2367 Candidate.Conversions.resize(NumArgs + 1);
2368
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002369 if (Method->isStatic() || !Object)
2370 // The implicit object argument is ignored.
2371 Candidate.IgnoreObjectArgument = true;
2372 else {
2373 // Determine the implicit conversion sequence for the object
2374 // parameter.
2375 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
Mike Stump11289f42009-09-09 15:08:12 +00002376 if (Candidate.Conversions[0].ConversionKind
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002377 == ImplicitConversionSequence::BadConversion) {
2378 Candidate.Viable = false;
2379 return;
2380 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002381 }
2382
2383 // Determine the implicit conversion sequences for each of the
2384 // arguments.
2385 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2386 if (ArgIdx < NumArgsInProto) {
2387 // (C++ 13.3.2p3): for F to be a viable function, there shall
2388 // exist for each argument an implicit conversion sequence
2389 // (13.3.3.1) that converts that argument to the corresponding
2390 // parameter of F.
2391 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002392 Candidate.Conversions[ArgIdx + 1]
2393 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002394 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002395 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002396 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002397 == ImplicitConversionSequence::BadConversion) {
2398 Candidate.Viable = false;
2399 break;
2400 }
2401 } else {
2402 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2403 // argument for which there is no corresponding parameter is
2404 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002405 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002406 = ImplicitConversionSequence::EllipsisConversion;
2407 }
2408 }
2409}
2410
Douglas Gregor97628d62009-08-21 00:16:32 +00002411/// \brief Add a C++ member function template as a candidate to the candidate
2412/// set, using template argument deduction to produce an appropriate member
2413/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002414void
Douglas Gregor97628d62009-08-21 00:16:32 +00002415Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2416 bool HasExplicitTemplateArgs,
2417 const TemplateArgument *ExplicitTemplateArgs,
2418 unsigned NumExplicitTemplateArgs,
2419 Expr *Object, Expr **Args, unsigned NumArgs,
2420 OverloadCandidateSet& CandidateSet,
2421 bool SuppressUserConversions,
2422 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002423 if (!CandidateSet.isNewCandidate(MethodTmpl))
2424 return;
2425
Douglas Gregor97628d62009-08-21 00:16:32 +00002426 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002427 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002428 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002429 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002430 // candidate functions in the usual way.113) A given name can refer to one
2431 // or more function templates and also to a set of overloaded non-template
2432 // functions. In such a case, the candidate functions generated from each
2433 // function template are combined with the set of non-template candidate
2434 // functions.
2435 TemplateDeductionInfo Info(Context);
2436 FunctionDecl *Specialization = 0;
2437 if (TemplateDeductionResult Result
2438 = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2439 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2440 Args, NumArgs, Specialization, Info)) {
2441 // FIXME: Record what happened with template argument deduction, so
2442 // that we can give the user a beautiful diagnostic.
2443 (void)Result;
2444 return;
2445 }
Mike Stump11289f42009-09-09 15:08:12 +00002446
Douglas Gregor97628d62009-08-21 00:16:32 +00002447 // Add the function template specialization produced by template argument
2448 // deduction as a candidate.
2449 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002450 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002451 "Specialization is not a member function?");
Mike Stump11289f42009-09-09 15:08:12 +00002452 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002453 CandidateSet, SuppressUserConversions, ForceRValue);
2454}
2455
Douglas Gregor05155d82009-08-21 23:19:43 +00002456/// \brief Add a C++ function template specialization as a candidate
2457/// in the candidate set, using template argument deduction to produce
2458/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002459void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002460Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor89026b52009-06-30 23:57:56 +00002461 bool HasExplicitTemplateArgs,
2462 const TemplateArgument *ExplicitTemplateArgs,
2463 unsigned NumExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002464 Expr **Args, unsigned NumArgs,
2465 OverloadCandidateSet& CandidateSet,
2466 bool SuppressUserConversions,
2467 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002468 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2469 return;
2470
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002471 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002472 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002473 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002474 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002475 // candidate functions in the usual way.113) A given name can refer to one
2476 // or more function templates and also to a set of overloaded non-template
2477 // functions. In such a case, the candidate functions generated from each
2478 // function template are combined with the set of non-template candidate
2479 // functions.
2480 TemplateDeductionInfo Info(Context);
2481 FunctionDecl *Specialization = 0;
2482 if (TemplateDeductionResult Result
Douglas Gregor89026b52009-06-30 23:57:56 +00002483 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2484 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2485 Args, NumArgs, Specialization, Info)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002486 // FIXME: Record what happened with template argument deduction, so
2487 // that we can give the user a beautiful diagnostic.
2488 (void)Result;
2489 return;
2490 }
Mike Stump11289f42009-09-09 15:08:12 +00002491
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002492 // Add the function template specialization produced by template argument
2493 // deduction as a candidate.
2494 assert(Specialization && "Missing function template specialization?");
2495 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2496 SuppressUserConversions, ForceRValue);
2497}
Mike Stump11289f42009-09-09 15:08:12 +00002498
Douglas Gregora1f013e2008-11-07 22:36:19 +00002499/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002500/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002501/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002502/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002503/// (which may or may not be the same type as the type that the
2504/// conversion function produces).
2505void
2506Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2507 Expr *From, QualType ToType,
2508 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002509 assert(!Conversion->getDescribedFunctionTemplate() &&
2510 "Conversion function templates use AddTemplateConversionCandidate");
2511
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002512 if (!CandidateSet.isNewCandidate(Conversion))
2513 return;
2514
Douglas Gregora1f013e2008-11-07 22:36:19 +00002515 // Add this candidate
2516 CandidateSet.push_back(OverloadCandidate());
2517 OverloadCandidate& Candidate = CandidateSet.back();
2518 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002519 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002520 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002521 Candidate.FinalConversion.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00002522 Candidate.FinalConversion.FromTypePtr
Douglas Gregora1f013e2008-11-07 22:36:19 +00002523 = Conversion->getConversionType().getAsOpaquePtr();
2524 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2525
Douglas Gregor436424c2008-11-18 23:14:02 +00002526 // Determine the implicit conversion sequence for the implicit
2527 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002528 Candidate.Viable = true;
2529 Candidate.Conversions.resize(1);
Douglas Gregor436424c2008-11-18 23:14:02 +00002530 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002531 // Conversion functions to a different type in the base class is visible in
2532 // the derived class. So, a derived to base conversion should not participate
2533 // in overload resolution.
2534 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2535 Candidate.Conversions[0].Standard.Second = ICK_Identity;
Mike Stump11289f42009-09-09 15:08:12 +00002536 if (Candidate.Conversions[0].ConversionKind
Douglas Gregora1f013e2008-11-07 22:36:19 +00002537 == ImplicitConversionSequence::BadConversion) {
2538 Candidate.Viable = false;
2539 return;
2540 }
2541
2542 // To determine what the conversion from the result of calling the
2543 // conversion function to the type we're eventually trying to
2544 // convert to (ToType), we need to synthesize a call to the
2545 // conversion function and attempt copy initialization from it. This
2546 // makes sure that we get the right semantics with respect to
2547 // lvalues/rvalues and the type. Fortunately, we can allocate this
2548 // call on the stack and we don't need its arguments to be
2549 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002550 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregora1f013e2008-11-07 22:36:19 +00002551 SourceLocation());
2552 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Anders Carlssona2615922009-07-31 00:48:10 +00002553 CastExpr::CK_Unknown,
Douglas Gregora11693b2008-11-12 17:17:38 +00002554 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002555
2556 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002557 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2558 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002559 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002560 Conversion->getConversionType().getNonReferenceType(),
2561 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002562 ImplicitConversionSequence ICS =
2563 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002564 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002565 /*ForceRValue=*/false,
2566 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002567
Douglas Gregora1f013e2008-11-07 22:36:19 +00002568 switch (ICS.ConversionKind) {
2569 case ImplicitConversionSequence::StandardConversion:
2570 Candidate.FinalConversion = ICS.Standard;
2571 break;
2572
2573 case ImplicitConversionSequence::BadConversion:
2574 Candidate.Viable = false;
2575 break;
2576
2577 default:
Mike Stump11289f42009-09-09 15:08:12 +00002578 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002579 "Can only end up with a standard conversion sequence or failure");
2580 }
2581}
2582
Douglas Gregor05155d82009-08-21 23:19:43 +00002583/// \brief Adds a conversion function template specialization
2584/// candidate to the overload set, using template argument deduction
2585/// to deduce the template arguments of the conversion function
2586/// template from the type that we are converting to (C++
2587/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002588void
Douglas Gregor05155d82009-08-21 23:19:43 +00002589Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2590 Expr *From, QualType ToType,
2591 OverloadCandidateSet &CandidateSet) {
2592 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2593 "Only conversion function templates permitted here");
2594
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002595 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2596 return;
2597
Douglas Gregor05155d82009-08-21 23:19:43 +00002598 TemplateDeductionInfo Info(Context);
2599 CXXConversionDecl *Specialization = 0;
2600 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002601 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002602 Specialization, Info)) {
2603 // FIXME: Record what happened with template argument deduction, so
2604 // that we can give the user a beautiful diagnostic.
2605 (void)Result;
2606 return;
2607 }
Mike Stump11289f42009-09-09 15:08:12 +00002608
Douglas Gregor05155d82009-08-21 23:19:43 +00002609 // Add the conversion function template specialization produced by
2610 // template argument deduction as a candidate.
2611 assert(Specialization && "Missing function template specialization?");
2612 AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2613}
2614
Douglas Gregorab7897a2008-11-19 22:57:39 +00002615/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2616/// converts the given @c Object to a function pointer via the
2617/// conversion function @c Conversion, and then attempts to call it
2618/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2619/// the type of function that we'll eventually be calling.
2620void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002621 const FunctionProtoType *Proto,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002622 Expr *Object, Expr **Args, unsigned NumArgs,
2623 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002624 if (!CandidateSet.isNewCandidate(Conversion))
2625 return;
2626
Douglas Gregorab7897a2008-11-19 22:57:39 +00002627 CandidateSet.push_back(OverloadCandidate());
2628 OverloadCandidate& Candidate = CandidateSet.back();
2629 Candidate.Function = 0;
2630 Candidate.Surrogate = Conversion;
2631 Candidate.Viable = true;
2632 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002633 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002634 Candidate.Conversions.resize(NumArgs + 1);
2635
2636 // Determine the implicit conversion sequence for the implicit
2637 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002638 ImplicitConversionSequence ObjectInit
Douglas Gregorab7897a2008-11-19 22:57:39 +00002639 = TryObjectArgumentInitialization(Object, Conversion);
2640 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2641 Candidate.Viable = false;
2642 return;
2643 }
2644
2645 // The first conversion is actually a user-defined conversion whose
2646 // first conversion is ObjectInit's standard conversion (which is
2647 // effectively a reference binding). Record it as such.
Mike Stump11289f42009-09-09 15:08:12 +00002648 Candidate.Conversions[0].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002649 = ImplicitConversionSequence::UserDefinedConversion;
2650 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2651 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002652 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002653 = Candidate.Conversions[0].UserDefined.Before;
2654 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2655
Mike Stump11289f42009-09-09 15:08:12 +00002656 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00002657 unsigned NumArgsInProto = Proto->getNumArgs();
2658
2659 // (C++ 13.3.2p2): A candidate function having fewer than m
2660 // parameters is viable only if it has an ellipsis in its parameter
2661 // list (8.3.5).
2662 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2663 Candidate.Viable = false;
2664 return;
2665 }
2666
2667 // Function types don't have any default arguments, so just check if
2668 // we have enough arguments.
2669 if (NumArgs < NumArgsInProto) {
2670 // Not enough arguments.
2671 Candidate.Viable = false;
2672 return;
2673 }
2674
2675 // Determine the implicit conversion sequences for each of the
2676 // arguments.
2677 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2678 if (ArgIdx < NumArgsInProto) {
2679 // (C++ 13.3.2p3): for F to be a viable function, there shall
2680 // exist for each argument an implicit conversion sequence
2681 // (13.3.3.1) that converts that argument to the corresponding
2682 // parameter of F.
2683 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002684 Candidate.Conversions[ArgIdx + 1]
2685 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002686 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002687 /*ForceRValue=*/false,
2688 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002689 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002690 == ImplicitConversionSequence::BadConversion) {
2691 Candidate.Viable = false;
2692 break;
2693 }
2694 } else {
2695 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2696 // argument for which there is no corresponding parameter is
2697 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002698 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002699 = ImplicitConversionSequence::EllipsisConversion;
2700 }
2701 }
2702}
2703
Mike Stump87c57ac2009-05-16 07:39:55 +00002704// FIXME: This will eventually be removed, once we've migrated all of the
2705// operator overloading logic over to the scheme used by binary operators, which
2706// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002707void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002708 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00002709 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002710 OverloadCandidateSet& CandidateSet,
2711 SourceRange OpRange) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002712 FunctionSet Functions;
2713
2714 QualType T1 = Args[0]->getType();
2715 QualType T2;
2716 if (NumArgs > 1)
2717 T2 = Args[1]->getType();
2718
2719 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002720 if (S)
2721 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002722 ArgumentDependentLookup(OpName, Args, NumArgs, Functions);
2723 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2724 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
2725 AddBuiltinOperatorCandidates(Op, Args, NumArgs, CandidateSet);
2726}
2727
2728/// \brief Add overload candidates for overloaded operators that are
2729/// member functions.
2730///
2731/// Add the overloaded operator candidates that are member functions
2732/// for the operator Op that was used in an operator expression such
2733/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2734/// CandidateSet will store the added overload candidates. (C++
2735/// [over.match.oper]).
2736void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2737 SourceLocation OpLoc,
2738 Expr **Args, unsigned NumArgs,
2739 OverloadCandidateSet& CandidateSet,
2740 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002741 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2742
2743 // C++ [over.match.oper]p3:
2744 // For a unary operator @ with an operand of a type whose
2745 // cv-unqualified version is T1, and for a binary operator @ with
2746 // a left operand of a type whose cv-unqualified version is T1 and
2747 // a right operand of a type whose cv-unqualified version is T2,
2748 // three sets of candidate functions, designated member
2749 // candidates, non-member candidates and built-in candidates, are
2750 // constructed as follows:
2751 QualType T1 = Args[0]->getType();
2752 QualType T2;
2753 if (NumArgs > 1)
2754 T2 = Args[1]->getType();
2755
2756 // -- If T1 is a class type, the set of member candidates is the
2757 // result of the qualified lookup of T1::operator@
2758 // (13.3.1.1.1); otherwise, the set of member candidates is
2759 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002760 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002761 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00002762 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002763 return;
Mike Stump11289f42009-09-09 15:08:12 +00002764
John McCall9f3059a2009-10-09 21:13:30 +00002765 LookupResult Operators;
2766 LookupQualifiedName(Operators, T1Rec->getDecl(), OpName,
2767 LookupOrdinaryName, false);
Mike Stump11289f42009-09-09 15:08:12 +00002768 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002769 OperEnd = Operators.end();
2770 Oper != OperEnd;
2771 ++Oper)
Mike Stump11289f42009-09-09 15:08:12 +00002772 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Args[0],
Douglas Gregor55297ac2008-12-23 00:26:44 +00002773 Args+1, NumArgs - 1, CandidateSet,
Douglas Gregor436424c2008-11-18 23:14:02 +00002774 /*SuppressUserConversions=*/false);
Douglas Gregor436424c2008-11-18 23:14:02 +00002775 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002776}
2777
Douglas Gregora11693b2008-11-12 17:17:38 +00002778/// AddBuiltinCandidate - Add a candidate for a built-in
2779/// operator. ResultTy and ParamTys are the result and parameter types
2780/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00002781/// arguments being passed to the candidate. IsAssignmentOperator
2782/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00002783/// operator. NumContextualBoolArguments is the number of arguments
2784/// (at the beginning of the argument list) that will be contextually
2785/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00002786void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00002787 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00002788 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002789 bool IsAssignmentOperator,
2790 unsigned NumContextualBoolArguments) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002791 // Add this candidate
2792 CandidateSet.push_back(OverloadCandidate());
2793 OverloadCandidate& Candidate = CandidateSet.back();
2794 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00002795 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002796 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00002797 Candidate.BuiltinTypes.ResultTy = ResultTy;
2798 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2799 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2800
2801 // Determine the implicit conversion sequences for each of the
2802 // arguments.
2803 Candidate.Viable = true;
2804 Candidate.Conversions.resize(NumArgs);
2805 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00002806 // C++ [over.match.oper]p4:
2807 // For the built-in assignment operators, conversions of the
2808 // left operand are restricted as follows:
2809 // -- no temporaries are introduced to hold the left operand, and
2810 // -- no user-defined conversions are applied to the left
2811 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00002812 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00002813 //
2814 // We block these conversions by turning off user-defined
2815 // conversions, since that is the only way that initialization of
2816 // a reference to a non-class type can occur from something that
2817 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002818 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00002819 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00002820 "Contextual conversion to bool requires bool type");
2821 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2822 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002823 Candidate.Conversions[ArgIdx]
2824 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00002825 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00002826 /*ForceRValue=*/false,
2827 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002828 }
Mike Stump11289f42009-09-09 15:08:12 +00002829 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002830 == ImplicitConversionSequence::BadConversion) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002831 Candidate.Viable = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002832 break;
2833 }
Douglas Gregora11693b2008-11-12 17:17:38 +00002834 }
2835}
2836
2837/// BuiltinCandidateTypeSet - A set of types that will be used for the
2838/// candidate operator functions for built-in operators (C++
2839/// [over.built]). The types are separated into pointer types and
2840/// enumeration types.
2841class BuiltinCandidateTypeSet {
2842 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002843 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00002844
2845 /// PointerTypes - The set of pointer types that will be used in the
2846 /// built-in candidates.
2847 TypeSet PointerTypes;
2848
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002849 /// MemberPointerTypes - The set of member pointer types that will be
2850 /// used in the built-in candidates.
2851 TypeSet MemberPointerTypes;
2852
Douglas Gregora11693b2008-11-12 17:17:38 +00002853 /// EnumerationTypes - The set of enumeration types that will be
2854 /// used in the built-in candidates.
2855 TypeSet EnumerationTypes;
2856
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002857 /// Sema - The semantic analysis instance where we are building the
2858 /// candidate type set.
2859 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00002860
Douglas Gregora11693b2008-11-12 17:17:38 +00002861 /// Context - The AST context in which we will build the type sets.
2862 ASTContext &Context;
2863
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002864 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty);
2865 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00002866
2867public:
2868 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002869 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00002870
Mike Stump11289f42009-09-09 15:08:12 +00002871 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002872 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00002873
Douglas Gregor5fb53972009-01-14 15:45:31 +00002874 void AddTypesConvertedFrom(QualType Ty, bool AllowUserConversions,
2875 bool AllowExplicitConversions);
Douglas Gregora11693b2008-11-12 17:17:38 +00002876
2877 /// pointer_begin - First pointer type found;
2878 iterator pointer_begin() { return PointerTypes.begin(); }
2879
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002880 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00002881 iterator pointer_end() { return PointerTypes.end(); }
2882
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002883 /// member_pointer_begin - First member pointer type found;
2884 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2885
2886 /// member_pointer_end - Past the last member pointer type found;
2887 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2888
Douglas Gregora11693b2008-11-12 17:17:38 +00002889 /// enumeration_begin - First enumeration type found;
2890 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2891
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002892 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00002893 iterator enumeration_end() { return EnumerationTypes.end(); }
2894};
2895
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002896/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00002897/// the set of pointer types along with any more-qualified variants of
2898/// that type. For example, if @p Ty is "int const *", this routine
2899/// will add "int const *", "int const volatile *", "int const
2900/// restrict *", and "int const volatile restrict *" to the set of
2901/// pointer types. Returns true if the add of @p Ty itself succeeded,
2902/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00002903///
2904/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002905bool
2906BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty) {
John McCall8ccfcb52009-09-24 19:53:00 +00002907
Douglas Gregora11693b2008-11-12 17:17:38 +00002908 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002909 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00002910 return false;
2911
John McCall8ccfcb52009-09-24 19:53:00 +00002912 const PointerType *PointerTy = Ty->getAs<PointerType>();
2913 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00002914
John McCall8ccfcb52009-09-24 19:53:00 +00002915 QualType PointeeTy = PointerTy->getPointeeType();
2916 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
2917
2918 // Iterate through all strict supersets of BaseCVR.
2919 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
2920 if ((CVR | BaseCVR) != CVR) continue;
2921
2922 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
2923 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00002924 }
2925
2926 return true;
2927}
2928
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002929/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2930/// to the set of pointer types along with any more-qualified variants of
2931/// that type. For example, if @p Ty is "int const *", this routine
2932/// will add "int const *", "int const volatile *", "int const
2933/// restrict *", and "int const volatile restrict *" to the set of
2934/// pointer types. Returns true if the add of @p Ty itself succeeded,
2935/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00002936///
2937/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002938bool
2939BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
2940 QualType Ty) {
2941 // Insert this type.
2942 if (!MemberPointerTypes.insert(Ty))
2943 return false;
2944
John McCall8ccfcb52009-09-24 19:53:00 +00002945 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
2946 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002947
John McCall8ccfcb52009-09-24 19:53:00 +00002948 QualType PointeeTy = PointerTy->getPointeeType();
2949 const Type *ClassTy = PointerTy->getClass();
2950
2951 // Iterate through all strict supersets of the pointee type's CVR
2952 // qualifiers.
2953 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
2954 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
2955 if ((CVR | BaseCVR) != CVR) continue;
2956
2957 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
2958 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002959 }
2960
2961 return true;
2962}
2963
Douglas Gregora11693b2008-11-12 17:17:38 +00002964/// AddTypesConvertedFrom - Add each of the types to which the type @p
2965/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002966/// primarily interested in pointer types and enumeration types. We also
2967/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002968/// AllowUserConversions is true if we should look at the conversion
2969/// functions of a class type, and AllowExplicitConversions if we
2970/// should also include the explicit conversion functions of a class
2971/// type.
Mike Stump11289f42009-09-09 15:08:12 +00002972void
Douglas Gregor5fb53972009-01-14 15:45:31 +00002973BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
2974 bool AllowUserConversions,
2975 bool AllowExplicitConversions) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002976 // Only deal with canonical types.
2977 Ty = Context.getCanonicalType(Ty);
2978
2979 // Look through reference types; they aren't part of the type of an
2980 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002981 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00002982 Ty = RefTy->getPointeeType();
2983
2984 // We don't care about qualifiers on the type.
2985 Ty = Ty.getUnqualifiedType();
2986
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002987 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002988 QualType PointeeTy = PointerTy->getPointeeType();
2989
2990 // Insert our type, and its more-qualified variants, into the set
2991 // of types.
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002992 if (!AddPointerWithMoreQualifiedTypeVariants(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00002993 return;
2994
2995 // Add 'cv void*' to our set of types.
2996 if (!Ty->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002997 QualType QualVoid
John McCall8ccfcb52009-09-24 19:53:00 +00002998 = Context.getCVRQualifiedType(Context.VoidTy,
2999 PointeeTy.getCVRQualifiers());
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003000 AddPointerWithMoreQualifiedTypeVariants(Context.getPointerType(QualVoid));
Douglas Gregora11693b2008-11-12 17:17:38 +00003001 }
3002
3003 // If this is a pointer to a class type, add pointers to its bases
3004 // (with the same level of cv-qualification as the original
3005 // derived class, of course).
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003006 if (const RecordType *PointeeRec = PointeeTy->getAs<RecordType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003007 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(PointeeRec->getDecl());
3008 for (CXXRecordDecl::base_class_iterator Base = ClassDecl->bases_begin();
3009 Base != ClassDecl->bases_end(); ++Base) {
3010 QualType BaseTy = Context.getCanonicalType(Base->getType());
John McCall8ccfcb52009-09-24 19:53:00 +00003011 BaseTy = Context.getCVRQualifiedType(BaseTy.getUnqualifiedType(),
3012 PointeeTy.getCVRQualifiers());
Douglas Gregora11693b2008-11-12 17:17:38 +00003013
3014 // Add the pointer type, recursively, so that we get all of
3015 // the indirect base classes, too.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003016 AddTypesConvertedFrom(Context.getPointerType(BaseTy), false, false);
Douglas Gregora11693b2008-11-12 17:17:38 +00003017 }
3018 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003019 } else if (Ty->isMemberPointerType()) {
3020 // Member pointers are far easier, since the pointee can't be converted.
3021 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3022 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003023 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003024 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003025 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003026 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003027 if (SemaRef.RequireCompleteType(SourceLocation(), Ty, 0)) {
3028 // No conversion functions in incomplete types.
3029 return;
3030 }
Mike Stump11289f42009-09-09 15:08:12 +00003031
Douglas Gregora11693b2008-11-12 17:17:38 +00003032 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003033 OverloadedFunctionDecl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003034 = ClassDecl->getVisibleConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00003035 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregora11693b2008-11-12 17:17:38 +00003036 = Conversions->function_begin();
3037 Func != Conversions->function_end(); ++Func) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003038 CXXConversionDecl *Conv;
3039 FunctionTemplateDecl *ConvTemplate;
3040 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
3041
Mike Stump11289f42009-09-09 15:08:12 +00003042 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003043 // about which builtin types we can convert to.
3044 if (ConvTemplate)
3045 continue;
3046
Douglas Gregor5fb53972009-01-14 15:45:31 +00003047 if (AllowExplicitConversions || !Conv->isExplicit())
3048 AddTypesConvertedFrom(Conv->getConversionType(), false, false);
Douglas Gregora11693b2008-11-12 17:17:38 +00003049 }
3050 }
3051 }
3052}
3053
Douglas Gregor84605ae2009-08-24 13:43:27 +00003054/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3055/// the volatile- and non-volatile-qualified assignment operators for the
3056/// given type to the candidate set.
3057static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3058 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003059 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003060 unsigned NumArgs,
3061 OverloadCandidateSet &CandidateSet) {
3062 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003063
Douglas Gregor84605ae2009-08-24 13:43:27 +00003064 // T& operator=(T&, T)
3065 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3066 ParamTypes[1] = T;
3067 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3068 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003069
Douglas Gregor84605ae2009-08-24 13:43:27 +00003070 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3071 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003072 ParamTypes[0]
3073 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003074 ParamTypes[1] = T;
3075 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003076 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003077 }
3078}
Mike Stump11289f42009-09-09 15:08:12 +00003079
Douglas Gregord08452f2008-11-19 15:42:04 +00003080/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3081/// operator overloads to the candidate set (C++ [over.built]), based
3082/// on the operator @p Op and the arguments given. For example, if the
3083/// operator is a binary '+', this routine might add "int
3084/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003085void
Mike Stump11289f42009-09-09 15:08:12 +00003086Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregord08452f2008-11-19 15:42:04 +00003087 Expr **Args, unsigned NumArgs,
3088 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003089 // The set of "promoted arithmetic types", which are the arithmetic
3090 // types are that preserved by promotion (C++ [over.built]p2). Note
3091 // that the first few of these types are the promoted integral
3092 // types; these types need to be first.
3093 // FIXME: What about complex?
3094 const unsigned FirstIntegralType = 0;
3095 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003096 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003097 LastPromotedIntegralType = 13;
3098 const unsigned FirstPromotedArithmeticType = 7,
3099 LastPromotedArithmeticType = 16;
3100 const unsigned NumArithmeticTypes = 16;
3101 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003102 Context.BoolTy, Context.CharTy, Context.WCharTy,
3103// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003104 Context.SignedCharTy, Context.ShortTy,
3105 Context.UnsignedCharTy, Context.UnsignedShortTy,
3106 Context.IntTy, Context.LongTy, Context.LongLongTy,
3107 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3108 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3109 };
3110
3111 // Find all of the types that the arguments can convert to, but only
3112 // if the operator we're looking at has built-in operator candidates
3113 // that make use of these types.
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003114 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003115 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3116 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003117 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003118 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003119 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003120 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003121 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003122 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
3123 true,
3124 (Op == OO_Exclaim ||
3125 Op == OO_AmpAmp ||
3126 Op == OO_PipePipe));
Douglas Gregora11693b2008-11-12 17:17:38 +00003127 }
3128
3129 bool isComparison = false;
3130 switch (Op) {
3131 case OO_None:
3132 case NUM_OVERLOADED_OPERATORS:
3133 assert(false && "Expected an overloaded operator");
3134 break;
3135
Douglas Gregord08452f2008-11-19 15:42:04 +00003136 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003137 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003138 goto UnaryStar;
3139 else
3140 goto BinaryStar;
3141 break;
3142
3143 case OO_Plus: // '+' is either unary or binary
3144 if (NumArgs == 1)
3145 goto UnaryPlus;
3146 else
3147 goto BinaryPlus;
3148 break;
3149
3150 case OO_Minus: // '-' is either unary or binary
3151 if (NumArgs == 1)
3152 goto UnaryMinus;
3153 else
3154 goto BinaryMinus;
3155 break;
3156
3157 case OO_Amp: // '&' is either unary or binary
3158 if (NumArgs == 1)
3159 goto UnaryAmp;
3160 else
3161 goto BinaryAmp;
3162
3163 case OO_PlusPlus:
3164 case OO_MinusMinus:
3165 // C++ [over.built]p3:
3166 //
3167 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3168 // is either volatile or empty, there exist candidate operator
3169 // functions of the form
3170 //
3171 // VQ T& operator++(VQ T&);
3172 // T operator++(VQ T&, int);
3173 //
3174 // C++ [over.built]p4:
3175 //
3176 // For every pair (T, VQ), where T is an arithmetic type other
3177 // than bool, and VQ is either volatile or empty, there exist
3178 // candidate operator functions of the form
3179 //
3180 // VQ T& operator--(VQ T&);
3181 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003182 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003183 Arith < NumArithmeticTypes; ++Arith) {
3184 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003185 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003186 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003187
3188 // Non-volatile version.
3189 if (NumArgs == 1)
3190 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3191 else
3192 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3193
3194 // Volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00003195 ParamTypes[0]
3196 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
Douglas Gregord08452f2008-11-19 15:42:04 +00003197 if (NumArgs == 1)
3198 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3199 else
3200 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3201 }
3202
3203 // C++ [over.built]p5:
3204 //
3205 // For every pair (T, VQ), where T is a cv-qualified or
3206 // cv-unqualified object type, and VQ is either volatile or
3207 // empty, there exist candidate operator functions of the form
3208 //
3209 // T*VQ& operator++(T*VQ&);
3210 // T*VQ& operator--(T*VQ&);
3211 // T* operator++(T*VQ&, int);
3212 // T* operator--(T*VQ&, int);
3213 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3214 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3215 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003216 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003217 continue;
3218
Mike Stump11289f42009-09-09 15:08:12 +00003219 QualType ParamTypes[2] = {
3220 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003221 };
Mike Stump11289f42009-09-09 15:08:12 +00003222
Douglas Gregord08452f2008-11-19 15:42:04 +00003223 // Without volatile
3224 if (NumArgs == 1)
3225 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3226 else
3227 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3228
3229 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3230 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003231 ParamTypes[0]
3232 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003233 if (NumArgs == 1)
3234 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3235 else
3236 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3237 }
3238 }
3239 break;
3240
3241 UnaryStar:
3242 // C++ [over.built]p6:
3243 // For every cv-qualified or cv-unqualified object type T, there
3244 // exist candidate operator functions of the form
3245 //
3246 // T& operator*(T*);
3247 //
3248 // C++ [over.built]p7:
3249 // For every function type T, there exist candidate operator
3250 // functions of the form
3251 // T& operator*(T*);
3252 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3253 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3254 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003255 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003256 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003257 &ParamTy, Args, 1, CandidateSet);
3258 }
3259 break;
3260
3261 UnaryPlus:
3262 // C++ [over.built]p8:
3263 // For every type T, there exist candidate operator functions of
3264 // the form
3265 //
3266 // T* operator+(T*);
3267 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3268 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3269 QualType ParamTy = *Ptr;
3270 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3271 }
Mike Stump11289f42009-09-09 15:08:12 +00003272
Douglas Gregord08452f2008-11-19 15:42:04 +00003273 // Fall through
3274
3275 UnaryMinus:
3276 // C++ [over.built]p9:
3277 // For every promoted arithmetic type T, there exist candidate
3278 // operator functions of the form
3279 //
3280 // T operator+(T);
3281 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003282 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003283 Arith < LastPromotedArithmeticType; ++Arith) {
3284 QualType ArithTy = ArithmeticTypes[Arith];
3285 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3286 }
3287 break;
3288
3289 case OO_Tilde:
3290 // C++ [over.built]p10:
3291 // For every promoted integral type T, there exist candidate
3292 // operator functions of the form
3293 //
3294 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003295 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003296 Int < LastPromotedIntegralType; ++Int) {
3297 QualType IntTy = ArithmeticTypes[Int];
3298 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3299 }
3300 break;
3301
Douglas Gregora11693b2008-11-12 17:17:38 +00003302 case OO_New:
3303 case OO_Delete:
3304 case OO_Array_New:
3305 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003306 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003307 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003308 break;
3309
3310 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003311 UnaryAmp:
3312 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003313 // C++ [over.match.oper]p3:
3314 // -- For the operator ',', the unary operator '&', or the
3315 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003316 break;
3317
Douglas Gregor84605ae2009-08-24 13:43:27 +00003318 case OO_EqualEqual:
3319 case OO_ExclaimEqual:
3320 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003321 // For every pointer to member type T, there exist candidate operator
3322 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003323 //
3324 // bool operator==(T,T);
3325 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003326 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003327 MemPtr = CandidateTypes.member_pointer_begin(),
3328 MemPtrEnd = CandidateTypes.member_pointer_end();
3329 MemPtr != MemPtrEnd;
3330 ++MemPtr) {
3331 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3332 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3333 }
Mike Stump11289f42009-09-09 15:08:12 +00003334
Douglas Gregor84605ae2009-08-24 13:43:27 +00003335 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003336
Douglas Gregora11693b2008-11-12 17:17:38 +00003337 case OO_Less:
3338 case OO_Greater:
3339 case OO_LessEqual:
3340 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003341 // C++ [over.built]p15:
3342 //
3343 // For every pointer or enumeration type T, there exist
3344 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003345 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003346 // bool operator<(T, T);
3347 // bool operator>(T, T);
3348 // bool operator<=(T, T);
3349 // bool operator>=(T, T);
3350 // bool operator==(T, T);
3351 // bool operator!=(T, T);
3352 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3353 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3354 QualType ParamTypes[2] = { *Ptr, *Ptr };
3355 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3356 }
Mike Stump11289f42009-09-09 15:08:12 +00003357 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003358 = CandidateTypes.enumeration_begin();
3359 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3360 QualType ParamTypes[2] = { *Enum, *Enum };
3361 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3362 }
3363
3364 // Fall through.
3365 isComparison = true;
3366
Douglas Gregord08452f2008-11-19 15:42:04 +00003367 BinaryPlus:
3368 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003369 if (!isComparison) {
3370 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3371
3372 // C++ [over.built]p13:
3373 //
3374 // For every cv-qualified or cv-unqualified object type T
3375 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003376 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003377 // T* operator+(T*, ptrdiff_t);
3378 // T& operator[](T*, ptrdiff_t); [BELOW]
3379 // T* operator-(T*, ptrdiff_t);
3380 // T* operator+(ptrdiff_t, T*);
3381 // T& operator[](ptrdiff_t, T*); [BELOW]
3382 //
3383 // C++ [over.built]p14:
3384 //
3385 // For every T, where T is a pointer to object type, there
3386 // exist candidate operator functions of the form
3387 //
3388 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003389 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003390 = CandidateTypes.pointer_begin();
3391 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3392 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3393
3394 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3395 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3396
3397 if (Op == OO_Plus) {
3398 // T* operator+(ptrdiff_t, T*);
3399 ParamTypes[0] = ParamTypes[1];
3400 ParamTypes[1] = *Ptr;
3401 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3402 } else {
3403 // ptrdiff_t operator-(T, T);
3404 ParamTypes[1] = *Ptr;
3405 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3406 Args, 2, CandidateSet);
3407 }
3408 }
3409 }
3410 // Fall through
3411
Douglas Gregora11693b2008-11-12 17:17:38 +00003412 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003413 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003414 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003415 // C++ [over.built]p12:
3416 //
3417 // For every pair of promoted arithmetic types L and R, there
3418 // exist candidate operator functions of the form
3419 //
3420 // LR operator*(L, R);
3421 // LR operator/(L, R);
3422 // LR operator+(L, R);
3423 // LR operator-(L, R);
3424 // bool operator<(L, R);
3425 // bool operator>(L, R);
3426 // bool operator<=(L, R);
3427 // bool operator>=(L, R);
3428 // bool operator==(L, R);
3429 // bool operator!=(L, R);
3430 //
3431 // where LR is the result of the usual arithmetic conversions
3432 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003433 //
3434 // C++ [over.built]p24:
3435 //
3436 // For every pair of promoted arithmetic types L and R, there exist
3437 // candidate operator functions of the form
3438 //
3439 // LR operator?(bool, L, R);
3440 //
3441 // where LR is the result of the usual arithmetic conversions
3442 // between types L and R.
3443 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003444 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003445 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003446 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003447 Right < LastPromotedArithmeticType; ++Right) {
3448 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003449 QualType Result
3450 = isComparison
3451 ? Context.BoolTy
3452 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003453 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3454 }
3455 }
3456 break;
3457
3458 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003459 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003460 case OO_Caret:
3461 case OO_Pipe:
3462 case OO_LessLess:
3463 case OO_GreaterGreater:
3464 // C++ [over.built]p17:
3465 //
3466 // For every pair of promoted integral types L and R, there
3467 // exist candidate operator functions of the form
3468 //
3469 // LR operator%(L, R);
3470 // LR operator&(L, R);
3471 // LR operator^(L, R);
3472 // LR operator|(L, R);
3473 // L operator<<(L, R);
3474 // L operator>>(L, R);
3475 //
3476 // where LR is the result of the usual arithmetic conversions
3477 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003478 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003479 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003480 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003481 Right < LastPromotedIntegralType; ++Right) {
3482 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3483 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3484 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003485 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003486 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3487 }
3488 }
3489 break;
3490
3491 case OO_Equal:
3492 // C++ [over.built]p20:
3493 //
3494 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003495 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003496 // empty, there exist candidate operator functions of the form
3497 //
3498 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003499 for (BuiltinCandidateTypeSet::iterator
3500 Enum = CandidateTypes.enumeration_begin(),
3501 EnumEnd = CandidateTypes.enumeration_end();
3502 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003503 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003504 CandidateSet);
3505 for (BuiltinCandidateTypeSet::iterator
3506 MemPtr = CandidateTypes.member_pointer_begin(),
3507 MemPtrEnd = CandidateTypes.member_pointer_end();
3508 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003509 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003510 CandidateSet);
3511 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003512
3513 case OO_PlusEqual:
3514 case OO_MinusEqual:
3515 // C++ [over.built]p19:
3516 //
3517 // For every pair (T, VQ), where T is any type and VQ is either
3518 // volatile or empty, there exist candidate operator functions
3519 // of the form
3520 //
3521 // T*VQ& operator=(T*VQ&, T*);
3522 //
3523 // C++ [over.built]p21:
3524 //
3525 // For every pair (T, VQ), where T is a cv-qualified or
3526 // cv-unqualified object type and VQ is either volatile or
3527 // empty, there exist candidate operator functions of the form
3528 //
3529 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3530 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3531 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3532 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3533 QualType ParamTypes[2];
3534 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3535
3536 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003537 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003538 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3539 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003540
Douglas Gregord08452f2008-11-19 15:42:04 +00003541 if (!Context.getCanonicalType(*Ptr).isVolatileQualified()) {
3542 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00003543 ParamTypes[0]
3544 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00003545 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3546 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003547 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003548 }
3549 // Fall through.
3550
3551 case OO_StarEqual:
3552 case OO_SlashEqual:
3553 // C++ [over.built]p18:
3554 //
3555 // For every triple (L, VQ, R), where L is an arithmetic type,
3556 // VQ is either volatile or empty, and R is a promoted
3557 // arithmetic type, there exist candidate operator functions of
3558 // the form
3559 //
3560 // VQ L& operator=(VQ L&, R);
3561 // VQ L& operator*=(VQ L&, R);
3562 // VQ L& operator/=(VQ L&, R);
3563 // VQ L& operator+=(VQ L&, R);
3564 // VQ L& operator-=(VQ L&, R);
3565 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003566 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003567 Right < LastPromotedArithmeticType; ++Right) {
3568 QualType ParamTypes[2];
3569 ParamTypes[1] = ArithmeticTypes[Right];
3570
3571 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003572 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003573 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3574 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003575
3576 // Add this built-in operator as a candidate (VQ is 'volatile').
John McCall8ccfcb52009-09-24 19:53:00 +00003577 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003578 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003579 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3580 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003581 }
3582 }
3583 break;
3584
3585 case OO_PercentEqual:
3586 case OO_LessLessEqual:
3587 case OO_GreaterGreaterEqual:
3588 case OO_AmpEqual:
3589 case OO_CaretEqual:
3590 case OO_PipeEqual:
3591 // C++ [over.built]p22:
3592 //
3593 // For every triple (L, VQ, R), where L is an integral type, VQ
3594 // is either volatile or empty, and R is a promoted integral
3595 // type, there exist candidate operator functions of the form
3596 //
3597 // VQ L& operator%=(VQ L&, R);
3598 // VQ L& operator<<=(VQ L&, R);
3599 // VQ L& operator>>=(VQ L&, R);
3600 // VQ L& operator&=(VQ L&, R);
3601 // VQ L& operator^=(VQ L&, R);
3602 // VQ L& operator|=(VQ L&, R);
3603 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003604 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003605 Right < LastPromotedIntegralType; ++Right) {
3606 QualType ParamTypes[2];
3607 ParamTypes[1] = ArithmeticTypes[Right];
3608
3609 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003610 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003611 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3612
3613 // Add this built-in operator as a candidate (VQ is 'volatile').
3614 ParamTypes[0] = ArithmeticTypes[Left];
John McCall8ccfcb52009-09-24 19:53:00 +00003615 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003616 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003617 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3618 }
3619 }
3620 break;
3621
Douglas Gregord08452f2008-11-19 15:42:04 +00003622 case OO_Exclaim: {
3623 // C++ [over.operator]p23:
3624 //
3625 // There also exist candidate operator functions of the form
3626 //
Mike Stump11289f42009-09-09 15:08:12 +00003627 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00003628 // bool operator&&(bool, bool); [BELOW]
3629 // bool operator||(bool, bool); [BELOW]
3630 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003631 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3632 /*IsAssignmentOperator=*/false,
3633 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003634 break;
3635 }
3636
Douglas Gregora11693b2008-11-12 17:17:38 +00003637 case OO_AmpAmp:
3638 case OO_PipePipe: {
3639 // C++ [over.operator]p23:
3640 //
3641 // There also exist candidate operator functions of the form
3642 //
Douglas Gregord08452f2008-11-19 15:42:04 +00003643 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00003644 // bool operator&&(bool, bool);
3645 // bool operator||(bool, bool);
3646 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00003647 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3648 /*IsAssignmentOperator=*/false,
3649 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00003650 break;
3651 }
3652
3653 case OO_Subscript:
3654 // C++ [over.built]p13:
3655 //
3656 // For every cv-qualified or cv-unqualified object type T there
3657 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003658 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003659 // T* operator+(T*, ptrdiff_t); [ABOVE]
3660 // T& operator[](T*, ptrdiff_t);
3661 // T* operator-(T*, ptrdiff_t); [ABOVE]
3662 // T* operator+(ptrdiff_t, T*); [ABOVE]
3663 // T& operator[](ptrdiff_t, T*);
3664 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3665 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3666 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003667 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003668 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00003669
3670 // T& operator[](T*, ptrdiff_t)
3671 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3672
3673 // T& operator[](ptrdiff_t, T*);
3674 ParamTypes[0] = ParamTypes[1];
3675 ParamTypes[1] = *Ptr;
3676 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3677 }
3678 break;
3679
3680 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003681 // C++ [over.built]p11:
3682 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
3683 // C1 is the same type as C2 or is a derived class of C2, T is an object
3684 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
3685 // there exist candidate operator functions of the form
3686 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
3687 // where CV12 is the union of CV1 and CV2.
3688 {
3689 for (BuiltinCandidateTypeSet::iterator Ptr =
3690 CandidateTypes.pointer_begin();
3691 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3692 QualType C1Ty = (*Ptr);
3693 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003694 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003695 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003696 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003697 if (!isa<RecordType>(C1))
3698 continue;
3699 }
3700 for (BuiltinCandidateTypeSet::iterator
3701 MemPtr = CandidateTypes.member_pointer_begin(),
3702 MemPtrEnd = CandidateTypes.member_pointer_end();
3703 MemPtr != MemPtrEnd; ++MemPtr) {
3704 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
3705 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00003706 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003707 if (C1 != C2 && !IsDerivedFrom(C1, C2))
3708 break;
3709 QualType ParamTypes[2] = { *Ptr, *MemPtr };
3710 // build CV12 T&
3711 QualType T = mptr->getPointeeType();
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003712 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003713 QualType ResultTy = Context.getLValueReferenceType(T);
3714 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3715 }
3716 }
3717 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003718 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003719
3720 case OO_Conditional:
3721 // Note that we don't consider the first argument, since it has been
3722 // contextually converted to bool long ago. The candidates below are
3723 // therefore added as binary.
3724 //
3725 // C++ [over.built]p24:
3726 // For every type T, where T is a pointer or pointer-to-member type,
3727 // there exist candidate operator functions of the form
3728 //
3729 // T operator?(bool, T, T);
3730 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00003731 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3732 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3733 QualType ParamTypes[2] = { *Ptr, *Ptr };
3734 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3735 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003736 for (BuiltinCandidateTypeSet::iterator Ptr =
3737 CandidateTypes.member_pointer_begin(),
3738 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3739 QualType ParamTypes[2] = { *Ptr, *Ptr };
3740 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3741 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003742 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00003743 }
3744}
3745
Douglas Gregore254f902009-02-04 00:32:51 +00003746/// \brief Add function candidates found via argument-dependent lookup
3747/// to the set of overloading candidates.
3748///
3749/// This routine performs argument-dependent name lookup based on the
3750/// given function name (which may also be an operator name) and adds
3751/// all of the overload candidates found by ADL to the overload
3752/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00003753void
Douglas Gregore254f902009-02-04 00:32:51 +00003754Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3755 Expr **Args, unsigned NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00003756 bool HasExplicitTemplateArgs,
3757 const TemplateArgument *ExplicitTemplateArgs,
3758 unsigned NumExplicitTemplateArgs,
3759 OverloadCandidateSet& CandidateSet,
3760 bool PartialOverloading) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003761 FunctionSet Functions;
Douglas Gregore254f902009-02-04 00:32:51 +00003762
Douglas Gregorcabea402009-09-22 15:41:20 +00003763 // FIXME: Should we be trafficking in canonical function decls throughout?
3764
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003765 // Record all of the function candidates that we've already
3766 // added to the overload set, so that we don't add those same
3767 // candidates a second time.
3768 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3769 CandEnd = CandidateSet.end();
3770 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003771 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003772 Functions.insert(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003773 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3774 Functions.insert(FunTmpl);
3775 }
Douglas Gregore254f902009-02-04 00:32:51 +00003776
Douglas Gregorcabea402009-09-22 15:41:20 +00003777 // FIXME: Pass in the explicit template arguments?
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003778 ArgumentDependentLookup(Name, Args, NumArgs, Functions);
Douglas Gregore254f902009-02-04 00:32:51 +00003779
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003780 // Erase all of the candidates we already knew about.
3781 // FIXME: This is suboptimal. Is there a better way?
3782 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3783 CandEnd = CandidateSet.end();
3784 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003785 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003786 Functions.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003787 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3788 Functions.erase(FunTmpl);
3789 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003790
3791 // For each of the ADL candidates we found, add it to the overload
3792 // set.
3793 for (FunctionSet::iterator Func = Functions.begin(),
3794 FuncEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00003795 Func != FuncEnd; ++Func) {
Douglas Gregorcabea402009-09-22 15:41:20 +00003796 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
3797 if (HasExplicitTemplateArgs)
3798 continue;
3799
3800 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
3801 false, false, PartialOverloading);
3802 } else
Mike Stump11289f42009-09-09 15:08:12 +00003803 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregorcabea402009-09-22 15:41:20 +00003804 HasExplicitTemplateArgs,
3805 ExplicitTemplateArgs,
3806 NumExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003807 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00003808 }
Douglas Gregore254f902009-02-04 00:32:51 +00003809}
3810
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003811/// isBetterOverloadCandidate - Determines whether the first overload
3812/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00003813bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003814Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump11289f42009-09-09 15:08:12 +00003815 const OverloadCandidate& Cand2) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003816 // Define viable functions to be better candidates than non-viable
3817 // functions.
3818 if (!Cand2.Viable)
3819 return Cand1.Viable;
3820 else if (!Cand1.Viable)
3821 return false;
3822
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003823 // C++ [over.match.best]p1:
3824 //
3825 // -- if F is a static member function, ICS1(F) is defined such
3826 // that ICS1(F) is neither better nor worse than ICS1(G) for
3827 // any function G, and, symmetrically, ICS1(G) is neither
3828 // better nor worse than ICS1(F).
3829 unsigned StartArg = 0;
3830 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3831 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003832
Douglas Gregord3cb3562009-07-07 23:38:56 +00003833 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00003834 // A viable function F1 is defined to be a better function than another
3835 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00003836 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003837 unsigned NumArgs = Cand1.Conversions.size();
3838 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3839 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003840 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003841 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3842 Cand2.Conversions[ArgIdx])) {
3843 case ImplicitConversionSequence::Better:
3844 // Cand1 has a better conversion sequence.
3845 HasBetterConversion = true;
3846 break;
3847
3848 case ImplicitConversionSequence::Worse:
3849 // Cand1 can't be better than Cand2.
3850 return false;
3851
3852 case ImplicitConversionSequence::Indistinguishable:
3853 // Do nothing.
3854 break;
3855 }
3856 }
3857
Mike Stump11289f42009-09-09 15:08:12 +00003858 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00003859 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003860 if (HasBetterConversion)
3861 return true;
3862
Mike Stump11289f42009-09-09 15:08:12 +00003863 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00003864 // specialization, or, if not that,
3865 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
3866 Cand2.Function && Cand2.Function->getPrimaryTemplate())
3867 return true;
Mike Stump11289f42009-09-09 15:08:12 +00003868
3869 // -- F1 and F2 are function template specializations, and the function
3870 // template for F1 is more specialized than the template for F2
3871 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00003872 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00003873 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
3874 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00003875 if (FunctionTemplateDecl *BetterTemplate
3876 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
3877 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor6010da02009-09-14 23:02:14 +00003878 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
3879 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00003880 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003881
Douglas Gregora1f013e2008-11-07 22:36:19 +00003882 // -- the context is an initialization by user-defined conversion
3883 // (see 8.5, 13.3.1.5) and the standard conversion sequence
3884 // from the return type of F1 to the destination type (i.e.,
3885 // the type of the entity being initialized) is a better
3886 // conversion sequence than the standard conversion sequence
3887 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00003888 if (Cand1.Function && Cand2.Function &&
3889 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003890 isa<CXXConversionDecl>(Cand2.Function)) {
3891 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
3892 Cand2.FinalConversion)) {
3893 case ImplicitConversionSequence::Better:
3894 // Cand1 has a better conversion sequence.
3895 return true;
3896
3897 case ImplicitConversionSequence::Worse:
3898 // Cand1 can't be better than Cand2.
3899 return false;
3900
3901 case ImplicitConversionSequence::Indistinguishable:
3902 // Do nothing
3903 break;
3904 }
3905 }
3906
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003907 return false;
3908}
3909
Mike Stump11289f42009-09-09 15:08:12 +00003910/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003911/// within an overload candidate set.
3912///
3913/// \param CandidateSet the set of candidate functions.
3914///
3915/// \param Loc the location of the function name (or operator symbol) for
3916/// which overload resolution occurs.
3917///
Mike Stump11289f42009-09-09 15:08:12 +00003918/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003919/// function, Best points to the candidate function found.
3920///
3921/// \returns The result of overload resolution.
Mike Stump11289f42009-09-09 15:08:12 +00003922Sema::OverloadingResult
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003923Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003924 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00003925 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003926 // Find the best viable function.
3927 Best = CandidateSet.end();
3928 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3929 Cand != CandidateSet.end(); ++Cand) {
3930 if (Cand->Viable) {
3931 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
3932 Best = Cand;
3933 }
3934 }
3935
3936 // If we didn't find any viable functions, abort.
3937 if (Best == CandidateSet.end())
3938 return OR_No_Viable_Function;
3939
3940 // Make sure that this function is better than every other viable
3941 // function. If not, we have an ambiguity.
3942 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3943 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00003944 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003945 Cand != Best &&
Douglas Gregorab7897a2008-11-19 22:57:39 +00003946 !isBetterOverloadCandidate(*Best, *Cand)) {
3947 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003948 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003949 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003950 }
Mike Stump11289f42009-09-09 15:08:12 +00003951
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003952 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00003953 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00003954 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003955 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00003956 return OR_Deleted;
3957
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003958 // C++ [basic.def.odr]p2:
3959 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00003960 // when referred to from a potentially-evaluated expression. [Note: this
3961 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00003962 // (clause 13), user-defined conversions (12.3.2), allocation function for
3963 // placement new (5.3.4), as well as non-default initialization (8.5).
3964 if (Best->Function)
3965 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003966 return OR_Success;
3967}
3968
3969/// PrintOverloadCandidates - When overload resolution fails, prints
3970/// diagnostic messages containing the candidates in the candidate
3971/// set. If OnlyViable is true, only viable candidates will be printed.
Mike Stump11289f42009-09-09 15:08:12 +00003972void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003973Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00003974 bool OnlyViable,
3975 BinaryOperator::Opcode Opc,
3976 SourceLocation OpLoc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003977 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3978 LastCand = CandidateSet.end();
3979 for (; Cand != LastCand; ++Cand) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003980 if (Cand->Viable || !OnlyViable) {
3981 if (Cand->Function) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003982 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00003983 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00003984 // Deleted or "unavailable" function.
3985 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
3986 << Cand->Function->isDeleted();
Douglas Gregor4fb9cde8e2009-09-15 20:11:42 +00003987 } else if (FunctionTemplateDecl *FunTmpl
3988 = Cand->Function->getPrimaryTemplate()) {
3989 // Function template specialization
3990 // FIXME: Give a better reason!
3991 Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate)
3992 << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
3993 *Cand->Function->getTemplateSpecializationArgs());
Douglas Gregor171c45a2009-02-18 21:56:37 +00003994 } else {
3995 // Normal function
Fariborz Jahanian21ccf062009-09-23 00:58:07 +00003996 bool errReported = false;
3997 if (!Cand->Viable && Cand->Conversions.size() > 0) {
3998 for (int i = Cand->Conversions.size()-1; i >= 0; i--) {
3999 const ImplicitConversionSequence &Conversion =
4000 Cand->Conversions[i];
4001 if ((Conversion.ConversionKind !=
4002 ImplicitConversionSequence::BadConversion) ||
4003 Conversion.ConversionFunctionSet.size() == 0)
4004 continue;
4005 Diag(Cand->Function->getLocation(),
4006 diag::err_ovl_candidate_not_viable) << (i+1);
4007 errReported = true;
4008 for (int j = Conversion.ConversionFunctionSet.size()-1;
4009 j >= 0; j--) {
4010 FunctionDecl *Func = Conversion.ConversionFunctionSet[j];
4011 Diag(Func->getLocation(), diag::err_ovl_candidate);
4012 }
4013 }
4014 }
4015 if (!errReported)
4016 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor171c45a2009-02-18 21:56:37 +00004017 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00004018 } else if (Cand->IsSurrogate) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004019 // Desugar the type of the surrogate down to a function type,
4020 // retaining as many typedefs as possible while still showing
4021 // the function type (and, therefore, its parameter types).
4022 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004023 bool isLValueReference = false;
4024 bool isRValueReference = false;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004025 bool isPointer = false;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004026 if (const LValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004027 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004028 FnType = FnTypeRef->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004029 isLValueReference = true;
4030 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004031 FnType->getAs<RValueReferenceType>()) {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004032 FnType = FnTypeRef->getPointeeType();
4033 isRValueReference = true;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004034 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004035 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004036 FnType = FnTypePtr->getPointeeType();
4037 isPointer = true;
4038 }
4039 // Desugar down to a function type.
John McCall9dd450b2009-09-21 23:43:11 +00004040 FnType = QualType(FnType->getAs<FunctionType>(), 0);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004041 // Reconstruct the pointer/reference as appropriate.
4042 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004043 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
4044 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004045
Douglas Gregorab7897a2008-11-19 22:57:39 +00004046 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004047 << FnType;
Douglas Gregor66950a32009-09-30 21:46:01 +00004048 } else if (OnlyViable) {
Fariborz Jahanian0fe5e032009-10-09 17:09:58 +00004049 assert(Cand->Conversions.size() == 2 &&
4050 "builtin-binary-operator-not-binary");
4051 Diag(OpLoc, diag::err_ovl_builtin_candidate)
4052 << Cand->BuiltinTypes.ParamTypes[0]
4053 << Cand->BuiltinTypes.ParamTypes[1]
4054 << BinaryOperator::getOpcodeStr(Opc);
Douglas Gregora11693b2008-11-12 17:17:38 +00004055 }
4056 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004057 }
4058}
4059
Douglas Gregorcd695e52008-11-10 20:40:00 +00004060/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4061/// an overloaded function (C++ [over.over]), where @p From is an
4062/// expression with overloaded function type and @p ToType is the type
4063/// we're trying to resolve to. For example:
4064///
4065/// @code
4066/// int f(double);
4067/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00004068///
Douglas Gregorcd695e52008-11-10 20:40:00 +00004069/// int (*pfd)(double) = f; // selects f(double)
4070/// @endcode
4071///
4072/// This routine returns the resulting FunctionDecl if it could be
4073/// resolved, and NULL otherwise. When @p Complain is true, this
4074/// routine will emit diagnostics if there is an error.
4075FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004076Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00004077 bool Complain) {
4078 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004079 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004080 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004081 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004082 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00004083 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004084 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004085 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004086 FunctionType = MemTypePtr->getPointeeType();
4087 IsMember = true;
4088 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004089
4090 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00004091 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00004092 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004093 return 0;
4094
4095 // Find the actual overloaded function declaration.
4096 OverloadedFunctionDecl *Ovl = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004097
Douglas Gregorcd695e52008-11-10 20:40:00 +00004098 // C++ [over.over]p1:
4099 // [...] [Note: any redundant set of parentheses surrounding the
4100 // overloaded function name is ignored (5.1). ]
4101 Expr *OvlExpr = From->IgnoreParens();
4102
4103 // C++ [over.over]p1:
4104 // [...] The overloaded function name can be preceded by the &
4105 // operator.
4106 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4107 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4108 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4109 }
4110
4111 // Try to dig out the overloaded function.
Douglas Gregor9b146582009-07-08 20:55:45 +00004112 FunctionTemplateDecl *FunctionTemplate = 0;
4113 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00004114 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
Douglas Gregor9b146582009-07-08 20:55:45 +00004115 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
Anders Carlsson6c966c42009-10-07 22:26:29 +00004116 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(OvlExpr)) {
4117 Ovl = dyn_cast<OverloadedFunctionDecl>(ME->getMemberDecl());
4118 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(ME->getMemberDecl());
Douglas Gregor7d195b92009-10-09 22:54:25 +00004119 // FIXME: Explicit template arguments
Douglas Gregor9b146582009-07-08 20:55:45 +00004120 }
Douglas Gregor7d195b92009-10-09 22:54:25 +00004121 // FIXME: TemplateIdRefExpr?
Douglas Gregorcd695e52008-11-10 20:40:00 +00004122
Mike Stump11289f42009-09-09 15:08:12 +00004123 // If there's no overloaded function declaration or function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00004124 // we're done.
4125 if (!Ovl && !FunctionTemplate)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004126 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004127
Douglas Gregor9b146582009-07-08 20:55:45 +00004128 OverloadIterator Fun;
4129 if (Ovl)
4130 Fun = Ovl;
4131 else
4132 Fun = FunctionTemplate;
Mike Stump11289f42009-09-09 15:08:12 +00004133
Douglas Gregorcd695e52008-11-10 20:40:00 +00004134 // Look through all of the overloaded functions, searching for one
4135 // whose type matches exactly.
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004136 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004137 bool FoundNonTemplateFunction = false;
Douglas Gregor9b146582009-07-08 20:55:45 +00004138 for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00004139 // C++ [over.over]p3:
4140 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00004141 // targets of type "pointer-to-function" or "reference-to-function."
4142 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004143 // type "pointer-to-member-function."
4144 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00004145
Mike Stump11289f42009-09-09 15:08:12 +00004146 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregor9b146582009-07-08 20:55:45 +00004147 = dyn_cast<FunctionTemplateDecl>(*Fun)) {
Mike Stump11289f42009-09-09 15:08:12 +00004148 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004149 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00004150 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004151 // static when converting to member pointer.
4152 if (Method->isStatic() == IsMember)
4153 continue;
4154 } else if (IsMember)
4155 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004156
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004157 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004158 // If the name is a function template, template argument deduction is
4159 // done (14.8.2.2), and if the argument deduction succeeds, the
4160 // resulting template argument list is used to generate a single
4161 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004162 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004163 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00004164 FunctionDecl *Specialization = 0;
4165 TemplateDeductionInfo Info(Context);
4166 if (TemplateDeductionResult Result
4167 = DeduceTemplateArguments(FunctionTemplate, /*FIXME*/false,
4168 /*FIXME:*/0, /*FIXME:*/0,
4169 FunctionType, Specialization, Info)) {
4170 // FIXME: make a note of the failed deduction for diagnostics.
4171 (void)Result;
4172 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004173 // FIXME: If the match isn't exact, shouldn't we just drop this as
4174 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00004175 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00004176 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004177 Matches.insert(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004178 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor9b146582009-07-08 20:55:45 +00004179 }
4180 }
Mike Stump11289f42009-09-09 15:08:12 +00004181
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004182 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
4183 // Skip non-static functions when converting to pointer, and static
4184 // when converting to member pointer.
4185 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004186 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004187 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004188 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00004189
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004190 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004191 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004192 Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004193 FoundNonTemplateFunction = true;
4194 }
Mike Stump11289f42009-09-09 15:08:12 +00004195 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004196 }
4197
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004198 // If there were 0 or 1 matches, we're done.
4199 if (Matches.empty())
4200 return 0;
4201 else if (Matches.size() == 1)
4202 return *Matches.begin();
4203
4204 // C++ [over.over]p4:
4205 // If more than one function is selected, [...]
Douglas Gregor05155d82009-08-21 23:19:43 +00004206 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregorfae1d712009-09-26 03:56:17 +00004207 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004208 // [...] and any given function template specialization F1 is
4209 // eliminated if the set contains a second function template
4210 // specialization whose function template is more specialized
4211 // than the function template of F1 according to the partial
4212 // ordering rules of 14.5.5.2.
4213
4214 // The algorithm specified above is quadratic. We instead use a
4215 // two-pass algorithm (similar to the one used to identify the
4216 // best viable function in an overload set) that identifies the
4217 // best function template (if it exists).
Douglas Gregorfae1d712009-09-26 03:56:17 +00004218 llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
4219 Matches.end());
4220 return getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4221 TPOC_Other, From->getLocStart(),
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004222 PDiag(),
4223 PDiag(diag::err_addr_ovl_ambiguous)
Douglas Gregorfae1d712009-09-26 03:56:17 +00004224 << TemplateMatches[0]->getDeclName(),
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004225 PDiag(diag::err_ovl_template_candidate));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004226 }
Mike Stump11289f42009-09-09 15:08:12 +00004227
Douglas Gregorfae1d712009-09-26 03:56:17 +00004228 // [...] any function template specializations in the set are
4229 // eliminated if the set also contains a non-template function, [...]
4230 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4231 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4232 if ((*M)->getPrimaryTemplate() == 0)
4233 RemainingMatches.push_back(*M);
4234
Mike Stump11289f42009-09-09 15:08:12 +00004235 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004236 // selected function.
4237 if (RemainingMatches.size() == 1)
4238 return RemainingMatches.front();
Mike Stump11289f42009-09-09 15:08:12 +00004239
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004240 // FIXME: We should probably return the same thing that BestViableFunction
4241 // returns (even if we issue the diagnostics here).
4242 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4243 << RemainingMatches[0]->getDeclName();
4244 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4245 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregorcd695e52008-11-10 20:40:00 +00004246 return 0;
4247}
4248
Douglas Gregorcabea402009-09-22 15:41:20 +00004249/// \brief Add a single candidate to the overload set.
4250static void AddOverloadedCallCandidate(Sema &S,
4251 AnyFunctionDecl Callee,
4252 bool &ArgumentDependentLookup,
4253 bool HasExplicitTemplateArgs,
4254 const TemplateArgument *ExplicitTemplateArgs,
4255 unsigned NumExplicitTemplateArgs,
4256 Expr **Args, unsigned NumArgs,
4257 OverloadCandidateSet &CandidateSet,
4258 bool PartialOverloading) {
4259 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
4260 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
4261 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4262 PartialOverloading);
4263
4264 if (Func->getDeclContext()->isRecord() ||
4265 Func->getDeclContext()->isFunctionOrMethod())
4266 ArgumentDependentLookup = false;
4267 return;
4268 }
4269
4270 FunctionTemplateDecl *FuncTemplate = cast<FunctionTemplateDecl>(Callee);
4271 S.AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4272 ExplicitTemplateArgs,
4273 NumExplicitTemplateArgs,
4274 Args, NumArgs, CandidateSet);
4275
4276 if (FuncTemplate->getDeclContext()->isRecord())
4277 ArgumentDependentLookup = false;
4278}
4279
4280/// \brief Add the overload candidates named by callee and/or found by argument
4281/// dependent lookup to the given overload set.
4282void Sema::AddOverloadedCallCandidates(NamedDecl *Callee,
4283 DeclarationName &UnqualifiedName,
4284 bool &ArgumentDependentLookup,
4285 bool HasExplicitTemplateArgs,
4286 const TemplateArgument *ExplicitTemplateArgs,
4287 unsigned NumExplicitTemplateArgs,
4288 Expr **Args, unsigned NumArgs,
4289 OverloadCandidateSet &CandidateSet,
4290 bool PartialOverloading) {
4291 // Add the functions denoted by Callee to the set of candidate
4292 // functions. While we're doing so, track whether argument-dependent
4293 // lookup still applies, per:
4294 //
4295 // C++0x [basic.lookup.argdep]p3:
4296 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4297 // and let Y be the lookup set produced by argument dependent
4298 // lookup (defined as follows). If X contains
4299 //
4300 // -- a declaration of a class member, or
4301 //
4302 // -- a block-scope function declaration that is not a
4303 // using-declaration (FIXME: check for using declaration), or
4304 //
4305 // -- a declaration that is neither a function or a function
4306 // template
4307 //
4308 // then Y is empty.
4309 if (!Callee) {
4310 // Nothing to do.
4311 } else if (OverloadedFunctionDecl *Ovl
4312 = dyn_cast<OverloadedFunctionDecl>(Callee)) {
4313 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4314 FuncEnd = Ovl->function_end();
4315 Func != FuncEnd; ++Func)
4316 AddOverloadedCallCandidate(*this, *Func, ArgumentDependentLookup,
4317 HasExplicitTemplateArgs,
4318 ExplicitTemplateArgs, NumExplicitTemplateArgs,
4319 Args, NumArgs, CandidateSet,
4320 PartialOverloading);
4321 } else if (isa<FunctionDecl>(Callee) || isa<FunctionTemplateDecl>(Callee))
4322 AddOverloadedCallCandidate(*this,
4323 AnyFunctionDecl::getFromNamedDecl(Callee),
4324 ArgumentDependentLookup,
4325 HasExplicitTemplateArgs,
4326 ExplicitTemplateArgs, NumExplicitTemplateArgs,
4327 Args, NumArgs, CandidateSet,
4328 PartialOverloading);
4329 // FIXME: assert isa<FunctionDecl> || isa<FunctionTemplateDecl> rather than
4330 // checking dynamically.
4331
4332 if (Callee)
4333 UnqualifiedName = Callee->getDeclName();
4334
4335 if (ArgumentDependentLookup)
4336 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
4337 HasExplicitTemplateArgs,
4338 ExplicitTemplateArgs,
4339 NumExplicitTemplateArgs,
4340 CandidateSet,
4341 PartialOverloading);
4342}
4343
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004344/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00004345/// (which eventually refers to the declaration Func) and the call
4346/// arguments Args/NumArgs, attempt to resolve the function call down
4347/// to a specific function. If overload resolution succeeds, returns
4348/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00004349/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004350/// arguments and Fn, and returns NULL.
Douglas Gregore254f902009-02-04 00:32:51 +00004351FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004352 DeclarationName UnqualifiedName,
Douglas Gregor89026b52009-06-30 23:57:56 +00004353 bool HasExplicitTemplateArgs,
4354 const TemplateArgument *ExplicitTemplateArgs,
4355 unsigned NumExplicitTemplateArgs,
Douglas Gregora60a6912008-11-26 06:01:48 +00004356 SourceLocation LParenLoc,
4357 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004358 SourceLocation *CommaLocs,
Douglas Gregore254f902009-02-04 00:32:51 +00004359 SourceLocation RParenLoc,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004360 bool &ArgumentDependentLookup) {
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004361 OverloadCandidateSet CandidateSet;
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004362
4363 // Add the functions denoted by Callee to the set of candidate
Douglas Gregorcabea402009-09-22 15:41:20 +00004364 // functions.
4365 AddOverloadedCallCandidates(Callee, UnqualifiedName, ArgumentDependentLookup,
4366 HasExplicitTemplateArgs, ExplicitTemplateArgs,
4367 NumExplicitTemplateArgs, Args, NumArgs,
4368 CandidateSet);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004369 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004370 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregora60a6912008-11-26 06:01:48 +00004371 case OR_Success:
4372 return Best->Function;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004373
4374 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00004375 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004376 diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00004377 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004378 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4379 break;
4380
4381 case OR_Ambiguous:
4382 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004383 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004384 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4385 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004386
4387 case OR_Deleted:
4388 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4389 << Best->Function->isDeleted()
4390 << UnqualifiedName
4391 << Fn->getSourceRange();
4392 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4393 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004394 }
4395
4396 // Overload resolution failed. Destroy all of the subexpressions and
4397 // return NULL.
4398 Fn->Destroy(Context);
4399 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4400 Args[Arg]->Destroy(Context);
4401 return 0;
4402}
4403
Douglas Gregor084d8552009-03-13 23:49:33 +00004404/// \brief Create a unary operation that may resolve to an overloaded
4405/// operator.
4406///
4407/// \param OpLoc The location of the operator itself (e.g., '*').
4408///
4409/// \param OpcIn The UnaryOperator::Opcode that describes this
4410/// operator.
4411///
4412/// \param Functions The set of non-member functions that will be
4413/// considered by overload resolution. The caller needs to build this
4414/// set based on the context using, e.g.,
4415/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4416/// set should not contain any member functions; those will be added
4417/// by CreateOverloadedUnaryOp().
4418///
4419/// \param input The input argument.
4420Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4421 unsigned OpcIn,
4422 FunctionSet &Functions,
Mike Stump11289f42009-09-09 15:08:12 +00004423 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004424 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4425 Expr *Input = (Expr *)input.get();
4426
4427 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4428 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4429 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4430
4431 Expr *Args[2] = { Input, 0 };
4432 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004433
Douglas Gregor084d8552009-03-13 23:49:33 +00004434 // For post-increment and post-decrement, add the implicit '0' as
4435 // the second argument, so that we know this is a post-increment or
4436 // post-decrement.
4437 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4438 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00004439 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00004440 SourceLocation());
4441 NumArgs = 2;
4442 }
4443
4444 if (Input->isTypeDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00004445 OverloadedFunctionDecl *Overloads
Douglas Gregor084d8552009-03-13 23:49:33 +00004446 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump11289f42009-09-09 15:08:12 +00004447 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor084d8552009-03-13 23:49:33 +00004448 FuncEnd = Functions.end();
4449 Func != FuncEnd; ++Func)
4450 Overloads->addOverload(*Func);
4451
4452 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4453 OpLoc, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00004454
Douglas Gregor084d8552009-03-13 23:49:33 +00004455 input.release();
4456 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4457 &Args[0], NumArgs,
4458 Context.DependentTy,
4459 OpLoc));
4460 }
4461
4462 // Build an empty overload set.
4463 OverloadCandidateSet CandidateSet;
4464
4465 // Add the candidates from the given function set.
4466 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4467
4468 // Add operator candidates that are member functions.
4469 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4470
4471 // Add builtin operator candidates.
4472 AddBuiltinOperatorCandidates(Op, &Args[0], NumArgs, CandidateSet);
4473
4474 // Perform overload resolution.
4475 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004476 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004477 case OR_Success: {
4478 // We found a built-in operator or an overloaded operator.
4479 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00004480
Douglas Gregor084d8552009-03-13 23:49:33 +00004481 if (FnDecl) {
4482 // We matched an overloaded operator. Build a call to that
4483 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00004484
Douglas Gregor084d8552009-03-13 23:49:33 +00004485 // Convert the arguments.
4486 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4487 if (PerformObjectArgumentInitialization(Input, Method))
4488 return ExprError();
4489 } else {
4490 // Convert the arguments.
4491 if (PerformCopyInitialization(Input,
4492 FnDecl->getParamDecl(0)->getType(),
4493 "passing"))
4494 return ExprError();
4495 }
4496
4497 // Determine the result type
4498 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00004499 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor084d8552009-03-13 23:49:33 +00004500 ResultTy = ResultTy.getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00004501
Douglas Gregor084d8552009-03-13 23:49:33 +00004502 // Build the actual expression node.
4503 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4504 SourceLocation());
4505 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004506
Douglas Gregor084d8552009-03-13 23:49:33 +00004507 input.release();
Mike Stump11289f42009-09-09 15:08:12 +00004508
4509 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Anders Carlssone80ccac2009-08-16 04:11:06 +00004510 &Input, 1, ResultTy, OpLoc);
4511 return MaybeBindToTemporary(CE);
Douglas Gregor084d8552009-03-13 23:49:33 +00004512 } else {
4513 // We matched a built-in operator. Convert the arguments, then
4514 // break out so that we will build the appropriate built-in
4515 // operator node.
4516 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4517 Best->Conversions[0], "passing"))
4518 return ExprError();
4519
4520 break;
4521 }
4522 }
4523
4524 case OR_No_Viable_Function:
4525 // No viable function; fall through to handling this as a
4526 // built-in operator, which will produce an error message for us.
4527 break;
4528
4529 case OR_Ambiguous:
4530 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4531 << UnaryOperator::getOpcodeStr(Opc)
4532 << Input->getSourceRange();
4533 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4534 return ExprError();
4535
4536 case OR_Deleted:
4537 Diag(OpLoc, diag::err_ovl_deleted_oper)
4538 << Best->Function->isDeleted()
4539 << UnaryOperator::getOpcodeStr(Opc)
4540 << Input->getSourceRange();
4541 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4542 return ExprError();
4543 }
4544
4545 // Either we found no viable overloaded operator or we matched a
4546 // built-in operator. In either case, fall through to trying to
4547 // build a built-in operation.
4548 input.release();
4549 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4550}
4551
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004552/// \brief Create a binary operation that may resolve to an overloaded
4553/// operator.
4554///
4555/// \param OpLoc The location of the operator itself (e.g., '+').
4556///
4557/// \param OpcIn The BinaryOperator::Opcode that describes this
4558/// operator.
4559///
4560/// \param Functions The set of non-member functions that will be
4561/// considered by overload resolution. The caller needs to build this
4562/// set based on the context using, e.g.,
4563/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4564/// set should not contain any member functions; those will be added
4565/// by CreateOverloadedBinOp().
4566///
4567/// \param LHS Left-hand argument.
4568/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00004569Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004570Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004571 unsigned OpcIn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004572 FunctionSet &Functions,
4573 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004574 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00004575 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004576
4577 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4578 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4579 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4580
4581 // If either side is type-dependent, create an appropriate dependent
4582 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00004583 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004584 // .* cannot be overloaded.
4585 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00004586 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004587 Context.DependentTy, OpLoc));
4588
Mike Stump11289f42009-09-09 15:08:12 +00004589 OverloadedFunctionDecl *Overloads
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004590 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump11289f42009-09-09 15:08:12 +00004591 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004592 FuncEnd = Functions.end();
4593 Func != FuncEnd; ++Func)
4594 Overloads->addOverload(*Func);
4595
4596 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4597 OpLoc, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00004598
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004599 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00004600 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004601 Context.DependentTy,
4602 OpLoc));
4603 }
4604
4605 // If this is the .* operator, which is not overloadable, just
4606 // create a built-in binary operator.
4607 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00004608 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004609
4610 // If this is one of the assignment operators, we only perform
4611 // overload resolution if the left-hand side is a class or
4612 // enumeration type (C++ [expr.ass]p3).
4613 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
Douglas Gregore9899d92009-08-26 17:08:25 +00004614 !Args[0]->getType()->isOverloadableType())
4615 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004616
Douglas Gregor084d8552009-03-13 23:49:33 +00004617 // Build an empty overload set.
4618 OverloadCandidateSet CandidateSet;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004619
4620 // Add the candidates from the given function set.
4621 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4622
4623 // Add operator candidates that are member functions.
4624 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4625
4626 // Add builtin operator candidates.
4627 AddBuiltinOperatorCandidates(Op, Args, 2, CandidateSet);
4628
4629 // Perform overload resolution.
4630 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004631 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004632 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004633 // We found a built-in operator or an overloaded operator.
4634 FunctionDecl *FnDecl = Best->Function;
4635
4636 if (FnDecl) {
4637 // We matched an overloaded operator. Build a call to that
4638 // operator.
4639
4640 // Convert the arguments.
4641 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregore9899d92009-08-26 17:08:25 +00004642 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4643 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004644 "passing"))
4645 return ExprError();
4646 } else {
4647 // Convert the arguments.
Douglas Gregore9899d92009-08-26 17:08:25 +00004648 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004649 "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004650 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004651 "passing"))
4652 return ExprError();
4653 }
4654
4655 // Determine the result type
4656 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00004657 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004658 ResultTy = ResultTy.getNonReferenceType();
4659
4660 // Build the actual expression node.
4661 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00004662 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004663 UsualUnaryConversions(FnExpr);
4664
Mike Stump11289f42009-09-09 15:08:12 +00004665 Expr *CE = new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Anders Carlssone80ccac2009-08-16 04:11:06 +00004666 Args, 2, ResultTy, OpLoc);
4667 return MaybeBindToTemporary(CE);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004668 } else {
4669 // We matched a built-in operator. Convert the arguments, then
4670 // break out so that we will build the appropriate built-in
4671 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00004672 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004673 Best->Conversions[0], "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004674 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004675 Best->Conversions[1], "passing"))
4676 return ExprError();
4677
4678 break;
4679 }
4680 }
4681
Douglas Gregor66950a32009-09-30 21:46:01 +00004682 case OR_No_Viable_Function: {
4683 // C++ [over.match.oper]p9:
4684 // If the operator is the operator , [...] and there are no
4685 // viable functions, then the operator is assumed to be the
4686 // built-in operator and interpreted according to clause 5.
4687 if (Opc == BinaryOperator::Comma)
4688 break;
4689
Sebastian Redl027de2a2009-05-21 11:50:50 +00004690 // For class as left operand for assignment or compound assigment operator
4691 // do not fall through to handling in built-in, but report that no overloaded
4692 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00004693 OwningExprResult Result = ExprError();
4694 if (Args[0]->getType()->isRecordType() &&
4695 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00004696 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4697 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004698 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00004699 } else {
4700 // No viable function; try to create a built-in operation, which will
4701 // produce an error. Then, show the non-viable candidates.
4702 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00004703 }
Douglas Gregor66950a32009-09-30 21:46:01 +00004704 assert(Result.isInvalid() &&
4705 "C++ binary operator overloading is missing candidates!");
4706 if (Result.isInvalid())
4707 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4708 return move(Result);
4709 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004710
4711 case OR_Ambiguous:
4712 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4713 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004714 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004715 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true, Opc, OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004716 return ExprError();
4717
4718 case OR_Deleted:
4719 Diag(OpLoc, diag::err_ovl_deleted_oper)
4720 << Best->Function->isDeleted()
4721 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004722 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004723 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4724 return ExprError();
4725 }
4726
Douglas Gregor66950a32009-09-30 21:46:01 +00004727 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00004728 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004729}
4730
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004731/// BuildCallToMemberFunction - Build a call to a member
4732/// function. MemExpr is the expression that refers to the member
4733/// function (and includes the object parameter), Args/NumArgs are the
4734/// arguments to the function call (not including the object
4735/// parameter). The caller needs to validate that the member
4736/// expression refers to a member function or an overloaded member
4737/// function.
4738Sema::ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00004739Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
4740 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004741 unsigned NumArgs, SourceLocation *CommaLocs,
4742 SourceLocation RParenLoc) {
4743 // Dig out the member expression. This holds both the object
4744 // argument and the member function we're referring to.
4745 MemberExpr *MemExpr = 0;
4746 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
4747 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
4748 else
4749 MemExpr = dyn_cast<MemberExpr>(MemExprE);
4750 assert(MemExpr && "Building member call without member expression");
4751
4752 // Extract the object argument.
4753 Expr *ObjectArg = MemExpr->getBase();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004754
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004755 CXXMethodDecl *Method = 0;
Douglas Gregor97628d62009-08-21 00:16:32 +00004756 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
4757 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004758 // Add overload candidates
4759 OverloadCandidateSet CandidateSet;
Douglas Gregor97628d62009-08-21 00:16:32 +00004760 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00004761
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00004762 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
4763 Func != FuncEnd; ++Func) {
4764 if ((Method = dyn_cast<CXXMethodDecl>(*Func)))
Mike Stump11289f42009-09-09 15:08:12 +00004765 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00004766 /*SuppressUserConversions=*/false);
4767 else
Douglas Gregor84f14dd2009-09-01 00:37:14 +00004768 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
4769 MemExpr->hasExplicitTemplateArgumentList(),
4770 MemExpr->getTemplateArgs(),
4771 MemExpr->getNumTemplateArgs(),
4772 ObjectArg, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00004773 CandidateSet,
4774 /*SuppressUsedConversions=*/false);
4775 }
Mike Stump11289f42009-09-09 15:08:12 +00004776
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004777 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004778 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004779 case OR_Success:
4780 Method = cast<CXXMethodDecl>(Best->Function);
4781 break;
4782
4783 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00004784 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004785 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00004786 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004787 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4788 // FIXME: Leaking incoming expressions!
4789 return true;
4790
4791 case OR_Ambiguous:
Mike Stump11289f42009-09-09 15:08:12 +00004792 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004793 diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00004794 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004795 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4796 // FIXME: Leaking incoming expressions!
4797 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004798
4799 case OR_Deleted:
Mike Stump11289f42009-09-09 15:08:12 +00004800 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +00004801 diag::err_ovl_deleted_member_call)
4802 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00004803 << DeclName << MemExprE->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00004804 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4805 // FIXME: Leaking incoming expressions!
4806 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004807 }
4808
4809 FixOverloadedFunctionReference(MemExpr, Method);
4810 } else {
4811 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
4812 }
4813
4814 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00004815 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004816 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
Mike Stump11289f42009-09-09 15:08:12 +00004817 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004818 Method->getResultType().getNonReferenceType(),
4819 RParenLoc));
4820
4821 // Convert the object argument (for a non-static member function call).
Mike Stump11289f42009-09-09 15:08:12 +00004822 if (!Method->isStatic() &&
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004823 PerformObjectArgumentInitialization(ObjectArg, Method))
4824 return true;
4825 MemExpr->setBase(ObjectArg);
4826
4827 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004828 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004829 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004830 RParenLoc))
4831 return true;
4832
Anders Carlssonbc4c1072009-08-16 01:56:34 +00004833 if (CheckFunctionCall(Method, TheCall.get()))
4834 return true;
Anders Carlsson8c84c202009-08-16 03:42:12 +00004835
4836 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004837}
4838
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004839/// BuildCallToObjectOfClassType - Build a call to an object of class
4840/// type (C++ [over.call.object]), which can end up invoking an
4841/// overloaded function call operator (@c operator()) or performing a
4842/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00004843Sema::ExprResult
4844Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00004845 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004846 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004847 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004848 SourceLocation RParenLoc) {
4849 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004850 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00004851
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004852 // C++ [over.call.object]p1:
4853 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00004854 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004855 // candidate functions includes at least the function call
4856 // operators of T. The function call operators of T are obtained by
4857 // ordinary lookup of the name operator() in the context of
4858 // (E).operator().
4859 OverloadCandidateSet CandidateSet;
Douglas Gregor91f84212008-12-11 16:49:14 +00004860 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor55297ac2008-12-23 00:26:44 +00004861 DeclContext::lookup_const_iterator Oper, OperEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004862 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregor55297ac2008-12-23 00:26:44 +00004863 Oper != OperEnd; ++Oper)
Mike Stump11289f42009-09-09 15:08:12 +00004864 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
Douglas Gregor55297ac2008-12-23 00:26:44 +00004865 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004866
Douglas Gregorab7897a2008-11-19 22:57:39 +00004867 // C++ [over.call.object]p2:
4868 // In addition, for each conversion function declared in T of the
4869 // form
4870 //
4871 // operator conversion-type-id () cv-qualifier;
4872 //
4873 // where cv-qualifier is the same cv-qualification as, or a
4874 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00004875 // denotes the type "pointer to function of (P1,...,Pn) returning
4876 // R", or the type "reference to pointer to function of
4877 // (P1,...,Pn) returning R", or the type "reference to function
4878 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00004879 // is also considered as a candidate function. Similarly,
4880 // surrogate call functions are added to the set of candidate
4881 // functions for each conversion function declared in an
4882 // accessible base class provided the function is not hidden
4883 // within T by another intervening declaration.
Mike Stump11289f42009-09-09 15:08:12 +00004884
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004885 if (!RequireCompleteType(SourceLocation(), Object->getType(), 0)) {
4886 // FIXME: Look in base classes for more conversion operators!
Mike Stump11289f42009-09-09 15:08:12 +00004887 OverloadedFunctionDecl *Conversions
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004888 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00004889 for (OverloadedFunctionDecl::function_iterator
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004890 Func = Conversions->function_begin(),
4891 FuncEnd = Conversions->function_end();
4892 Func != FuncEnd; ++Func) {
4893 CXXConversionDecl *Conv;
4894 FunctionTemplateDecl *ConvTemplate;
4895 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
Douglas Gregor05155d82009-08-21 23:19:43 +00004896
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004897 // Skip over templated conversion functions; they aren't
4898 // surrogates.
4899 if (ConvTemplate)
4900 continue;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004901
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004902 // Strip the reference type (if any) and then the pointer type (if
4903 // any) to get down to what might be a function type.
4904 QualType ConvType = Conv->getConversionType().getNonReferenceType();
4905 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
4906 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004907
John McCall9dd450b2009-09-21 23:43:11 +00004908 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004909 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
4910 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00004911 }
Mike Stump11289f42009-09-09 15:08:12 +00004912
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004913 // Perform overload resolution.
4914 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004915 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004916 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00004917 // Overload resolution succeeded; we'll build the appropriate call
4918 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004919 break;
4920
4921 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00004922 Diag(Object->getSourceRange().getBegin(),
Sebastian Redl15b02d22008-11-22 13:44:36 +00004923 diag::err_ovl_no_viable_object_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00004924 << Object->getType() << Object->getSourceRange();
Sebastian Redl15b02d22008-11-22 13:44:36 +00004925 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004926 break;
4927
4928 case OR_Ambiguous:
4929 Diag(Object->getSourceRange().getBegin(),
4930 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004931 << Object->getType() << Object->getSourceRange();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004932 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4933 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004934
4935 case OR_Deleted:
4936 Diag(Object->getSourceRange().getBegin(),
4937 diag::err_ovl_deleted_object_call)
4938 << Best->Function->isDeleted()
4939 << Object->getType() << Object->getSourceRange();
4940 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4941 break;
Mike Stump11289f42009-09-09 15:08:12 +00004942 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004943
Douglas Gregorab7897a2008-11-19 22:57:39 +00004944 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004945 // We had an error; delete all of the subexpressions and return
4946 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00004947 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004948 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00004949 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004950 return true;
4951 }
4952
Douglas Gregorab7897a2008-11-19 22:57:39 +00004953 if (Best->Function == 0) {
4954 // Since there is no function declaration, this is one of the
4955 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00004956 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00004957 = cast<CXXConversionDecl>(
4958 Best->Conversions[0].UserDefined.ConversionFunction);
4959
4960 // We selected one of the surrogate functions that converts the
4961 // object parameter to a function pointer. Perform the conversion
4962 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00004963
4964 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00004965 // and then call it.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00004966 CXXMemberCallExpr *CE =
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00004967 BuildCXXMemberCallExpr(Object, Conv);
4968
Fariborz Jahanian774cf792009-09-28 18:35:46 +00004969 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00004970 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
4971 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004972 }
4973
4974 // We found an overloaded operator(). Build a CXXOperatorCallExpr
4975 // that calls this method, using Object for the implicit object
4976 // parameter and passing along the remaining arguments.
4977 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00004978 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004979
4980 unsigned NumArgsInProto = Proto->getNumArgs();
4981 unsigned NumArgsToCheck = NumArgs;
4982
4983 // Build the full argument list for the method call (the
4984 // implicit object parameter is placed at the beginning of the
4985 // list).
4986 Expr **MethodArgs;
4987 if (NumArgs < NumArgsInProto) {
4988 NumArgsToCheck = NumArgsInProto;
4989 MethodArgs = new Expr*[NumArgsInProto + 1];
4990 } else {
4991 MethodArgs = new Expr*[NumArgs + 1];
4992 }
4993 MethodArgs[0] = Object;
4994 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4995 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00004996
4997 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004998 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00004999 UsualUnaryConversions(NewFn);
5000
5001 // Once we've built TheCall, all of the expressions are properly
5002 // owned.
5003 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005004 ExprOwningPtr<CXXOperatorCallExpr>
5005 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005006 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00005007 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005008 delete [] MethodArgs;
5009
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005010 // We may have default arguments. If so, we need to allocate more
5011 // slots in the call for them.
5012 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00005013 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005014 else if (NumArgs > NumArgsInProto)
5015 NumArgsToCheck = NumArgsInProto;
5016
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005017 bool IsError = false;
5018
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005019 // Initialize the implicit object parameter.
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005020 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005021 TheCall->setArg(0, Object);
5022
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005023
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005024 // Check the argument types.
5025 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005026 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005027 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005028 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00005029
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005030 // Pass the argument.
5031 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005032 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005033 } else {
Anders Carlssone8271232009-08-14 18:30:22 +00005034 Arg = CXXDefaultArgExpr::Create(Context, Method->getParamDecl(i));
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005035 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005036
5037 TheCall->setArg(i + 1, Arg);
5038 }
5039
5040 // If this is a variadic call, handle args passed through "...".
5041 if (Proto->isVariadic()) {
5042 // Promote the arguments (C99 6.5.2.2p7).
5043 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
5044 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005045 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005046 TheCall->setArg(i + 1, Arg);
5047 }
5048 }
5049
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005050 if (IsError) return true;
5051
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005052 if (CheckFunctionCall(Method, TheCall.get()))
5053 return true;
5054
Anders Carlsson1c83deb2009-08-16 03:53:54 +00005055 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005056}
5057
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005058/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00005059/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005060/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00005061Sema::OwningExprResult
5062Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
5063 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005064 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00005065
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005066 // C++ [over.ref]p1:
5067 //
5068 // [...] An expression x->m is interpreted as (x.operator->())->m
5069 // for a class object x of type T if T::operator->() exists and if
5070 // the operator is selected as the best match function by the
5071 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005072 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
5073 OverloadCandidateSet CandidateSet;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005074 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00005075
John McCall9f3059a2009-10-09 21:13:30 +00005076 LookupResult R;
5077 LookupQualifiedName(R, BaseRecord->getDecl(), OpName, LookupOrdinaryName);
Anders Carlsson78b54932009-09-10 23:18:36 +00005078
5079 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
5080 Oper != OperEnd; ++Oper)
Douglas Gregor55297ac2008-12-23 00:26:44 +00005081 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005082 /*SuppressUserConversions=*/false);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005083
5084 // Perform overload resolution.
5085 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005086 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005087 case OR_Success:
5088 // Overload resolution succeeded; we'll build the call below.
5089 break;
5090
5091 case OR_No_Viable_Function:
5092 if (CandidateSet.empty())
5093 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00005094 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005095 else
5096 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00005097 << "operator->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005098 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregord8061562009-08-06 03:17:00 +00005099 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005100
5101 case OR_Ambiguous:
5102 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00005103 << "->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005104 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005105 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005106
5107 case OR_Deleted:
5108 Diag(OpLoc, diag::err_ovl_deleted_oper)
5109 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00005110 << "->" << Base->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005111 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005112 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005113 }
5114
5115 // Convert the object parameter.
5116 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9ecea262008-11-21 03:04:22 +00005117 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00005118 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00005119
5120 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00005121 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005122
5123 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00005124 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
5125 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005126 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00005127 Base = new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr, &Base, 1,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005128 Method->getResultType().getNonReferenceType(),
Fariborz Jahanianac3005c2009-09-30 17:46:20 +00005129 Method->getLocation());
Douglas Gregord8061562009-08-06 03:17:00 +00005130 return Owned(Base);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005131}
5132
Douglas Gregorcd695e52008-11-10 20:40:00 +00005133/// FixOverloadedFunctionReference - E is an expression that refers to
5134/// a C++ overloaded function (possibly with some parentheses and
5135/// perhaps a '&' around it). We have resolved the overloaded function
5136/// to the function declaration Fn, so patch up the expression E to
5137/// refer (possibly indirectly) to Fn.
5138void Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
5139 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
5140 FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
5141 E->setType(PE->getSubExpr()->getType());
5142 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00005143 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00005144 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005145 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5146 if (Method->isStatic()) {
5147 // Do nothing: static member functions aren't any different
5148 // from non-member functions.
Mike Stump11289f42009-09-09 15:08:12 +00005149 } else if (QualifiedDeclRefExpr *DRE
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005150 = dyn_cast<QualifiedDeclRefExpr>(UnOp->getSubExpr())) {
5151 // We have taken the address of a pointer to member
5152 // function. Perform the computation here so that we get the
5153 // appropriate pointer to member type.
5154 DRE->setDecl(Fn);
5155 DRE->setType(Fn->getType());
5156 QualType ClassType
5157 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
Mike Stump11289f42009-09-09 15:08:12 +00005158 E->setType(Context.getMemberPointerType(Fn->getType(),
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005159 ClassType.getTypePtr()));
5160 return;
5161 }
5162 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005163 FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
Douglas Gregor3a7796b2009-02-11 00:19:33 +00005164 E->setType(Context.getPointerType(UnOp->getSubExpr()->getType()));
Douglas Gregorcd695e52008-11-10 20:40:00 +00005165 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
Douglas Gregor9b146582009-07-08 20:55:45 +00005166 assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
Mike Stump11289f42009-09-09 15:08:12 +00005167 isa<FunctionTemplateDecl>(DR->getDecl())) &&
Douglas Gregor9b146582009-07-08 20:55:45 +00005168 "Expected overloaded function or function template");
Douglas Gregorcd695e52008-11-10 20:40:00 +00005169 DR->setDecl(Fn);
5170 E->setType(Fn->getType());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005171 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
5172 MemExpr->setMemberDecl(Fn);
5173 E->setType(Fn->getType());
Douglas Gregorcd695e52008-11-10 20:40:00 +00005174 } else {
5175 assert(false && "Invalid reference to overloaded function");
5176 }
5177}
5178
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005179} // end namespace clang