blob: d2bdfb8e2cc8461c7c4eb94bc5bba0f2c6ec63ff [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)
Fariborz Jahanian574de2c2009-10-12 17:51:19 +0000467 if (Cand->Viable)
468 ICS.ConversionFunctionSet.push_back(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000469 }
470 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000471
472 return ICS;
473}
474
475/// IsStandardConversion - Determines whether there is a standard
476/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
477/// expression From to the type ToType. Standard conversion sequences
478/// only consider non-class types; for conversions that involve class
479/// types, use TryImplicitConversion. If a conversion exists, SCS will
480/// contain the standard conversion sequence required to perform this
481/// conversion and this routine will return true. Otherwise, this
482/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000483bool
484Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000485 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000486 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000487 QualType FromType = From->getType();
488
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000489 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000490 SCS.setAsIdentityConversion();
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000491 SCS.Deprecated = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000492 SCS.IncompatibleObjC = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000493 SCS.FromTypePtr = FromType.getAsOpaquePtr();
Douglas Gregor2fe98832008-11-03 19:09:14 +0000494 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000495
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000496 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000497 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000498 if (FromType->isRecordType() || ToType->isRecordType()) {
499 if (getLangOptions().CPlusPlus)
500 return false;
501
Mike Stump11289f42009-09-09 15:08:12 +0000502 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000503 }
504
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000505 // The first conversion can be an lvalue-to-rvalue conversion,
506 // array-to-pointer conversion, or function-to-pointer conversion
507 // (C++ 4p1).
508
Mike Stump11289f42009-09-09 15:08:12 +0000509 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000510 // An lvalue (3.10) of a non-function, non-array type T can be
511 // converted to an rvalue.
512 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000513 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000514 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000515 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000516 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000517
518 // If T is a non-class type, the type of the rvalue is the
519 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000520 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
521 // just strip the qualifiers because they don't matter.
522
523 // FIXME: Doesn't see through to qualifiers behind a typedef!
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000524 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000525 } else if (FromType->isArrayType()) {
526 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000527 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000528
529 // An lvalue or rvalue of type "array of N T" or "array of unknown
530 // bound of T" can be converted to an rvalue of type "pointer to
531 // T" (C++ 4.2p1).
532 FromType = Context.getArrayDecayedType(FromType);
533
534 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
535 // This conversion is deprecated. (C++ D.4).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000536 SCS.Deprecated = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000537
538 // For the purpose of ranking in overload resolution
539 // (13.3.3.1.1), this conversion is considered an
540 // array-to-pointer conversion followed by a qualification
541 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000542 SCS.Second = ICK_Identity;
543 SCS.Third = ICK_Qualification;
544 SCS.ToTypePtr = ToType.getAsOpaquePtr();
545 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000546 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000547 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
548 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000549 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000550
551 // An lvalue of function type T can be converted to an rvalue of
552 // type "pointer to T." The result is a pointer to the
553 // function. (C++ 4.3p1).
554 FromType = Context.getPointerType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000555 } else if (FunctionDecl *Fn
Douglas Gregorcd695e52008-11-10 20:40:00 +0000556 = ResolveAddressOfOverloadedFunction(From, ToType, false)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000557 // Address of overloaded function (C++ [over.over]).
Douglas Gregorcd695e52008-11-10 20:40:00 +0000558 SCS.First = ICK_Function_To_Pointer;
559
560 // We were able to resolve the address of the overloaded function,
561 // so we can convert to the type of that function.
562 FromType = Fn->getType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +0000563 if (ToType->isLValueReferenceType())
564 FromType = Context.getLValueReferenceType(FromType);
565 else if (ToType->isRValueReferenceType())
566 FromType = Context.getRValueReferenceType(FromType);
Sebastian Redl18f8ff62009-02-04 21:23:32 +0000567 else if (ToType->isMemberPointerType()) {
568 // Resolve address only succeeds if both sides are member pointers,
569 // but it doesn't have to be the same class. See DR 247.
570 // Note that this means that the type of &Derived::fn can be
571 // Ret (Base::*)(Args) if the fn overload actually found is from the
572 // base class, even if it was brought into the derived class via a
573 // using declaration. The standard isn't clear on this issue at all.
574 CXXMethodDecl *M = cast<CXXMethodDecl>(Fn);
575 FromType = Context.getMemberPointerType(FromType,
576 Context.getTypeDeclType(M->getParent()).getTypePtr());
577 } else
Douglas Gregorcd695e52008-11-10 20:40:00 +0000578 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000579 } else {
580 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000581 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000582 }
583
584 // The second conversion can be an integral promotion, floating
585 // point promotion, integral conversion, floating point conversion,
586 // floating-integral conversion, pointer conversion,
587 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000588 // For overloading in C, this can also be a "compatible-type"
589 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000590 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000591 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000592 // The unqualified versions of the types are the same: there's no
593 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000594 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000595 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000596 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000597 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000598 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000599 } else if (IsFloatingPointPromotion(FromType, ToType)) {
600 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000601 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000602 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000603 } else if (IsComplexPromotion(FromType, ToType)) {
604 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000605 SCS.Second = ICK_Complex_Promotion;
606 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000607 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000608 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000609 // Integral conversions (C++ 4.7).
610 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000611 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000612 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000613 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
614 // Floating point conversions (C++ 4.8).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000615 SCS.Second = ICK_Floating_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000616 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000617 } else if (FromType->isComplexType() && ToType->isComplexType()) {
618 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000619 SCS.Second = ICK_Complex_Conversion;
620 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000621 } else if ((FromType->isFloatingType() &&
622 ToType->isIntegralType() && (!ToType->isBooleanType() &&
623 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000624 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000625 ToType->isFloatingType())) {
626 // Floating-integral conversions (C++ 4.9).
627 // FIXME: isIntegralType shouldn't be true for enums in C++.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000628 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000629 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000630 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
631 (ToType->isComplexType() && FromType->isArithmeticType())) {
632 // Complex-real conversions (C99 6.3.1.7)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000633 SCS.Second = ICK_Complex_Real;
634 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000635 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
636 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000637 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000638 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000639 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000640 } else if (IsMemberPointerConversion(From, FromType, ToType,
641 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000642 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000643 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000644 } else if (ToType->isBooleanType() &&
645 (FromType->isArithmeticType() ||
646 FromType->isEnumeralType() ||
647 FromType->isPointerType() ||
648 FromType->isBlockPointerType() ||
649 FromType->isMemberPointerType() ||
650 FromType->isNullPtrType())) {
651 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000652 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000653 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000654 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000655 Context.typesAreCompatible(ToType, FromType)) {
656 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000657 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000658 } else {
659 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000660 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000661 }
662
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000663 QualType CanonFrom;
664 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000665 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000666 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000667 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000668 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000669 CanonFrom = Context.getCanonicalType(FromType);
670 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000671 } else {
672 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000673 SCS.Third = ICK_Identity;
674
Mike Stump11289f42009-09-09 15:08:12 +0000675 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000676 // [...] Any difference in top-level cv-qualification is
677 // subsumed by the initialization itself and does not constitute
678 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000679 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000680 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000681 if (CanonFrom.getUnqualifiedType() == CanonTo.getUnqualifiedType() &&
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000682 CanonFrom.getCVRQualifiers() != CanonTo.getCVRQualifiers()) {
683 FromType = ToType;
684 CanonFrom = CanonTo;
685 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000686 }
687
688 // If we have not converted the argument type to the parameter type,
689 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000690 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000691 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000692
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000693 SCS.ToTypePtr = FromType.getAsOpaquePtr();
694 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000695}
696
697/// IsIntegralPromotion - Determines whether the conversion from the
698/// expression From (whose potentially-adjusted type is FromType) to
699/// ToType is an integral promotion (C++ 4.5). If so, returns true and
700/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000701bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000702 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000703 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000704 if (!To) {
705 return false;
706 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000707
708 // An rvalue of type char, signed char, unsigned char, short int, or
709 // unsigned short int can be converted to an rvalue of type int if
710 // int can represent all the values of the source type; otherwise,
711 // the source rvalue can be converted to an rvalue of type unsigned
712 // int (C++ 4.5p1).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000713 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000714 if (// We can promote any signed, promotable integer type to an int
715 (FromType->isSignedIntegerType() ||
716 // We can promote any unsigned integer type whose size is
717 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +0000718 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000719 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000720 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000721 }
722
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000723 return To->getKind() == BuiltinType::UInt;
724 }
725
726 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
727 // can be converted to an rvalue of the first of the following types
728 // that can represent all the values of its underlying type: int,
729 // unsigned int, long, or unsigned long (C++ 4.5p2).
730 if ((FromType->isEnumeralType() || FromType->isWideCharType())
731 && ToType->isIntegerType()) {
732 // Determine whether the type we're converting from is signed or
733 // unsigned.
734 bool FromIsSigned;
735 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall9dd450b2009-09-21 23:43:11 +0000736 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000737 QualType UnderlyingType = FromEnumType->getDecl()->getIntegerType();
738 FromIsSigned = UnderlyingType->isSignedIntegerType();
739 } else {
740 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
741 FromIsSigned = true;
742 }
743
744 // The types we'll try to promote to, in the appropriate
745 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +0000746 QualType PromoteTypes[6] = {
747 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +0000748 Context.LongTy, Context.UnsignedLongTy ,
749 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000750 };
Douglas Gregor1d248c52008-12-12 02:00:36 +0000751 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000752 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
753 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +0000754 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000755 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
756 // We found the type that we can promote to. If this is the
757 // type we wanted, we have a promotion. Otherwise, no
758 // promotion.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000759 return Context.getCanonicalType(ToType).getUnqualifiedType()
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000760 == Context.getCanonicalType(PromoteTypes[Idx]).getUnqualifiedType();
761 }
762 }
763 }
764
765 // An rvalue for an integral bit-field (9.6) can be converted to an
766 // rvalue of type int if int can represent all the values of the
767 // bit-field; otherwise, it can be converted to unsigned int if
768 // unsigned int can represent all the values of the bit-field. If
769 // the bit-field is larger yet, no integral promotion applies to
770 // it. If the bit-field has an enumerated type, it is treated as any
771 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +0000772 // FIXME: We should delay checking of bit-fields until we actually perform the
773 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +0000774 using llvm::APSInt;
775 if (From)
776 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000777 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +0000778 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
779 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
780 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
781 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +0000782
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000783 // Are we promoting to an int from a bitfield that fits in an int?
784 if (BitWidth < ToSize ||
785 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
786 return To->getKind() == BuiltinType::Int;
787 }
Mike Stump11289f42009-09-09 15:08:12 +0000788
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000789 // Are we promoting to an unsigned int from an unsigned bitfield
790 // that fits into an unsigned int?
791 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
792 return To->getKind() == BuiltinType::UInt;
793 }
Mike Stump11289f42009-09-09 15:08:12 +0000794
Douglas Gregor2eedc3a2008-12-20 23:49:58 +0000795 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000796 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000797 }
Mike Stump11289f42009-09-09 15:08:12 +0000798
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000799 // An rvalue of type bool can be converted to an rvalue of type int,
800 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000801 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000802 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000803 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000804
805 return false;
806}
807
808/// IsFloatingPointPromotion - Determines whether the conversion from
809/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
810/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000811bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000812 /// An rvalue of type float can be converted to an rvalue of type
813 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +0000814 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
815 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000816 if (FromBuiltin->getKind() == BuiltinType::Float &&
817 ToBuiltin->getKind() == BuiltinType::Double)
818 return true;
819
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000820 // C99 6.3.1.5p1:
821 // When a float is promoted to double or long double, or a
822 // double is promoted to long double [...].
823 if (!getLangOptions().CPlusPlus &&
824 (FromBuiltin->getKind() == BuiltinType::Float ||
825 FromBuiltin->getKind() == BuiltinType::Double) &&
826 (ToBuiltin->getKind() == BuiltinType::LongDouble))
827 return true;
828 }
829
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000830 return false;
831}
832
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000833/// \brief Determine if a conversion is a complex promotion.
834///
835/// A complex promotion is defined as a complex -> complex conversion
836/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +0000837/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000838bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000839 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000840 if (!FromComplex)
841 return false;
842
John McCall9dd450b2009-09-21 23:43:11 +0000843 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000844 if (!ToComplex)
845 return false;
846
847 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +0000848 ToComplex->getElementType()) ||
849 IsIntegralPromotion(0, FromComplex->getElementType(),
850 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000851}
852
Douglas Gregor237f96c2008-11-26 23:31:11 +0000853/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
854/// the pointer type FromPtr to a pointer to type ToPointee, with the
855/// same type qualifiers as FromPtr has on its pointee type. ToType,
856/// if non-empty, will be a pointer to ToType that may or may not have
857/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +0000858static QualType
859BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000860 QualType ToPointee, QualType ToType,
861 ASTContext &Context) {
862 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
863 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +0000864 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +0000865
866 // Exact qualifier match -> return the pointer type we're converting to.
John McCall8ccfcb52009-09-24 19:53:00 +0000867 if (CanonToPointee.getQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +0000868 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +0000869 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +0000870 return ToType;
871
872 // Build a pointer to ToPointee. It has the right qualifiers
873 // already.
874 return Context.getPointerType(ToPointee);
875 }
876
877 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +0000878 return Context.getPointerType(
879 Context.getQualifiedType(CanonToPointee.getUnqualifiedType(), Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +0000880}
881
Mike Stump11289f42009-09-09 15:08:12 +0000882static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +0000883 bool InOverloadResolution,
884 ASTContext &Context) {
885 // Handle value-dependent integral null pointer constants correctly.
886 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
887 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
888 Expr->getType()->isIntegralType())
889 return !InOverloadResolution;
890
Douglas Gregor56751b52009-09-25 04:25:58 +0000891 return Expr->isNullPointerConstant(Context,
892 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
893 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +0000894}
Mike Stump11289f42009-09-09 15:08:12 +0000895
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000896/// IsPointerConversion - Determines whether the conversion of the
897/// expression From, which has the (possibly adjusted) type FromType,
898/// can be converted to the type ToType via a pointer conversion (C++
899/// 4.10). If so, returns true and places the converted type (that
900/// might differ from ToType in its cv-qualifiers at some level) into
901/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +0000902///
Douglas Gregora29dc052008-11-27 01:19:21 +0000903/// This routine also supports conversions to and from block pointers
904/// and conversions with Objective-C's 'id', 'id<protocols...>', and
905/// pointers to interfaces. FIXME: Once we've determined the
906/// appropriate overloading rules for Objective-C, we may want to
907/// split the Objective-C checks into a different routine; however,
908/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +0000909/// conversions, so for now they live here. IncompatibleObjC will be
910/// set if the conversion is an allowed Objective-C conversion that
911/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000912bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000913 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +0000914 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +0000915 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +0000916 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +0000917 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
918 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000919
Mike Stump11289f42009-09-09 15:08:12 +0000920 // Conversion from a null pointer constant to any Objective-C pointer type.
921 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000922 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +0000923 ConvertedType = ToType;
924 return true;
925 }
926
Douglas Gregor231d1c62008-11-27 00:15:41 +0000927 // Blocks: Block pointers can be converted to void*.
928 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000929 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000930 ConvertedType = ToType;
931 return true;
932 }
933 // Blocks: A null pointer constant can be converted to a block
934 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +0000935 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000936 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +0000937 ConvertedType = ToType;
938 return true;
939 }
940
Sebastian Redl576fd422009-05-10 18:38:11 +0000941 // If the left-hand-side is nullptr_t, the right side can be a null
942 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +0000943 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +0000944 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +0000945 ConvertedType = ToType;
946 return true;
947 }
948
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000949 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000950 if (!ToTypePtr)
951 return false;
952
953 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +0000954 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000955 ConvertedType = ToType;
956 return true;
957 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000958
Douglas Gregor237f96c2008-11-26 23:31:11 +0000959 // Beyond this point, both types need to be pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000960 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +0000961 if (!FromTypePtr)
962 return false;
963
964 QualType FromPointeeType = FromTypePtr->getPointeeType();
965 QualType ToPointeeType = ToTypePtr->getPointeeType();
966
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000967 // An rvalue of type "pointer to cv T," where T is an object type,
968 // can be converted to an rvalue of type "pointer to cv void" (C++
969 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +0000970 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +0000971 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +0000972 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +0000973 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000974 return true;
975 }
976
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000977 // When we're overloading in C, we allow a special kind of pointer
978 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +0000979 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000980 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000981 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000982 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +0000983 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000984 return true;
985 }
986
Douglas Gregor5c407d92008-10-23 00:40:37 +0000987 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +0000988 //
Douglas Gregor5c407d92008-10-23 00:40:37 +0000989 // An rvalue of type "pointer to cv D," where D is a class type,
990 // can be converted to an rvalue of type "pointer to cv B," where
991 // B is a base class (clause 10) of D. If B is an inaccessible
992 // (clause 11) or ambiguous (10.2) base class of D, a program that
993 // necessitates this conversion is ill-formed. The result of the
994 // conversion is a pointer to the base class sub-object of the
995 // derived class object. The null pointer value is converted to
996 // the null pointer value of the destination type.
997 //
Douglas Gregor39c16d42008-10-24 04:54:22 +0000998 // Note that we do not check for ambiguity or inaccessibility
999 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001000 if (getLangOptions().CPlusPlus &&
1001 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001002 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001003 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001004 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001005 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001006 ToType, Context);
1007 return true;
1008 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001009
Douglas Gregora119f102008-12-19 19:13:09 +00001010 return false;
1011}
1012
1013/// isObjCPointerConversion - Determines whether this is an
1014/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1015/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001016bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001017 QualType& ConvertedType,
1018 bool &IncompatibleObjC) {
1019 if (!getLangOptions().ObjC1)
1020 return false;
1021
Steve Naroff7cae42b2009-07-10 23:34:53 +00001022 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001023 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001024 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001025 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001026
Steve Naroff7cae42b2009-07-10 23:34:53 +00001027 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001028 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001029 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001030 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001031 ConvertedType = ToType;
1032 return true;
1033 }
1034 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001035 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001036 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001037 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001038 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001039 ConvertedType = ToType;
1040 return true;
1041 }
1042 // Objective C++: We're able to convert from a pointer to an
1043 // interface to a pointer to a different interface.
1044 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
1045 ConvertedType = ToType;
1046 return true;
1047 }
1048
1049 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1050 // Okay: this is some kind of implicit downcast of Objective-C
1051 // interfaces, which is permitted. However, we're going to
1052 // complain about it.
1053 IncompatibleObjC = true;
1054 ConvertedType = FromType;
1055 return true;
1056 }
Mike Stump11289f42009-09-09 15:08:12 +00001057 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001058 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001059 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001060 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001061 ToPointeeType = ToCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001062 else if (const BlockPointerType *ToBlockPtr = ToType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001063 ToPointeeType = ToBlockPtr->getPointeeType();
1064 else
Douglas Gregora119f102008-12-19 19:13:09 +00001065 return false;
1066
Douglas Gregor033f56d2008-12-23 00:53:59 +00001067 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001068 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001069 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001070 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001071 FromPointeeType = FromBlockPtr->getPointeeType();
1072 else
Douglas Gregora119f102008-12-19 19:13:09 +00001073 return false;
1074
Douglas Gregora119f102008-12-19 19:13:09 +00001075 // If we have pointers to pointers, recursively check whether this
1076 // is an Objective-C conversion.
1077 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1078 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1079 IncompatibleObjC)) {
1080 // We always complain about this conversion.
1081 IncompatibleObjC = true;
1082 ConvertedType = ToType;
1083 return true;
1084 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001085 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001086 // differences in the argument and result types are in Objective-C
1087 // pointer conversions. If so, we permit the conversion (but
1088 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001089 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001090 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001091 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001092 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001093 if (FromFunctionType && ToFunctionType) {
1094 // If the function types are exactly the same, this isn't an
1095 // Objective-C pointer conversion.
1096 if (Context.getCanonicalType(FromPointeeType)
1097 == Context.getCanonicalType(ToPointeeType))
1098 return false;
1099
1100 // Perform the quick checks that will tell us whether these
1101 // function types are obviously different.
1102 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1103 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1104 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1105 return false;
1106
1107 bool HasObjCConversion = false;
1108 if (Context.getCanonicalType(FromFunctionType->getResultType())
1109 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1110 // Okay, the types match exactly. Nothing to do.
1111 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1112 ToFunctionType->getResultType(),
1113 ConvertedType, IncompatibleObjC)) {
1114 // Okay, we have an Objective-C pointer conversion.
1115 HasObjCConversion = true;
1116 } else {
1117 // Function types are too different. Abort.
1118 return false;
1119 }
Mike Stump11289f42009-09-09 15:08:12 +00001120
Douglas Gregora119f102008-12-19 19:13:09 +00001121 // Check argument types.
1122 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1123 ArgIdx != NumArgs; ++ArgIdx) {
1124 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1125 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1126 if (Context.getCanonicalType(FromArgType)
1127 == Context.getCanonicalType(ToArgType)) {
1128 // Okay, the types match exactly. Nothing to do.
1129 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1130 ConvertedType, IncompatibleObjC)) {
1131 // Okay, we have an Objective-C pointer conversion.
1132 HasObjCConversion = true;
1133 } else {
1134 // Argument types are too different. Abort.
1135 return false;
1136 }
1137 }
1138
1139 if (HasObjCConversion) {
1140 // We had an Objective-C conversion. Allow this pointer
1141 // conversion, but complain about it.
1142 ConvertedType = ToType;
1143 IncompatibleObjC = true;
1144 return true;
1145 }
1146 }
1147
Sebastian Redl72b597d2009-01-25 19:43:20 +00001148 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001149}
1150
Douglas Gregor39c16d42008-10-24 04:54:22 +00001151/// CheckPointerConversion - Check the pointer conversion from the
1152/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001153/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001154/// conversions for which IsPointerConversion has already returned
1155/// true. It returns true and produces a diagnostic if there was an
1156/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001157bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
1158 CastExpr::CastKind &Kind) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001159 QualType FromType = From->getType();
1160
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001161 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1162 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001163 QualType FromPointeeType = FromPtrType->getPointeeType(),
1164 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001165
Douglas Gregor39c16d42008-10-24 04:54:22 +00001166 if (FromPointeeType->isRecordType() &&
1167 ToPointeeType->isRecordType()) {
1168 // We must have a derived-to-base conversion. Check an
1169 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001170 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1171 From->getExprLoc(),
1172 From->getSourceRange()))
1173 return true;
1174
1175 // The conversion was successful.
1176 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001177 }
1178 }
Mike Stump11289f42009-09-09 15:08:12 +00001179 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001180 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001181 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001182 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001183 // Objective-C++ conversions are always okay.
1184 // FIXME: We should have a different class of conversions for the
1185 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001186 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001187 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001188
Steve Naroff7cae42b2009-07-10 23:34:53 +00001189 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001190 return false;
1191}
1192
Sebastian Redl72b597d2009-01-25 19:43:20 +00001193/// IsMemberPointerConversion - Determines whether the conversion of the
1194/// expression From, which has the (possibly adjusted) type FromType, can be
1195/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1196/// If so, returns true and places the converted type (that might differ from
1197/// ToType in its cv-qualifiers at some level) into ConvertedType.
1198bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001199 QualType ToType,
1200 bool InOverloadResolution,
1201 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001202 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001203 if (!ToTypePtr)
1204 return false;
1205
1206 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001207 if (From->isNullPointerConstant(Context,
1208 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1209 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001210 ConvertedType = ToType;
1211 return true;
1212 }
1213
1214 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001215 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001216 if (!FromTypePtr)
1217 return false;
1218
1219 // A pointer to member of B can be converted to a pointer to member of D,
1220 // where D is derived from B (C++ 4.11p2).
1221 QualType FromClass(FromTypePtr->getClass(), 0);
1222 QualType ToClass(ToTypePtr->getClass(), 0);
1223 // FIXME: What happens when these are dependent? Is this function even called?
1224
1225 if (IsDerivedFrom(ToClass, FromClass)) {
1226 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1227 ToClass.getTypePtr());
1228 return true;
1229 }
1230
1231 return false;
1232}
1233
1234/// CheckMemberPointerConversion - Check the member pointer conversion from the
1235/// expression From to the type ToType. This routine checks for ambiguous or
1236/// virtual (FIXME: or inaccessible) base-to-derived member pointer conversions
1237/// for which IsMemberPointerConversion has already returned true. It returns
1238/// true and produces a diagnostic if there was an error, or returns false
1239/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001240bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Anders Carlssond7923c62009-08-22 23:33:40 +00001241 CastExpr::CastKind &Kind) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001242 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001243 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001244 if (!FromPtrType) {
1245 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001246 assert(From->isNullPointerConstant(Context,
1247 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001248 "Expr must be null pointer constant!");
1249 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001250 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001251 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001252
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001253 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001254 assert(ToPtrType && "No member pointer cast has a target type "
1255 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001256
Sebastian Redled8f2002009-01-28 18:33:18 +00001257 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1258 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001259
Sebastian Redled8f2002009-01-28 18:33:18 +00001260 // FIXME: What about dependent types?
1261 assert(FromClass->isRecordType() && "Pointer into non-class.");
1262 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001263
Douglas Gregor36d1b142009-10-06 17:59:45 +00001264 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/false,
1265 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001266 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1267 assert(DerivationOkay &&
1268 "Should not have been called if derivation isn't OK.");
1269 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001270
Sebastian Redled8f2002009-01-28 18:33:18 +00001271 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1272 getUnqualifiedType())) {
1273 // Derivation is ambiguous. Redo the check to find the exact paths.
1274 Paths.clear();
1275 Paths.setRecordingPaths(true);
1276 bool StillOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1277 assert(StillOkay && "Derivation changed due to quantum fluctuation.");
1278 (void)StillOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001279
Sebastian Redled8f2002009-01-28 18:33:18 +00001280 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1281 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1282 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1283 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001284 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001285
Douglas Gregor89ee6822009-02-28 01:32:25 +00001286 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001287 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1288 << FromClass << ToClass << QualType(VBase, 0)
1289 << From->getSourceRange();
1290 return true;
1291 }
1292
Anders Carlssond7923c62009-08-22 23:33:40 +00001293 // Must be a base to derived member conversion.
1294 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001295 return false;
1296}
1297
Douglas Gregor9a657932008-10-21 23:43:52 +00001298/// IsQualificationConversion - Determines whether the conversion from
1299/// an rvalue of type FromType to ToType is a qualification conversion
1300/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001301bool
1302Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001303 FromType = Context.getCanonicalType(FromType);
1304 ToType = Context.getCanonicalType(ToType);
1305
1306 // If FromType and ToType are the same type, this is not a
1307 // qualification conversion.
1308 if (FromType == ToType)
1309 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001310
Douglas Gregor9a657932008-10-21 23:43:52 +00001311 // (C++ 4.4p4):
1312 // A conversion can add cv-qualifiers at levels other than the first
1313 // in multi-level pointers, subject to the following rules: [...]
1314 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001315 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001316 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001317 // Within each iteration of the loop, we check the qualifiers to
1318 // determine if this still looks like a qualification
1319 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001320 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001321 // until there are no more pointers or pointers-to-members left to
1322 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001323 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001324
1325 // -- for every j > 0, if const is in cv 1,j then const is in cv
1326 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001327 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001328 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001329
Douglas Gregor9a657932008-10-21 23:43:52 +00001330 // -- if the cv 1,j and cv 2,j are different, then const is in
1331 // every cv for 0 < k < j.
1332 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001333 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001334 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001335
Douglas Gregor9a657932008-10-21 23:43:52 +00001336 // Keep track of whether all prior cv-qualifiers in the "to" type
1337 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001338 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001339 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001340 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001341
1342 // We are left with FromType and ToType being the pointee types
1343 // after unwrapping the original FromType and ToType the same number
1344 // of types. If we unwrapped any pointers, and if FromType and
1345 // ToType have the same unqualified type (since we checked
1346 // qualifiers above), then this is a qualification conversion.
1347 return UnwrappedAnyPointer &&
1348 FromType.getUnqualifiedType() == ToType.getUnqualifiedType();
1349}
1350
Douglas Gregor05155d82009-08-21 23:19:43 +00001351/// \brief Given a function template or function, extract the function template
1352/// declaration (if any) and the underlying function declaration.
1353template<typename T>
1354static void GetFunctionAndTemplate(AnyFunctionDecl Orig, T *&Function,
1355 FunctionTemplateDecl *&FunctionTemplate) {
1356 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(Orig);
1357 if (FunctionTemplate)
1358 Function = cast<T>(FunctionTemplate->getTemplatedDecl());
1359 else
1360 Function = cast<T>(Orig);
1361}
1362
Douglas Gregor576e98c2009-01-30 23:27:23 +00001363/// Determines whether there is a user-defined conversion sequence
1364/// (C++ [over.ics.user]) that converts expression From to the type
1365/// ToType. If such a conversion exists, User will contain the
1366/// user-defined conversion sequence that performs such a conversion
1367/// and this routine will return true. Otherwise, this routine returns
1368/// false and User is unspecified.
1369///
1370/// \param AllowConversionFunctions true if the conversion should
1371/// consider conversion functions at all. If false, only constructors
1372/// will be considered.
1373///
1374/// \param AllowExplicit true if the conversion should consider C++0x
1375/// "explicit" conversion functions as well as non-explicit conversion
1376/// functions (C++0x [class.conv.fct]p2).
Sebastian Redl42e92c42009-04-12 17:16:29 +00001377///
1378/// \param ForceRValue true if the expression should be treated as an rvalue
1379/// for overload resolution.
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001380/// \param UserCast true if looking for user defined conversion for a static
1381/// cast.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001382Sema::OverloadingResult Sema::IsUserDefinedConversion(
1383 Expr *From, QualType ToType,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001384 UserDefinedConversionSequence& User,
Fariborz Jahanian19c73282009-09-15 00:10:11 +00001385 OverloadCandidateSet& CandidateSet,
Douglas Gregor576e98c2009-01-30 23:27:23 +00001386 bool AllowConversionFunctions,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001387 bool AllowExplicit, bool ForceRValue,
1388 bool UserCast) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001389 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001390 if (CXXRecordDecl *ToRecordDecl
Douglas Gregor89ee6822009-02-28 01:32:25 +00001391 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
1392 // C++ [over.match.ctor]p1:
1393 // When objects of class type are direct-initialized (8.5), or
1394 // copy-initialized from an expression of the same or a
1395 // derived class type (8.5), overload resolution selects the
1396 // constructor. [...] For copy-initialization, the candidate
1397 // functions are all the converting constructors (12.3.1) of
1398 // that class. The argument list is the expression-list within
1399 // the parentheses of the initializer.
Mike Stump11289f42009-09-09 15:08:12 +00001400 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001401 = Context.DeclarationNames.getCXXConstructorName(
1402 Context.getCanonicalType(ToType).getUnqualifiedType());
1403 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001404 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001405 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001406 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001407 // Find the constructor (which may be a template).
1408 CXXConstructorDecl *Constructor = 0;
1409 FunctionTemplateDecl *ConstructorTmpl
1410 = dyn_cast<FunctionTemplateDecl>(*Con);
1411 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001412 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001413 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1414 else
1415 Constructor = cast<CXXConstructorDecl>(*Con);
Mike Stump11289f42009-09-09 15:08:12 +00001416
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001417 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001418 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001419 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001420 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001421 1, CandidateSet,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001422 /*SuppressUserConversions=*/!UserCast,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001423 ForceRValue);
1424 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001425 // Allow one user-defined conversion when user specifies a
1426 // From->ToType conversion via an static cast (c-style, etc).
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001427 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001428 /*SuppressUserConversions=*/!UserCast,
1429 ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001430 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001431 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001432 }
1433 }
1434
Douglas Gregor576e98c2009-01-30 23:27:23 +00001435 if (!AllowConversionFunctions) {
1436 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001437 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1438 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001439 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001440 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001441 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001442 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001443 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001444 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1445 // Add all of the conversion functions as candidates.
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001446 OverloadedFunctionDecl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001447 = FromRecordDecl->getVisibleConversionFunctions();
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001448 for (OverloadedFunctionDecl::function_iterator Func
1449 = Conversions->function_begin();
1450 Func != Conversions->function_end(); ++Func) {
1451 CXXConversionDecl *Conv;
1452 FunctionTemplateDecl *ConvTemplate;
1453 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1454 if (ConvTemplate)
1455 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1456 else
1457 Conv = dyn_cast<CXXConversionDecl>(*Func);
1458
1459 if (AllowExplicit || !Conv->isExplicit()) {
1460 if (ConvTemplate)
1461 AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1462 CandidateSet);
1463 else
1464 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1465 }
1466 }
1467 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001468 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001469
1470 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001471 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001472 case OR_Success:
1473 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001474 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001475 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1476 // C++ [over.ics.user]p1:
1477 // If the user-defined conversion is specified by a
1478 // constructor (12.3.1), the initial standard conversion
1479 // sequence converts the source type to the type required by
1480 // the argument of the constructor.
1481 //
1482 // FIXME: What about ellipsis conversions?
1483 QualType ThisType = Constructor->getThisType(Context);
1484 User.Before = Best->Conversions[0].Standard;
1485 User.ConversionFunction = Constructor;
1486 User.After.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00001487 User.After.FromTypePtr
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001488 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001489 User.After.ToTypePtr = ToType.getAsOpaquePtr();
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001490 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001491 } else if (CXXConversionDecl *Conversion
1492 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1493 // C++ [over.ics.user]p1:
1494 //
1495 // [...] If the user-defined conversion is specified by a
1496 // conversion function (12.3.2), the initial standard
1497 // conversion sequence converts the source type to the
1498 // implicit object parameter of the conversion function.
1499 User.Before = Best->Conversions[0].Standard;
1500 User.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00001501
1502 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001503 // The second standard conversion sequence converts the
1504 // result of the user-defined conversion to the target type
1505 // for the sequence. Since an implicit conversion sequence
1506 // is an initialization, the special rules for
1507 // initialization by user-defined conversion apply when
1508 // selecting the best user-defined conversion for a
1509 // user-defined conversion sequence (see 13.3.3 and
1510 // 13.3.3.1).
1511 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001512 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001513 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001514 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001515 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001516 }
Mike Stump11289f42009-09-09 15:08:12 +00001517
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001518 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001519 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001520 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001521 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001522 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001523
1524 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001525 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001526 }
1527
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001528 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001529}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001530
1531bool
1532Sema::DiagnoseAmbiguousUserDefinedConversion(Expr *From, QualType ToType) {
1533 ImplicitConversionSequence ICS;
1534 OverloadCandidateSet CandidateSet;
1535 OverloadingResult OvResult =
1536 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1537 CandidateSet, true, false, false);
1538 if (OvResult != OR_Ambiguous)
1539 return false;
1540 Diag(From->getSourceRange().getBegin(),
1541 diag::err_typecheck_ambiguous_condition)
1542 << From->getType() << ToType << From->getSourceRange();
1543 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1544 return true;
1545}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001546
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001547/// CompareImplicitConversionSequences - Compare two implicit
1548/// conversion sequences to determine whether one is better than the
1549/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001550ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001551Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1552 const ImplicitConversionSequence& ICS2)
1553{
1554 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1555 // conversion sequences (as defined in 13.3.3.1)
1556 // -- a standard conversion sequence (13.3.3.1.1) is a better
1557 // conversion sequence than a user-defined conversion sequence or
1558 // an ellipsis conversion sequence, and
1559 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1560 // conversion sequence than an ellipsis conversion sequence
1561 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001562 //
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001563 if (ICS1.ConversionKind < ICS2.ConversionKind)
1564 return ImplicitConversionSequence::Better;
1565 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1566 return ImplicitConversionSequence::Worse;
1567
1568 // Two implicit conversion sequences of the same form are
1569 // indistinguishable conversion sequences unless one of the
1570 // following rules apply: (C++ 13.3.3.2p3):
1571 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1572 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
Mike Stump11289f42009-09-09 15:08:12 +00001573 else if (ICS1.ConversionKind ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001574 ImplicitConversionSequence::UserDefinedConversion) {
1575 // User-defined conversion sequence U1 is a better conversion
1576 // sequence than another user-defined conversion sequence U2 if
1577 // they contain the same user-defined conversion function or
1578 // constructor and if the second standard conversion sequence of
1579 // U1 is better than the second standard conversion sequence of
1580 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001581 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001582 ICS2.UserDefined.ConversionFunction)
1583 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1584 ICS2.UserDefined.After);
1585 }
1586
1587 return ImplicitConversionSequence::Indistinguishable;
1588}
1589
1590/// CompareStandardConversionSequences - Compare two standard
1591/// conversion sequences to determine whether one is better than the
1592/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001593ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001594Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1595 const StandardConversionSequence& SCS2)
1596{
1597 // Standard conversion sequence S1 is a better conversion sequence
1598 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1599
1600 // -- S1 is a proper subsequence of S2 (comparing the conversion
1601 // sequences in the canonical form defined by 13.3.3.1.1,
1602 // excluding any Lvalue Transformation; the identity conversion
1603 // sequence is considered to be a subsequence of any
1604 // non-identity conversion sequence) or, if not that,
1605 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1606 // Neither is a proper subsequence of the other. Do nothing.
1607 ;
1608 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1609 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001610 (SCS1.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001611 SCS1.Third == ICK_Identity))
1612 // SCS1 is a proper subsequence of SCS2.
1613 return ImplicitConversionSequence::Better;
1614 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1615 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001616 (SCS2.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001617 SCS2.Third == ICK_Identity))
1618 // SCS2 is a proper subsequence of SCS1.
1619 return ImplicitConversionSequence::Worse;
1620
1621 // -- the rank of S1 is better than the rank of S2 (by the rules
1622 // defined below), or, if not that,
1623 ImplicitConversionRank Rank1 = SCS1.getRank();
1624 ImplicitConversionRank Rank2 = SCS2.getRank();
1625 if (Rank1 < Rank2)
1626 return ImplicitConversionSequence::Better;
1627 else if (Rank2 < Rank1)
1628 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001629
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001630 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1631 // are indistinguishable unless one of the following rules
1632 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001633
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001634 // A conversion that is not a conversion of a pointer, or
1635 // pointer to member, to bool is better than another conversion
1636 // that is such a conversion.
1637 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1638 return SCS2.isPointerConversionToBool()
1639 ? ImplicitConversionSequence::Better
1640 : ImplicitConversionSequence::Worse;
1641
Douglas Gregor5c407d92008-10-23 00:40:37 +00001642 // C++ [over.ics.rank]p4b2:
1643 //
1644 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001645 // conversion of B* to A* is better than conversion of B* to
1646 // void*, and conversion of A* to void* is better than conversion
1647 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001648 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001649 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001650 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001651 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001652 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1653 // Exactly one of the conversion sequences is a conversion to
1654 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001655 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1656 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001657 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1658 // Neither conversion sequence converts to a void pointer; compare
1659 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001660 if (ImplicitConversionSequence::CompareKind DerivedCK
1661 = CompareDerivedToBaseConversions(SCS1, SCS2))
1662 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001663 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1664 // Both conversion sequences are conversions to void
1665 // pointers. Compare the source types to determine if there's an
1666 // inheritance relationship in their sources.
1667 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1668 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1669
1670 // Adjust the types we're converting from via the array-to-pointer
1671 // conversion, if we need to.
1672 if (SCS1.First == ICK_Array_To_Pointer)
1673 FromType1 = Context.getArrayDecayedType(FromType1);
1674 if (SCS2.First == ICK_Array_To_Pointer)
1675 FromType2 = Context.getArrayDecayedType(FromType2);
1676
Mike Stump11289f42009-09-09 15:08:12 +00001677 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001678 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001679 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001680 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001681
1682 if (IsDerivedFrom(FromPointee2, FromPointee1))
1683 return ImplicitConversionSequence::Better;
1684 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1685 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001686
1687 // Objective-C++: If one interface is more specific than the
1688 // other, it is the better one.
John McCall9dd450b2009-09-21 23:43:11 +00001689 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1690 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001691 if (FromIface1 && FromIface1) {
1692 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1693 return ImplicitConversionSequence::Better;
1694 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1695 return ImplicitConversionSequence::Worse;
1696 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001697 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001698
1699 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1700 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001701 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001702 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001703 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001704
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001705 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001706 // C++0x [over.ics.rank]p3b4:
1707 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1708 // implicit object parameter of a non-static member function declared
1709 // without a ref-qualifier, and S1 binds an rvalue reference to an
1710 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001711 // FIXME: We don't know if we're dealing with the implicit object parameter,
1712 // or if the member function in this case has a ref qualifier.
1713 // (Of course, we don't have ref qualifiers yet.)
1714 if (SCS1.RRefBinding != SCS2.RRefBinding)
1715 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1716 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001717
1718 // C++ [over.ics.rank]p3b4:
1719 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1720 // which the references refer are the same type except for
1721 // top-level cv-qualifiers, and the type to which the reference
1722 // initialized by S2 refers is more cv-qualified than the type
1723 // to which the reference initialized by S1 refers.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001724 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1725 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001726 T1 = Context.getCanonicalType(T1);
1727 T2 = Context.getCanonicalType(T2);
1728 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1729 if (T2.isMoreQualifiedThan(T1))
1730 return ImplicitConversionSequence::Better;
1731 else if (T1.isMoreQualifiedThan(T2))
1732 return ImplicitConversionSequence::Worse;
1733 }
1734 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001735
1736 return ImplicitConversionSequence::Indistinguishable;
1737}
1738
1739/// CompareQualificationConversions - Compares two standard conversion
1740/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001741/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1742ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001743Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001744 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001745 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001746 // -- S1 and S2 differ only in their qualification conversion and
1747 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1748 // cv-qualification signature of type T1 is a proper subset of
1749 // the cv-qualification signature of type T2, and S1 is not the
1750 // deprecated string literal array-to-pointer conversion (4.2).
1751 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1752 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1753 return ImplicitConversionSequence::Indistinguishable;
1754
1755 // FIXME: the example in the standard doesn't use a qualification
1756 // conversion (!)
1757 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1758 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1759 T1 = Context.getCanonicalType(T1);
1760 T2 = Context.getCanonicalType(T2);
1761
1762 // If the types are the same, we won't learn anything by unwrapped
1763 // them.
1764 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1765 return ImplicitConversionSequence::Indistinguishable;
1766
Mike Stump11289f42009-09-09 15:08:12 +00001767 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001768 = ImplicitConversionSequence::Indistinguishable;
1769 while (UnwrapSimilarPointerTypes(T1, T2)) {
1770 // Within each iteration of the loop, we check the qualifiers to
1771 // determine if this still looks like a qualification
1772 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001773 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001774 // until there are no more pointers or pointers-to-members left
1775 // to unwrap. This essentially mimics what
1776 // IsQualificationConversion does, but here we're checking for a
1777 // strict subset of qualifiers.
1778 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1779 // The qualifiers are the same, so this doesn't tell us anything
1780 // about how the sequences rank.
1781 ;
1782 else if (T2.isMoreQualifiedThan(T1)) {
1783 // T1 has fewer qualifiers, so it could be the better sequence.
1784 if (Result == ImplicitConversionSequence::Worse)
1785 // Neither has qualifiers that are a subset of the other's
1786 // qualifiers.
1787 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001788
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001789 Result = ImplicitConversionSequence::Better;
1790 } else if (T1.isMoreQualifiedThan(T2)) {
1791 // T2 has fewer qualifiers, so it could be the better sequence.
1792 if (Result == ImplicitConversionSequence::Better)
1793 // Neither has qualifiers that are a subset of the other's
1794 // qualifiers.
1795 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001796
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001797 Result = ImplicitConversionSequence::Worse;
1798 } else {
1799 // Qualifiers are disjoint.
1800 return ImplicitConversionSequence::Indistinguishable;
1801 }
1802
1803 // If the types after this point are equivalent, we're done.
1804 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1805 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001806 }
1807
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001808 // Check that the winning standard conversion sequence isn't using
1809 // the deprecated string literal array to pointer conversion.
1810 switch (Result) {
1811 case ImplicitConversionSequence::Better:
1812 if (SCS1.Deprecated)
1813 Result = ImplicitConversionSequence::Indistinguishable;
1814 break;
1815
1816 case ImplicitConversionSequence::Indistinguishable:
1817 break;
1818
1819 case ImplicitConversionSequence::Worse:
1820 if (SCS2.Deprecated)
1821 Result = ImplicitConversionSequence::Indistinguishable;
1822 break;
1823 }
1824
1825 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001826}
1827
Douglas Gregor5c407d92008-10-23 00:40:37 +00001828/// CompareDerivedToBaseConversions - Compares two standard conversion
1829/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00001830/// various kinds of derived-to-base conversions (C++
1831/// [over.ics.rank]p4b3). As part of these checks, we also look at
1832/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001833ImplicitConversionSequence::CompareKind
1834Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1835 const StandardConversionSequence& SCS2) {
1836 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1837 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1838 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1839 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1840
1841 // Adjust the types we're converting from via the array-to-pointer
1842 // conversion, if we need to.
1843 if (SCS1.First == ICK_Array_To_Pointer)
1844 FromType1 = Context.getArrayDecayedType(FromType1);
1845 if (SCS2.First == ICK_Array_To_Pointer)
1846 FromType2 = Context.getArrayDecayedType(FromType2);
1847
1848 // Canonicalize all of the types.
1849 FromType1 = Context.getCanonicalType(FromType1);
1850 ToType1 = Context.getCanonicalType(ToType1);
1851 FromType2 = Context.getCanonicalType(FromType2);
1852 ToType2 = Context.getCanonicalType(ToType2);
1853
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001854 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00001855 //
1856 // If class B is derived directly or indirectly from class A and
1857 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001858 //
1859 // For Objective-C, we let A, B, and C also be Objective-C
1860 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001861
1862 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00001863 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00001864 SCS2.Second == ICK_Pointer_Conversion &&
1865 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1866 FromType1->isPointerType() && FromType2->isPointerType() &&
1867 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001868 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001869 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001870 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001871 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001872 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001873 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001874 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001875 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001876
John McCall9dd450b2009-09-21 23:43:11 +00001877 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1878 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1879 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
1880 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001881
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001882 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00001883 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1884 if (IsDerivedFrom(ToPointee1, ToPointee2))
1885 return ImplicitConversionSequence::Better;
1886 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1887 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001888
1889 if (ToIface1 && ToIface2) {
1890 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1891 return ImplicitConversionSequence::Better;
1892 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1893 return ImplicitConversionSequence::Worse;
1894 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001895 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001896
1897 // -- conversion of B* to A* is better than conversion of C* to A*,
1898 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1899 if (IsDerivedFrom(FromPointee2, FromPointee1))
1900 return ImplicitConversionSequence::Better;
1901 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1902 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00001903
Douglas Gregor237f96c2008-11-26 23:31:11 +00001904 if (FromIface1 && FromIface2) {
1905 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1906 return ImplicitConversionSequence::Better;
1907 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1908 return ImplicitConversionSequence::Worse;
1909 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001910 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001911 }
1912
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001913 // Compare based on reference bindings.
1914 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1915 SCS1.Second == ICK_Derived_To_Base) {
1916 // -- binding of an expression of type C to a reference of type
1917 // B& is better than binding an expression of type C to a
1918 // reference of type A&,
1919 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1920 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1921 if (IsDerivedFrom(ToType1, ToType2))
1922 return ImplicitConversionSequence::Better;
1923 else if (IsDerivedFrom(ToType2, ToType1))
1924 return ImplicitConversionSequence::Worse;
1925 }
1926
Douglas Gregor2fe98832008-11-03 19:09:14 +00001927 // -- binding of an expression of type B to a reference of type
1928 // A& is better than binding an expression of type C to a
1929 // reference of type A&,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001930 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1931 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1932 if (IsDerivedFrom(FromType2, FromType1))
1933 return ImplicitConversionSequence::Better;
1934 else if (IsDerivedFrom(FromType1, FromType2))
1935 return ImplicitConversionSequence::Worse;
1936 }
1937 }
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00001938
1939 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00001940 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
1941 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
1942 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
1943 const MemberPointerType * FromMemPointer1 =
1944 FromType1->getAs<MemberPointerType>();
1945 const MemberPointerType * ToMemPointer1 =
1946 ToType1->getAs<MemberPointerType>();
1947 const MemberPointerType * FromMemPointer2 =
1948 FromType2->getAs<MemberPointerType>();
1949 const MemberPointerType * ToMemPointer2 =
1950 ToType2->getAs<MemberPointerType>();
1951 const Type *FromPointeeType1 = FromMemPointer1->getClass();
1952 const Type *ToPointeeType1 = ToMemPointer1->getClass();
1953 const Type *FromPointeeType2 = FromMemPointer2->getClass();
1954 const Type *ToPointeeType2 = ToMemPointer2->getClass();
1955 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
1956 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
1957 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
1958 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00001959 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00001960 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1961 if (IsDerivedFrom(ToPointee1, ToPointee2))
1962 return ImplicitConversionSequence::Worse;
1963 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1964 return ImplicitConversionSequence::Better;
1965 }
1966 // conversion of B::* to C::* is better than conversion of A::* to C::*
1967 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
1968 if (IsDerivedFrom(FromPointee1, FromPointee2))
1969 return ImplicitConversionSequence::Better;
1970 else if (IsDerivedFrom(FromPointee2, FromPointee1))
1971 return ImplicitConversionSequence::Worse;
1972 }
1973 }
1974
Douglas Gregor2fe98832008-11-03 19:09:14 +00001975 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1976 SCS1.Second == ICK_Derived_To_Base) {
1977 // -- conversion of C to B is better than conversion of C to A,
1978 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1979 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1980 if (IsDerivedFrom(ToType1, ToType2))
1981 return ImplicitConversionSequence::Better;
1982 else if (IsDerivedFrom(ToType2, ToType1))
1983 return ImplicitConversionSequence::Worse;
1984 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001985
Douglas Gregor2fe98832008-11-03 19:09:14 +00001986 // -- conversion of B to A is better than conversion of C to A.
1987 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1988 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1989 if (IsDerivedFrom(FromType2, FromType1))
1990 return ImplicitConversionSequence::Better;
1991 else if (IsDerivedFrom(FromType1, FromType2))
1992 return ImplicitConversionSequence::Worse;
1993 }
1994 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001995
Douglas Gregor5c407d92008-10-23 00:40:37 +00001996 return ImplicitConversionSequence::Indistinguishable;
1997}
1998
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001999/// TryCopyInitialization - Try to copy-initialize a value of type
2000/// ToType from the expression From. Return the implicit conversion
2001/// sequence required to pass this argument, which may be a bad
2002/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002003/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redl42e92c42009-04-12 17:16:29 +00002004/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2005/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump11289f42009-09-09 15:08:12 +00002006ImplicitConversionSequence
2007Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002008 bool SuppressUserConversions, bool ForceRValue,
2009 bool InOverloadResolution) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002010 if (ToType->isReferenceType()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002011 ImplicitConversionSequence ICS;
Mike Stump11289f42009-09-09 15:08:12 +00002012 CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002013 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002014 SuppressUserConversions,
2015 /*AllowExplicit=*/false,
2016 ForceRValue,
2017 &ICS);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002018 return ICS;
2019 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002020 return TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002021 SuppressUserConversions,
2022 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002023 ForceRValue,
2024 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002025 }
2026}
2027
Sebastian Redl42e92c42009-04-12 17:16:29 +00002028/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2029/// the expression @p From. Returns true (and emits a diagnostic) if there was
2030/// an error, returns false if the initialization succeeded. Elidable should
2031/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2032/// differently in C++0x for this case.
Mike Stump11289f42009-09-09 15:08:12 +00002033bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002034 const char* Flavor, bool Elidable) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002035 if (!getLangOptions().CPlusPlus) {
2036 // In C, argument passing is the same as performing an assignment.
2037 QualType FromType = From->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002038
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002039 AssignConvertType ConvTy =
2040 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00002041 if (ConvTy != Compatible &&
2042 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2043 ConvTy = Compatible;
Mike Stump11289f42009-09-09 15:08:12 +00002044
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002045 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
2046 FromType, From, Flavor);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002047 }
Sebastian Redl42e92c42009-04-12 17:16:29 +00002048
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002049 if (ToType->isReferenceType())
Anders Carlsson271e3a42009-08-27 17:30:43 +00002050 return CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002051 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002052 /*SuppressUserConversions=*/false,
2053 /*AllowExplicit=*/false,
2054 /*ForceRValue=*/false);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002055
Sebastian Redl42e92c42009-04-12 17:16:29 +00002056 if (!PerformImplicitConversion(From, ToType, Flavor,
2057 /*AllowExplicit=*/false, Elidable))
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002058 return false;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002059 if (!DiagnoseAmbiguousUserDefinedConversion(From, ToType))
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002060 return Diag(From->getSourceRange().getBegin(),
2061 diag::err_typecheck_convert_incompatible)
2062 << ToType << From->getType() << Flavor << From->getSourceRange();
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002063 return true;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002064}
2065
Douglas Gregor436424c2008-11-18 23:14:02 +00002066/// TryObjectArgumentInitialization - Try to initialize the object
2067/// parameter of the given member function (@c Method) from the
2068/// expression @p From.
2069ImplicitConversionSequence
2070Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
2071 QualType ClassType = Context.getTypeDeclType(Method->getParent());
John McCall8ccfcb52009-09-24 19:53:00 +00002072 QualType ImplicitParamType
2073 = Context.getCVRQualifiedType(ClassType, Method->getTypeQualifiers());
Douglas Gregor436424c2008-11-18 23:14:02 +00002074
2075 // Set up the conversion sequence as a "bad" conversion, to allow us
2076 // to exit early.
2077 ImplicitConversionSequence ICS;
2078 ICS.Standard.setAsIdentityConversion();
2079 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2080
2081 // We need to have an object of class type.
2082 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002083 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002084 FromType = PT->getPointeeType();
2085
2086 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002087
2088 // The implicit object parmeter is has the type "reference to cv X",
2089 // where X is the class of which the function is a member
2090 // (C++ [over.match.funcs]p4). However, when finding an implicit
2091 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002092 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002093 // (C++ [over.match.funcs]p5). We perform a simplified version of
2094 // reference binding here, that allows class rvalues to bind to
2095 // non-constant references.
2096
2097 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2098 // with the implicit object parameter (C++ [over.match.funcs]p5).
2099 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor01df9462009-11-05 00:07:36 +00002100 if (ImplicitParamType.getCVRQualifiers() != FromTypeCanon.getCVRQualifiers() &&
2101 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon))
Douglas Gregor436424c2008-11-18 23:14:02 +00002102 return ICS;
2103
2104 // Check that we have either the same type or a derived type. It
2105 // affects the conversion rank.
2106 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2107 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
2108 ICS.Standard.Second = ICK_Identity;
2109 else if (IsDerivedFrom(FromType, ClassType))
2110 ICS.Standard.Second = ICK_Derived_To_Base;
2111 else
2112 return ICS;
2113
2114 // Success. Mark this as a reference binding.
2115 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2116 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2117 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2118 ICS.Standard.ReferenceBinding = true;
2119 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002120 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002121 return ICS;
2122}
2123
2124/// PerformObjectArgumentInitialization - Perform initialization of
2125/// the implicit object parameter for the given Method with the given
2126/// expression.
2127bool
2128Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002129 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002130 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002131 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002132
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002133 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002134 FromRecordType = PT->getPointeeType();
2135 DestType = Method->getThisType(Context);
2136 } else {
2137 FromRecordType = From->getType();
2138 DestType = ImplicitParamRecordType;
2139 }
2140
Mike Stump11289f42009-09-09 15:08:12 +00002141 ImplicitConversionSequence ICS
Douglas Gregor436424c2008-11-18 23:14:02 +00002142 = TryObjectArgumentInitialization(From, Method);
2143 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2144 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002145 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002146 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002147
Douglas Gregor436424c2008-11-18 23:14:02 +00002148 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002149 CheckDerivedToBaseConversion(FromRecordType,
2150 ImplicitParamRecordType,
Douglas Gregor436424c2008-11-18 23:14:02 +00002151 From->getSourceRange().getBegin(),
2152 From->getSourceRange()))
2153 return true;
2154
Mike Stump11289f42009-09-09 15:08:12 +00002155 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson4f4aab22009-08-07 18:45:49 +00002156 /*isLvalue=*/true);
Douglas Gregor436424c2008-11-18 23:14:02 +00002157 return false;
2158}
2159
Douglas Gregor5fb53972009-01-14 15:45:31 +00002160/// TryContextuallyConvertToBool - Attempt to contextually convert the
2161/// expression From to bool (C++0x [conv]p3).
2162ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002163 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002164 // FIXME: Are these flags correct?
2165 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002166 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002167 /*ForceRValue=*/false,
2168 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002169}
2170
2171/// PerformContextuallyConvertToBool - Perform a contextual conversion
2172/// of the expression From to bool (C++0x [conv]p3).
2173bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2174 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2175 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2176 return false;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002177
2178 if (!DiagnoseAmbiguousUserDefinedConversion(From, Context.BoolTy))
2179 return Diag(From->getSourceRange().getBegin(),
2180 diag::err_typecheck_bool_condition)
2181 << From->getType() << From->getSourceRange();
2182 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002183}
2184
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002185/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002186/// candidate functions, using the given function call arguments. If
2187/// @p SuppressUserConversions, then don't allow user-defined
2188/// conversions via constructors or conversion operators.
Sebastian Redl42e92c42009-04-12 17:16:29 +00002189/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2190/// hacky way to implement the overloading rules for elidable copy
2191/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregorcabea402009-09-22 15:41:20 +00002192///
2193/// \para PartialOverloading true if we are performing "partial" overloading
2194/// based on an incomplete set of function arguments. This feature is used by
2195/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002196void
2197Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002198 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002199 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002200 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002201 bool ForceRValue,
2202 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002203 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002204 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002205 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002206 assert(!isa<CXXConversionDecl>(Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002207 "Use AddConversionCandidate for conversion functions");
Mike Stump11289f42009-09-09 15:08:12 +00002208 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002209 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002210
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002211 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002212 if (!isa<CXXConstructorDecl>(Method)) {
2213 // If we get here, it's because we're calling a member function
2214 // that is named without a member access expression (e.g.,
2215 // "this->f") that was either written explicitly or created
2216 // implicitly. This can happen with a qualified call to a member
2217 // function, e.g., X::f(). We use a NULL object as the implied
2218 // object argument (C++ [over.call.func]p3).
Mike Stump11289f42009-09-09 15:08:12 +00002219 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002220 SuppressUserConversions, ForceRValue);
2221 return;
2222 }
2223 // We treat a constructor like a non-member function, since its object
2224 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002225 }
2226
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002227 if (!CandidateSet.isNewCandidate(Function))
2228 return;
2229
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002230 // Add this candidate
2231 CandidateSet.push_back(OverloadCandidate());
2232 OverloadCandidate& Candidate = CandidateSet.back();
2233 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002234 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002235 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002236 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002237
2238 unsigned NumArgsInProto = Proto->getNumArgs();
2239
2240 // (C++ 13.3.2p2): A candidate function having fewer than m
2241 // parameters is viable only if it has an ellipsis in its parameter
2242 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002243 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2244 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002245 Candidate.Viable = false;
2246 return;
2247 }
2248
2249 // (C++ 13.3.2p2): A candidate function having more than m parameters
2250 // is viable only if the (m+1)st parameter has a default argument
2251 // (8.3.6). For the purposes of overload resolution, the
2252 // parameter list is truncated on the right, so that there are
2253 // exactly m parameters.
2254 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002255 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002256 // Not enough arguments.
2257 Candidate.Viable = false;
2258 return;
2259 }
2260
2261 // Determine the implicit conversion sequences for each of the
2262 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002263 Candidate.Conversions.resize(NumArgs);
2264 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2265 if (ArgIdx < NumArgsInProto) {
2266 // (C++ 13.3.2p3): for F to be a viable function, there shall
2267 // exist for each argument an implicit conversion sequence
2268 // (13.3.3.1) that converts that argument to the corresponding
2269 // parameter of F.
2270 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002271 Candidate.Conversions[ArgIdx]
2272 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002273 SuppressUserConversions, ForceRValue,
2274 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002275 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002276 == ImplicitConversionSequence::BadConversion) {
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002277 // 13.3.3.1-p10 If several different sequences of conversions exist that
2278 // each convert the argument to the parameter type, the implicit conversion
2279 // sequence associated with the parameter is defined to be the unique conversion
2280 // sequence designated the ambiguous conversion sequence. For the purpose of
2281 // ranking implicit conversion sequences as described in 13.3.3.2, the ambiguous
2282 // conversion sequence is treated as a user-defined sequence that is
2283 // indistinguishable from any other user-defined conversion sequence
Fariborz Jahanian91ae9fd2009-09-29 17:31:54 +00002284 if (!Candidate.Conversions[ArgIdx].ConversionFunctionSet.empty()) {
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002285 Candidate.Conversions[ArgIdx].ConversionKind =
2286 ImplicitConversionSequence::UserDefinedConversion;
Fariborz Jahanian91ae9fd2009-09-29 17:31:54 +00002287 // Set the conversion function to one of them. As due to ambiguity,
2288 // they carry the same weight and is needed for overload resolution
2289 // later.
2290 Candidate.Conversions[ArgIdx].UserDefined.ConversionFunction =
2291 Candidate.Conversions[ArgIdx].ConversionFunctionSet[0];
2292 }
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002293 else {
2294 Candidate.Viable = false;
2295 break;
2296 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002297 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002298 } else {
2299 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2300 // argument for which there is no corresponding parameter is
2301 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002302 Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002303 = ImplicitConversionSequence::EllipsisConversion;
2304 }
2305 }
2306}
2307
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002308/// \brief Add all of the function declarations in the given function set to
2309/// the overload canddiate set.
2310void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2311 Expr **Args, unsigned NumArgs,
2312 OverloadCandidateSet& CandidateSet,
2313 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002314 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002315 FEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00002316 F != FEnd; ++F) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002317 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2318 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2319 AddMethodCandidate(cast<CXXMethodDecl>(FD),
2320 Args[0], Args + 1, NumArgs - 1,
2321 CandidateSet, SuppressUserConversions);
2322 else
2323 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2324 SuppressUserConversions);
2325 } else {
2326 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2327 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2328 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
2329 AddMethodTemplateCandidate(FunTmpl,
Douglas Gregor89026b52009-06-30 23:57:56 +00002330 /*FIXME: explicit args */false, 0, 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002331 Args[0], Args + 1, NumArgs - 1,
2332 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002333 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002334 else
2335 AddTemplateOverloadCandidate(FunTmpl,
2336 /*FIXME: explicit args */false, 0, 0,
2337 Args, NumArgs, CandidateSet,
2338 SuppressUserConversions);
2339 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002340 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002341}
2342
Douglas Gregor436424c2008-11-18 23:14:02 +00002343/// AddMethodCandidate - Adds the given C++ member function to the set
2344/// of candidate functions, using the given function call arguments
2345/// and the object argument (@c Object). For example, in a call
2346/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2347/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2348/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002349/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2350/// a slightly hacky way to implement the overloading rules for elidable copy
2351/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002352void
Douglas Gregor436424c2008-11-18 23:14:02 +00002353Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2354 Expr **Args, unsigned NumArgs,
2355 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002356 bool SuppressUserConversions, bool ForceRValue) {
2357 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002358 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002359 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002360 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor436424c2008-11-18 23:14:02 +00002361 "Use AddConversionCandidate for conversion functions");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002362 assert(!isa<CXXConstructorDecl>(Method) &&
2363 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002364
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002365 if (!CandidateSet.isNewCandidate(Method))
2366 return;
2367
Douglas Gregor436424c2008-11-18 23:14:02 +00002368 // Add this candidate
2369 CandidateSet.push_back(OverloadCandidate());
2370 OverloadCandidate& Candidate = CandidateSet.back();
2371 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002372 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002373 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002374
2375 unsigned NumArgsInProto = Proto->getNumArgs();
2376
2377 // (C++ 13.3.2p2): A candidate function having fewer than m
2378 // parameters is viable only if it has an ellipsis in its parameter
2379 // list (8.3.5).
2380 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2381 Candidate.Viable = false;
2382 return;
2383 }
2384
2385 // (C++ 13.3.2p2): A candidate function having more than m parameters
2386 // is viable only if the (m+1)st parameter has a default argument
2387 // (8.3.6). For the purposes of overload resolution, the
2388 // parameter list is truncated on the right, so that there are
2389 // exactly m parameters.
2390 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2391 if (NumArgs < MinRequiredArgs) {
2392 // Not enough arguments.
2393 Candidate.Viable = false;
2394 return;
2395 }
2396
2397 Candidate.Viable = true;
2398 Candidate.Conversions.resize(NumArgs + 1);
2399
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002400 if (Method->isStatic() || !Object)
2401 // The implicit object argument is ignored.
2402 Candidate.IgnoreObjectArgument = true;
2403 else {
2404 // Determine the implicit conversion sequence for the object
2405 // parameter.
2406 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
Mike Stump11289f42009-09-09 15:08:12 +00002407 if (Candidate.Conversions[0].ConversionKind
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002408 == ImplicitConversionSequence::BadConversion) {
2409 Candidate.Viable = false;
2410 return;
2411 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002412 }
2413
2414 // Determine the implicit conversion sequences for each of the
2415 // arguments.
2416 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2417 if (ArgIdx < NumArgsInProto) {
2418 // (C++ 13.3.2p3): for F to be a viable function, there shall
2419 // exist for each argument an implicit conversion sequence
2420 // (13.3.3.1) that converts that argument to the corresponding
2421 // parameter of F.
2422 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002423 Candidate.Conversions[ArgIdx + 1]
2424 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002425 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002426 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002427 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002428 == ImplicitConversionSequence::BadConversion) {
2429 Candidate.Viable = false;
2430 break;
2431 }
2432 } else {
2433 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2434 // argument for which there is no corresponding parameter is
2435 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002436 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002437 = ImplicitConversionSequence::EllipsisConversion;
2438 }
2439 }
2440}
2441
Douglas Gregor97628d62009-08-21 00:16:32 +00002442/// \brief Add a C++ member function template as a candidate to the candidate
2443/// set, using template argument deduction to produce an appropriate member
2444/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002445void
Douglas Gregor97628d62009-08-21 00:16:32 +00002446Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2447 bool HasExplicitTemplateArgs,
John McCall0ad16662009-10-29 08:12:44 +00002448 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002449 unsigned NumExplicitTemplateArgs,
2450 Expr *Object, Expr **Args, unsigned NumArgs,
2451 OverloadCandidateSet& CandidateSet,
2452 bool SuppressUserConversions,
2453 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002454 if (!CandidateSet.isNewCandidate(MethodTmpl))
2455 return;
2456
Douglas Gregor97628d62009-08-21 00:16:32 +00002457 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002458 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002459 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002460 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002461 // candidate functions in the usual way.113) A given name can refer to one
2462 // or more function templates and also to a set of overloaded non-template
2463 // functions. In such a case, the candidate functions generated from each
2464 // function template are combined with the set of non-template candidate
2465 // functions.
2466 TemplateDeductionInfo Info(Context);
2467 FunctionDecl *Specialization = 0;
2468 if (TemplateDeductionResult Result
2469 = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2470 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2471 Args, NumArgs, Specialization, Info)) {
2472 // FIXME: Record what happened with template argument deduction, so
2473 // that we can give the user a beautiful diagnostic.
2474 (void)Result;
2475 return;
2476 }
Mike Stump11289f42009-09-09 15:08:12 +00002477
Douglas Gregor97628d62009-08-21 00:16:32 +00002478 // Add the function template specialization produced by template argument
2479 // deduction as a candidate.
2480 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002481 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002482 "Specialization is not a member function?");
Mike Stump11289f42009-09-09 15:08:12 +00002483 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002484 CandidateSet, SuppressUserConversions, ForceRValue);
2485}
2486
Douglas Gregor05155d82009-08-21 23:19:43 +00002487/// \brief Add a C++ function template specialization as a candidate
2488/// in the candidate set, using template argument deduction to produce
2489/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002490void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002491Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor89026b52009-06-30 23:57:56 +00002492 bool HasExplicitTemplateArgs,
John McCall0ad16662009-10-29 08:12:44 +00002493 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00002494 unsigned NumExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002495 Expr **Args, unsigned NumArgs,
2496 OverloadCandidateSet& CandidateSet,
2497 bool SuppressUserConversions,
2498 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002499 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2500 return;
2501
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002502 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002503 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002504 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002505 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002506 // candidate functions in the usual way.113) A given name can refer to one
2507 // or more function templates and also to a set of overloaded non-template
2508 // functions. In such a case, the candidate functions generated from each
2509 // function template are combined with the set of non-template candidate
2510 // functions.
2511 TemplateDeductionInfo Info(Context);
2512 FunctionDecl *Specialization = 0;
2513 if (TemplateDeductionResult Result
Douglas Gregor89026b52009-06-30 23:57:56 +00002514 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2515 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2516 Args, NumArgs, Specialization, Info)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002517 // FIXME: Record what happened with template argument deduction, so
2518 // that we can give the user a beautiful diagnostic.
2519 (void)Result;
2520 return;
2521 }
Mike Stump11289f42009-09-09 15:08:12 +00002522
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002523 // Add the function template specialization produced by template argument
2524 // deduction as a candidate.
2525 assert(Specialization && "Missing function template specialization?");
2526 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2527 SuppressUserConversions, ForceRValue);
2528}
Mike Stump11289f42009-09-09 15:08:12 +00002529
Douglas Gregora1f013e2008-11-07 22:36:19 +00002530/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002531/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002532/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002533/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002534/// (which may or may not be the same type as the type that the
2535/// conversion function produces).
2536void
2537Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2538 Expr *From, QualType ToType,
2539 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002540 assert(!Conversion->getDescribedFunctionTemplate() &&
2541 "Conversion function templates use AddTemplateConversionCandidate");
2542
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002543 if (!CandidateSet.isNewCandidate(Conversion))
2544 return;
2545
Douglas Gregora1f013e2008-11-07 22:36:19 +00002546 // Add this candidate
2547 CandidateSet.push_back(OverloadCandidate());
2548 OverloadCandidate& Candidate = CandidateSet.back();
2549 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002550 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002551 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002552 Candidate.FinalConversion.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00002553 Candidate.FinalConversion.FromTypePtr
Douglas Gregora1f013e2008-11-07 22:36:19 +00002554 = Conversion->getConversionType().getAsOpaquePtr();
2555 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2556
Douglas Gregor436424c2008-11-18 23:14:02 +00002557 // Determine the implicit conversion sequence for the implicit
2558 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002559 Candidate.Viable = true;
2560 Candidate.Conversions.resize(1);
Douglas Gregor436424c2008-11-18 23:14:02 +00002561 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002562 // Conversion functions to a different type in the base class is visible in
2563 // the derived class. So, a derived to base conversion should not participate
2564 // in overload resolution.
2565 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2566 Candidate.Conversions[0].Standard.Second = ICK_Identity;
Mike Stump11289f42009-09-09 15:08:12 +00002567 if (Candidate.Conversions[0].ConversionKind
Douglas Gregora1f013e2008-11-07 22:36:19 +00002568 == ImplicitConversionSequence::BadConversion) {
2569 Candidate.Viable = false;
2570 return;
2571 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002572
2573 // We won't go through a user-define type conversion function to convert a
2574 // derived to base as such conversions are given Conversion Rank. They only
2575 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2576 QualType FromCanon
2577 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2578 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2579 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2580 Candidate.Viable = false;
2581 return;
2582 }
2583
Douglas Gregora1f013e2008-11-07 22:36:19 +00002584
2585 // To determine what the conversion from the result of calling the
2586 // conversion function to the type we're eventually trying to
2587 // convert to (ToType), we need to synthesize a call to the
2588 // conversion function and attempt copy initialization from it. This
2589 // makes sure that we get the right semantics with respect to
2590 // lvalues/rvalues and the type. Fortunately, we can allocate this
2591 // call on the stack and we don't need its arguments to be
2592 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002593 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregora1f013e2008-11-07 22:36:19 +00002594 SourceLocation());
2595 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00002596 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregora11693b2008-11-12 17:17:38 +00002597 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002598
2599 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002600 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2601 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002602 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002603 Conversion->getConversionType().getNonReferenceType(),
2604 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002605 ImplicitConversionSequence ICS =
2606 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002607 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002608 /*ForceRValue=*/false,
2609 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002610
Douglas Gregora1f013e2008-11-07 22:36:19 +00002611 switch (ICS.ConversionKind) {
2612 case ImplicitConversionSequence::StandardConversion:
2613 Candidate.FinalConversion = ICS.Standard;
2614 break;
2615
2616 case ImplicitConversionSequence::BadConversion:
2617 Candidate.Viable = false;
2618 break;
2619
2620 default:
Mike Stump11289f42009-09-09 15:08:12 +00002621 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002622 "Can only end up with a standard conversion sequence or failure");
2623 }
2624}
2625
Douglas Gregor05155d82009-08-21 23:19:43 +00002626/// \brief Adds a conversion function template specialization
2627/// candidate to the overload set, using template argument deduction
2628/// to deduce the template arguments of the conversion function
2629/// template from the type that we are converting to (C++
2630/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002631void
Douglas Gregor05155d82009-08-21 23:19:43 +00002632Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2633 Expr *From, QualType ToType,
2634 OverloadCandidateSet &CandidateSet) {
2635 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2636 "Only conversion function templates permitted here");
2637
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002638 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2639 return;
2640
Douglas Gregor05155d82009-08-21 23:19:43 +00002641 TemplateDeductionInfo Info(Context);
2642 CXXConversionDecl *Specialization = 0;
2643 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002644 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002645 Specialization, Info)) {
2646 // FIXME: Record what happened with template argument deduction, so
2647 // that we can give the user a beautiful diagnostic.
2648 (void)Result;
2649 return;
2650 }
Mike Stump11289f42009-09-09 15:08:12 +00002651
Douglas Gregor05155d82009-08-21 23:19:43 +00002652 // Add the conversion function template specialization produced by
2653 // template argument deduction as a candidate.
2654 assert(Specialization && "Missing function template specialization?");
2655 AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2656}
2657
Douglas Gregorab7897a2008-11-19 22:57:39 +00002658/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2659/// converts the given @c Object to a function pointer via the
2660/// conversion function @c Conversion, and then attempts to call it
2661/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2662/// the type of function that we'll eventually be calling.
2663void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002664 const FunctionProtoType *Proto,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002665 Expr *Object, Expr **Args, unsigned NumArgs,
2666 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002667 if (!CandidateSet.isNewCandidate(Conversion))
2668 return;
2669
Douglas Gregorab7897a2008-11-19 22:57:39 +00002670 CandidateSet.push_back(OverloadCandidate());
2671 OverloadCandidate& Candidate = CandidateSet.back();
2672 Candidate.Function = 0;
2673 Candidate.Surrogate = Conversion;
2674 Candidate.Viable = true;
2675 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002676 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002677 Candidate.Conversions.resize(NumArgs + 1);
2678
2679 // Determine the implicit conversion sequence for the implicit
2680 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002681 ImplicitConversionSequence ObjectInit
Douglas Gregorab7897a2008-11-19 22:57:39 +00002682 = TryObjectArgumentInitialization(Object, Conversion);
2683 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2684 Candidate.Viable = false;
2685 return;
2686 }
2687
2688 // The first conversion is actually a user-defined conversion whose
2689 // first conversion is ObjectInit's standard conversion (which is
2690 // effectively a reference binding). Record it as such.
Mike Stump11289f42009-09-09 15:08:12 +00002691 Candidate.Conversions[0].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002692 = ImplicitConversionSequence::UserDefinedConversion;
2693 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2694 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002695 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002696 = Candidate.Conversions[0].UserDefined.Before;
2697 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2698
Mike Stump11289f42009-09-09 15:08:12 +00002699 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00002700 unsigned NumArgsInProto = Proto->getNumArgs();
2701
2702 // (C++ 13.3.2p2): A candidate function having fewer than m
2703 // parameters is viable only if it has an ellipsis in its parameter
2704 // list (8.3.5).
2705 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2706 Candidate.Viable = false;
2707 return;
2708 }
2709
2710 // Function types don't have any default arguments, so just check if
2711 // we have enough arguments.
2712 if (NumArgs < NumArgsInProto) {
2713 // Not enough arguments.
2714 Candidate.Viable = false;
2715 return;
2716 }
2717
2718 // Determine the implicit conversion sequences for each of the
2719 // arguments.
2720 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2721 if (ArgIdx < NumArgsInProto) {
2722 // (C++ 13.3.2p3): for F to be a viable function, there shall
2723 // exist for each argument an implicit conversion sequence
2724 // (13.3.3.1) that converts that argument to the corresponding
2725 // parameter of F.
2726 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002727 Candidate.Conversions[ArgIdx + 1]
2728 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002729 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002730 /*ForceRValue=*/false,
2731 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002732 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002733 == ImplicitConversionSequence::BadConversion) {
2734 Candidate.Viable = false;
2735 break;
2736 }
2737 } else {
2738 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2739 // argument for which there is no corresponding parameter is
2740 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002741 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002742 = ImplicitConversionSequence::EllipsisConversion;
2743 }
2744 }
2745}
2746
Mike Stump87c57ac2009-05-16 07:39:55 +00002747// FIXME: This will eventually be removed, once we've migrated all of the
2748// operator overloading logic over to the scheme used by binary operators, which
2749// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002750void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002751 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00002752 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002753 OverloadCandidateSet& CandidateSet,
2754 SourceRange OpRange) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002755 FunctionSet Functions;
2756
2757 QualType T1 = Args[0]->getType();
2758 QualType T2;
2759 if (NumArgs > 1)
2760 T2 = Args[1]->getType();
2761
2762 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002763 if (S)
2764 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Sebastian Redlc057f422009-10-23 19:23:15 +00002765 ArgumentDependentLookup(OpName, /*Operator*/true, Args, NumArgs, Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002766 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2767 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002768 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002769}
2770
2771/// \brief Add overload candidates for overloaded operators that are
2772/// member functions.
2773///
2774/// Add the overloaded operator candidates that are member functions
2775/// for the operator Op that was used in an operator expression such
2776/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2777/// CandidateSet will store the added overload candidates. (C++
2778/// [over.match.oper]).
2779void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2780 SourceLocation OpLoc,
2781 Expr **Args, unsigned NumArgs,
2782 OverloadCandidateSet& CandidateSet,
2783 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002784 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2785
2786 // C++ [over.match.oper]p3:
2787 // For a unary operator @ with an operand of a type whose
2788 // cv-unqualified version is T1, and for a binary operator @ with
2789 // a left operand of a type whose cv-unqualified version is T1 and
2790 // a right operand of a type whose cv-unqualified version is T2,
2791 // three sets of candidate functions, designated member
2792 // candidates, non-member candidates and built-in candidates, are
2793 // constructed as follows:
2794 QualType T1 = Args[0]->getType();
2795 QualType T2;
2796 if (NumArgs > 1)
2797 T2 = Args[1]->getType();
2798
2799 // -- If T1 is a class type, the set of member candidates is the
2800 // result of the qualified lookup of T1::operator@
2801 // (13.3.1.1.1); otherwise, the set of member candidates is
2802 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002803 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002804 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00002805 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002806 return;
Mike Stump11289f42009-09-09 15:08:12 +00002807
John McCall9f3059a2009-10-09 21:13:30 +00002808 LookupResult Operators;
2809 LookupQualifiedName(Operators, T1Rec->getDecl(), OpName,
2810 LookupOrdinaryName, false);
Mike Stump11289f42009-09-09 15:08:12 +00002811 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002812 OperEnd = Operators.end();
2813 Oper != OperEnd;
Douglas Gregor4aa2dc42009-10-14 16:50:13 +00002814 ++Oper) {
2815 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Oper)) {
2816 AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet,
2817 /*SuppressUserConversions=*/false);
2818 continue;
2819 }
2820
2821 assert(isa<FunctionTemplateDecl>(*Oper) &&
2822 isa<CXXMethodDecl>(cast<FunctionTemplateDecl>(*Oper)
2823 ->getTemplatedDecl()) &&
2824 "Expected a member function template");
2825 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Oper), false, 0, 0,
2826 Args[0], Args+1, NumArgs - 1, CandidateSet,
2827 /*SuppressUserConversions=*/false);
2828 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002829 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002830}
2831
Douglas Gregora11693b2008-11-12 17:17:38 +00002832/// AddBuiltinCandidate - Add a candidate for a built-in
2833/// operator. ResultTy and ParamTys are the result and parameter types
2834/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00002835/// arguments being passed to the candidate. IsAssignmentOperator
2836/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00002837/// operator. NumContextualBoolArguments is the number of arguments
2838/// (at the beginning of the argument list) that will be contextually
2839/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00002840void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00002841 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00002842 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002843 bool IsAssignmentOperator,
2844 unsigned NumContextualBoolArguments) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002845 // Add this candidate
2846 CandidateSet.push_back(OverloadCandidate());
2847 OverloadCandidate& Candidate = CandidateSet.back();
2848 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00002849 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002850 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00002851 Candidate.BuiltinTypes.ResultTy = ResultTy;
2852 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2853 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2854
2855 // Determine the implicit conversion sequences for each of the
2856 // arguments.
2857 Candidate.Viable = true;
2858 Candidate.Conversions.resize(NumArgs);
2859 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00002860 // C++ [over.match.oper]p4:
2861 // For the built-in assignment operators, conversions of the
2862 // left operand are restricted as follows:
2863 // -- no temporaries are introduced to hold the left operand, and
2864 // -- no user-defined conversions are applied to the left
2865 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00002866 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00002867 //
2868 // We block these conversions by turning off user-defined
2869 // conversions, since that is the only way that initialization of
2870 // a reference to a non-class type can occur from something that
2871 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002872 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00002873 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00002874 "Contextual conversion to bool requires bool type");
2875 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2876 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002877 Candidate.Conversions[ArgIdx]
2878 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00002879 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00002880 /*ForceRValue=*/false,
2881 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002882 }
Mike Stump11289f42009-09-09 15:08:12 +00002883 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002884 == ImplicitConversionSequence::BadConversion) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002885 Candidate.Viable = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002886 break;
2887 }
Douglas Gregora11693b2008-11-12 17:17:38 +00002888 }
2889}
2890
2891/// BuiltinCandidateTypeSet - A set of types that will be used for the
2892/// candidate operator functions for built-in operators (C++
2893/// [over.built]). The types are separated into pointer types and
2894/// enumeration types.
2895class BuiltinCandidateTypeSet {
2896 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002897 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00002898
2899 /// PointerTypes - The set of pointer types that will be used in the
2900 /// built-in candidates.
2901 TypeSet PointerTypes;
2902
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002903 /// MemberPointerTypes - The set of member pointer types that will be
2904 /// used in the built-in candidates.
2905 TypeSet MemberPointerTypes;
2906
Douglas Gregora11693b2008-11-12 17:17:38 +00002907 /// EnumerationTypes - The set of enumeration types that will be
2908 /// used in the built-in candidates.
2909 TypeSet EnumerationTypes;
2910
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002911 /// Sema - The semantic analysis instance where we are building the
2912 /// candidate type set.
2913 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00002914
Douglas Gregora11693b2008-11-12 17:17:38 +00002915 /// Context - The AST context in which we will build the type sets.
2916 ASTContext &Context;
2917
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00002918 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
2919 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002920 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00002921
2922public:
2923 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002924 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00002925
Mike Stump11289f42009-09-09 15:08:12 +00002926 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002927 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00002928
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002929 void AddTypesConvertedFrom(QualType Ty,
2930 SourceLocation Loc,
2931 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00002932 bool AllowExplicitConversions,
2933 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00002934
2935 /// pointer_begin - First pointer type found;
2936 iterator pointer_begin() { return PointerTypes.begin(); }
2937
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002938 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00002939 iterator pointer_end() { return PointerTypes.end(); }
2940
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002941 /// member_pointer_begin - First member pointer type found;
2942 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2943
2944 /// member_pointer_end - Past the last member pointer type found;
2945 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2946
Douglas Gregora11693b2008-11-12 17:17:38 +00002947 /// enumeration_begin - First enumeration type found;
2948 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2949
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002950 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00002951 iterator enumeration_end() { return EnumerationTypes.end(); }
2952};
2953
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002954/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00002955/// the set of pointer types along with any more-qualified variants of
2956/// that type. For example, if @p Ty is "int const *", this routine
2957/// will add "int const *", "int const volatile *", "int const
2958/// restrict *", and "int const volatile restrict *" to the set of
2959/// pointer types. Returns true if the add of @p Ty itself succeeded,
2960/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00002961///
2962/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002963bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002964BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
2965 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00002966
Douglas Gregora11693b2008-11-12 17:17:38 +00002967 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002968 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00002969 return false;
2970
John McCall8ccfcb52009-09-24 19:53:00 +00002971 const PointerType *PointerTy = Ty->getAs<PointerType>();
2972 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00002973
John McCall8ccfcb52009-09-24 19:53:00 +00002974 QualType PointeeTy = PointerTy->getPointeeType();
2975 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00002976 bool hasVolatile = VisibleQuals.hasVolatile();
2977 bool hasRestrict = VisibleQuals.hasRestrict();
2978
John McCall8ccfcb52009-09-24 19:53:00 +00002979 // Iterate through all strict supersets of BaseCVR.
2980 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
2981 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00002982 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
2983 // in the types.
2984 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
2985 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00002986 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
2987 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00002988 }
2989
2990 return true;
2991}
2992
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002993/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2994/// to the set of pointer types along with any more-qualified variants of
2995/// that type. For example, if @p Ty is "int const *", this routine
2996/// will add "int const *", "int const volatile *", "int const
2997/// restrict *", and "int const volatile restrict *" to the set of
2998/// pointer types. Returns true if the add of @p Ty itself succeeded,
2999/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003000///
3001/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003002bool
3003BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3004 QualType Ty) {
3005 // Insert this type.
3006 if (!MemberPointerTypes.insert(Ty))
3007 return false;
3008
John McCall8ccfcb52009-09-24 19:53:00 +00003009 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3010 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003011
John McCall8ccfcb52009-09-24 19:53:00 +00003012 QualType PointeeTy = PointerTy->getPointeeType();
3013 const Type *ClassTy = PointerTy->getClass();
3014
3015 // Iterate through all strict supersets of the pointee type's CVR
3016 // qualifiers.
3017 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3018 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3019 if ((CVR | BaseCVR) != CVR) continue;
3020
3021 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3022 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003023 }
3024
3025 return true;
3026}
3027
Douglas Gregora11693b2008-11-12 17:17:38 +00003028/// AddTypesConvertedFrom - Add each of the types to which the type @p
3029/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003030/// primarily interested in pointer types and enumeration types. We also
3031/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003032/// AllowUserConversions is true if we should look at the conversion
3033/// functions of a class type, and AllowExplicitConversions if we
3034/// should also include the explicit conversion functions of a class
3035/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003036void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003037BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003038 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003039 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003040 bool AllowExplicitConversions,
3041 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003042 // Only deal with canonical types.
3043 Ty = Context.getCanonicalType(Ty);
3044
3045 // Look through reference types; they aren't part of the type of an
3046 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003047 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003048 Ty = RefTy->getPointeeType();
3049
3050 // We don't care about qualifiers on the type.
3051 Ty = Ty.getUnqualifiedType();
3052
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003053 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003054 QualType PointeeTy = PointerTy->getPointeeType();
3055
3056 // Insert our type, and its more-qualified variants, into the set
3057 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003058 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003059 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003060 } else if (Ty->isMemberPointerType()) {
3061 // Member pointers are far easier, since the pointee can't be converted.
3062 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3063 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003064 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003065 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003066 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003067 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003068 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003069 // No conversion functions in incomplete types.
3070 return;
3071 }
Mike Stump11289f42009-09-09 15:08:12 +00003072
Douglas Gregora11693b2008-11-12 17:17:38 +00003073 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003074 OverloadedFunctionDecl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003075 = ClassDecl->getVisibleConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00003076 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregora11693b2008-11-12 17:17:38 +00003077 = Conversions->function_begin();
3078 Func != Conversions->function_end(); ++Func) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003079 CXXConversionDecl *Conv;
3080 FunctionTemplateDecl *ConvTemplate;
3081 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
3082
Mike Stump11289f42009-09-09 15:08:12 +00003083 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003084 // about which builtin types we can convert to.
3085 if (ConvTemplate)
3086 continue;
3087
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003088 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003089 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003090 VisibleQuals);
3091 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003092 }
3093 }
3094 }
3095}
3096
Douglas Gregor84605ae2009-08-24 13:43:27 +00003097/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3098/// the volatile- and non-volatile-qualified assignment operators for the
3099/// given type to the candidate set.
3100static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3101 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003102 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003103 unsigned NumArgs,
3104 OverloadCandidateSet &CandidateSet) {
3105 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003106
Douglas Gregor84605ae2009-08-24 13:43:27 +00003107 // T& operator=(T&, T)
3108 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3109 ParamTypes[1] = T;
3110 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3111 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003112
Douglas Gregor84605ae2009-08-24 13:43:27 +00003113 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3114 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003115 ParamTypes[0]
3116 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003117 ParamTypes[1] = T;
3118 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003119 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003120 }
3121}
Mike Stump11289f42009-09-09 15:08:12 +00003122
Sebastian Redl1054fae2009-10-25 17:03:50 +00003123/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3124/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003125static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3126 Qualifiers VRQuals;
3127 const RecordType *TyRec;
3128 if (const MemberPointerType *RHSMPType =
3129 ArgExpr->getType()->getAs<MemberPointerType>())
3130 TyRec = cast<RecordType>(RHSMPType->getClass());
3131 else
3132 TyRec = ArgExpr->getType()->getAs<RecordType>();
3133 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003134 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003135 VRQuals.addVolatile();
3136 VRQuals.addRestrict();
3137 return VRQuals;
3138 }
3139
3140 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
3141 OverloadedFunctionDecl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003142 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003143
3144 for (OverloadedFunctionDecl::function_iterator Func
3145 = Conversions->function_begin();
3146 Func != Conversions->function_end(); ++Func) {
3147 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*Func)) {
3148 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3149 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3150 CanTy = ResTypeRef->getPointeeType();
3151 // Need to go down the pointer/mempointer chain and add qualifiers
3152 // as see them.
3153 bool done = false;
3154 while (!done) {
3155 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3156 CanTy = ResTypePtr->getPointeeType();
3157 else if (const MemberPointerType *ResTypeMPtr =
3158 CanTy->getAs<MemberPointerType>())
3159 CanTy = ResTypeMPtr->getPointeeType();
3160 else
3161 done = true;
3162 if (CanTy.isVolatileQualified())
3163 VRQuals.addVolatile();
3164 if (CanTy.isRestrictQualified())
3165 VRQuals.addRestrict();
3166 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3167 return VRQuals;
3168 }
3169 }
3170 }
3171 return VRQuals;
3172}
3173
Douglas Gregord08452f2008-11-19 15:42:04 +00003174/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3175/// operator overloads to the candidate set (C++ [over.built]), based
3176/// on the operator @p Op and the arguments given. For example, if the
3177/// operator is a binary '+', this routine might add "int
3178/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003179void
Mike Stump11289f42009-09-09 15:08:12 +00003180Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003181 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003182 Expr **Args, unsigned NumArgs,
3183 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003184 // The set of "promoted arithmetic types", which are the arithmetic
3185 // types are that preserved by promotion (C++ [over.built]p2). Note
3186 // that the first few of these types are the promoted integral
3187 // types; these types need to be first.
3188 // FIXME: What about complex?
3189 const unsigned FirstIntegralType = 0;
3190 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003191 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003192 LastPromotedIntegralType = 13;
3193 const unsigned FirstPromotedArithmeticType = 7,
3194 LastPromotedArithmeticType = 16;
3195 const unsigned NumArithmeticTypes = 16;
3196 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003197 Context.BoolTy, Context.CharTy, Context.WCharTy,
3198// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003199 Context.SignedCharTy, Context.ShortTy,
3200 Context.UnsignedCharTy, Context.UnsignedShortTy,
3201 Context.IntTy, Context.LongTy, Context.LongLongTy,
3202 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3203 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3204 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003205 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3206 "Invalid first promoted integral type");
3207 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3208 == Context.UnsignedLongLongTy &&
3209 "Invalid last promoted integral type");
3210 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3211 "Invalid first promoted arithmetic type");
3212 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3213 == Context.LongDoubleTy &&
3214 "Invalid last promoted arithmetic type");
3215
Douglas Gregora11693b2008-11-12 17:17:38 +00003216 // Find all of the types that the arguments can convert to, but only
3217 // if the operator we're looking at has built-in operator candidates
3218 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003219 Qualifiers VisibleTypeConversionsQuals;
3220 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003221 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3222 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3223
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003224 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003225 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3226 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003227 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003228 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003229 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003230 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003231 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003232 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003233 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003234 true,
3235 (Op == OO_Exclaim ||
3236 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003237 Op == OO_PipePipe),
3238 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003239 }
3240
3241 bool isComparison = false;
3242 switch (Op) {
3243 case OO_None:
3244 case NUM_OVERLOADED_OPERATORS:
3245 assert(false && "Expected an overloaded operator");
3246 break;
3247
Douglas Gregord08452f2008-11-19 15:42:04 +00003248 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003249 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003250 goto UnaryStar;
3251 else
3252 goto BinaryStar;
3253 break;
3254
3255 case OO_Plus: // '+' is either unary or binary
3256 if (NumArgs == 1)
3257 goto UnaryPlus;
3258 else
3259 goto BinaryPlus;
3260 break;
3261
3262 case OO_Minus: // '-' is either unary or binary
3263 if (NumArgs == 1)
3264 goto UnaryMinus;
3265 else
3266 goto BinaryMinus;
3267 break;
3268
3269 case OO_Amp: // '&' is either unary or binary
3270 if (NumArgs == 1)
3271 goto UnaryAmp;
3272 else
3273 goto BinaryAmp;
3274
3275 case OO_PlusPlus:
3276 case OO_MinusMinus:
3277 // C++ [over.built]p3:
3278 //
3279 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3280 // is either volatile or empty, there exist candidate operator
3281 // functions of the form
3282 //
3283 // VQ T& operator++(VQ T&);
3284 // T operator++(VQ T&, int);
3285 //
3286 // C++ [over.built]p4:
3287 //
3288 // For every pair (T, VQ), where T is an arithmetic type other
3289 // than bool, and VQ is either volatile or empty, there exist
3290 // candidate operator functions of the form
3291 //
3292 // VQ T& operator--(VQ T&);
3293 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003294 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003295 Arith < NumArithmeticTypes; ++Arith) {
3296 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003297 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003298 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003299
3300 // Non-volatile version.
3301 if (NumArgs == 1)
3302 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3303 else
3304 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003305 // heuristic to reduce number of builtin candidates in the set.
3306 // Add volatile version only if there are conversions to a volatile type.
3307 if (VisibleTypeConversionsQuals.hasVolatile()) {
3308 // Volatile version
3309 ParamTypes[0]
3310 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3311 if (NumArgs == 1)
3312 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3313 else
3314 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3315 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003316 }
3317
3318 // C++ [over.built]p5:
3319 //
3320 // For every pair (T, VQ), where T is a cv-qualified or
3321 // cv-unqualified object type, and VQ is either volatile or
3322 // empty, there exist candidate operator functions of the form
3323 //
3324 // T*VQ& operator++(T*VQ&);
3325 // T*VQ& operator--(T*VQ&);
3326 // T* operator++(T*VQ&, int);
3327 // T* operator--(T*VQ&, int);
3328 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3329 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3330 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003331 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003332 continue;
3333
Mike Stump11289f42009-09-09 15:08:12 +00003334 QualType ParamTypes[2] = {
3335 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003336 };
Mike Stump11289f42009-09-09 15:08:12 +00003337
Douglas Gregord08452f2008-11-19 15:42:04 +00003338 // Without volatile
3339 if (NumArgs == 1)
3340 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3341 else
3342 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3343
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003344 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3345 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003346 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003347 ParamTypes[0]
3348 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003349 if (NumArgs == 1)
3350 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3351 else
3352 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3353 }
3354 }
3355 break;
3356
3357 UnaryStar:
3358 // C++ [over.built]p6:
3359 // For every cv-qualified or cv-unqualified object type T, there
3360 // exist candidate operator functions of the form
3361 //
3362 // T& operator*(T*);
3363 //
3364 // C++ [over.built]p7:
3365 // For every function type T, there exist candidate operator
3366 // functions of the form
3367 // T& operator*(T*);
3368 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3369 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3370 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003371 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003372 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003373 &ParamTy, Args, 1, CandidateSet);
3374 }
3375 break;
3376
3377 UnaryPlus:
3378 // C++ [over.built]p8:
3379 // For every type T, there exist candidate operator functions of
3380 // the form
3381 //
3382 // T* operator+(T*);
3383 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3384 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3385 QualType ParamTy = *Ptr;
3386 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3387 }
Mike Stump11289f42009-09-09 15:08:12 +00003388
Douglas Gregord08452f2008-11-19 15:42:04 +00003389 // Fall through
3390
3391 UnaryMinus:
3392 // C++ [over.built]p9:
3393 // For every promoted arithmetic type T, there exist candidate
3394 // operator functions of the form
3395 //
3396 // T operator+(T);
3397 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003398 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003399 Arith < LastPromotedArithmeticType; ++Arith) {
3400 QualType ArithTy = ArithmeticTypes[Arith];
3401 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3402 }
3403 break;
3404
3405 case OO_Tilde:
3406 // C++ [over.built]p10:
3407 // For every promoted integral type T, there exist candidate
3408 // operator functions of the form
3409 //
3410 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003411 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003412 Int < LastPromotedIntegralType; ++Int) {
3413 QualType IntTy = ArithmeticTypes[Int];
3414 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3415 }
3416 break;
3417
Douglas Gregora11693b2008-11-12 17:17:38 +00003418 case OO_New:
3419 case OO_Delete:
3420 case OO_Array_New:
3421 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003422 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003423 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003424 break;
3425
3426 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003427 UnaryAmp:
3428 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003429 // C++ [over.match.oper]p3:
3430 // -- For the operator ',', the unary operator '&', or the
3431 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003432 break;
3433
Douglas Gregor84605ae2009-08-24 13:43:27 +00003434 case OO_EqualEqual:
3435 case OO_ExclaimEqual:
3436 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003437 // For every pointer to member type T, there exist candidate operator
3438 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003439 //
3440 // bool operator==(T,T);
3441 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003442 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003443 MemPtr = CandidateTypes.member_pointer_begin(),
3444 MemPtrEnd = CandidateTypes.member_pointer_end();
3445 MemPtr != MemPtrEnd;
3446 ++MemPtr) {
3447 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3448 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3449 }
Mike Stump11289f42009-09-09 15:08:12 +00003450
Douglas Gregor84605ae2009-08-24 13:43:27 +00003451 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003452
Douglas Gregora11693b2008-11-12 17:17:38 +00003453 case OO_Less:
3454 case OO_Greater:
3455 case OO_LessEqual:
3456 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003457 // C++ [over.built]p15:
3458 //
3459 // For every pointer or enumeration type T, there exist
3460 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003461 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003462 // bool operator<(T, T);
3463 // bool operator>(T, T);
3464 // bool operator<=(T, T);
3465 // bool operator>=(T, T);
3466 // bool operator==(T, T);
3467 // bool operator!=(T, T);
3468 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3469 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3470 QualType ParamTypes[2] = { *Ptr, *Ptr };
3471 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3472 }
Mike Stump11289f42009-09-09 15:08:12 +00003473 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003474 = CandidateTypes.enumeration_begin();
3475 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3476 QualType ParamTypes[2] = { *Enum, *Enum };
3477 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3478 }
3479
3480 // Fall through.
3481 isComparison = true;
3482
Douglas Gregord08452f2008-11-19 15:42:04 +00003483 BinaryPlus:
3484 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003485 if (!isComparison) {
3486 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3487
3488 // C++ [over.built]p13:
3489 //
3490 // For every cv-qualified or cv-unqualified object type T
3491 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003492 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003493 // T* operator+(T*, ptrdiff_t);
3494 // T& operator[](T*, ptrdiff_t); [BELOW]
3495 // T* operator-(T*, ptrdiff_t);
3496 // T* operator+(ptrdiff_t, T*);
3497 // T& operator[](ptrdiff_t, T*); [BELOW]
3498 //
3499 // C++ [over.built]p14:
3500 //
3501 // For every T, where T is a pointer to object type, there
3502 // exist candidate operator functions of the form
3503 //
3504 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003505 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003506 = CandidateTypes.pointer_begin();
3507 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3508 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3509
3510 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3511 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3512
3513 if (Op == OO_Plus) {
3514 // T* operator+(ptrdiff_t, T*);
3515 ParamTypes[0] = ParamTypes[1];
3516 ParamTypes[1] = *Ptr;
3517 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3518 } else {
3519 // ptrdiff_t operator-(T, T);
3520 ParamTypes[1] = *Ptr;
3521 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3522 Args, 2, CandidateSet);
3523 }
3524 }
3525 }
3526 // Fall through
3527
Douglas Gregora11693b2008-11-12 17:17:38 +00003528 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003529 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003530 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003531 // C++ [over.built]p12:
3532 //
3533 // For every pair of promoted arithmetic types L and R, there
3534 // exist candidate operator functions of the form
3535 //
3536 // LR operator*(L, R);
3537 // LR operator/(L, R);
3538 // LR operator+(L, R);
3539 // LR operator-(L, R);
3540 // bool operator<(L, R);
3541 // bool operator>(L, R);
3542 // bool operator<=(L, R);
3543 // bool operator>=(L, R);
3544 // bool operator==(L, R);
3545 // bool operator!=(L, R);
3546 //
3547 // where LR is the result of the usual arithmetic conversions
3548 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003549 //
3550 // C++ [over.built]p24:
3551 //
3552 // For every pair of promoted arithmetic types L and R, there exist
3553 // candidate operator functions of the form
3554 //
3555 // LR operator?(bool, L, R);
3556 //
3557 // where LR is the result of the usual arithmetic conversions
3558 // between types L and R.
3559 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003560 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003561 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003562 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003563 Right < LastPromotedArithmeticType; ++Right) {
3564 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003565 QualType Result
3566 = isComparison
3567 ? Context.BoolTy
3568 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003569 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3570 }
3571 }
3572 break;
3573
3574 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003575 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003576 case OO_Caret:
3577 case OO_Pipe:
3578 case OO_LessLess:
3579 case OO_GreaterGreater:
3580 // C++ [over.built]p17:
3581 //
3582 // For every pair of promoted integral types L and R, there
3583 // exist candidate operator functions of the form
3584 //
3585 // LR operator%(L, R);
3586 // LR operator&(L, R);
3587 // LR operator^(L, R);
3588 // LR operator|(L, R);
3589 // L operator<<(L, R);
3590 // L operator>>(L, R);
3591 //
3592 // where LR is the result of the usual arithmetic conversions
3593 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003594 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003595 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003596 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003597 Right < LastPromotedIntegralType; ++Right) {
3598 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3599 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3600 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003601 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003602 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3603 }
3604 }
3605 break;
3606
3607 case OO_Equal:
3608 // C++ [over.built]p20:
3609 //
3610 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003611 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003612 // empty, there exist candidate operator functions of the form
3613 //
3614 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003615 for (BuiltinCandidateTypeSet::iterator
3616 Enum = CandidateTypes.enumeration_begin(),
3617 EnumEnd = CandidateTypes.enumeration_end();
3618 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003619 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003620 CandidateSet);
3621 for (BuiltinCandidateTypeSet::iterator
3622 MemPtr = CandidateTypes.member_pointer_begin(),
3623 MemPtrEnd = CandidateTypes.member_pointer_end();
3624 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003625 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003626 CandidateSet);
3627 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003628
3629 case OO_PlusEqual:
3630 case OO_MinusEqual:
3631 // C++ [over.built]p19:
3632 //
3633 // For every pair (T, VQ), where T is any type and VQ is either
3634 // volatile or empty, there exist candidate operator functions
3635 // of the form
3636 //
3637 // T*VQ& operator=(T*VQ&, T*);
3638 //
3639 // C++ [over.built]p21:
3640 //
3641 // For every pair (T, VQ), where T is a cv-qualified or
3642 // cv-unqualified object type and VQ is either volatile or
3643 // empty, there exist candidate operator functions of the form
3644 //
3645 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3646 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3647 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3648 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3649 QualType ParamTypes[2];
3650 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3651
3652 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003653 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003654 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3655 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003656
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003657 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3658 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003659 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00003660 ParamTypes[0]
3661 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00003662 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3663 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003664 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003665 }
3666 // Fall through.
3667
3668 case OO_StarEqual:
3669 case OO_SlashEqual:
3670 // C++ [over.built]p18:
3671 //
3672 // For every triple (L, VQ, R), where L is an arithmetic type,
3673 // VQ is either volatile or empty, and R is a promoted
3674 // arithmetic type, there exist candidate operator functions of
3675 // the form
3676 //
3677 // VQ L& operator=(VQ L&, R);
3678 // VQ L& operator*=(VQ L&, R);
3679 // VQ L& operator/=(VQ L&, R);
3680 // VQ L& operator+=(VQ L&, R);
3681 // VQ L& operator-=(VQ L&, R);
3682 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003683 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003684 Right < LastPromotedArithmeticType; ++Right) {
3685 QualType ParamTypes[2];
3686 ParamTypes[1] = ArithmeticTypes[Right];
3687
3688 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003689 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003690 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3691 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003692
3693 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003694 if (VisibleTypeConversionsQuals.hasVolatile()) {
3695 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3696 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3697 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3698 /*IsAssigmentOperator=*/Op == OO_Equal);
3699 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003700 }
3701 }
3702 break;
3703
3704 case OO_PercentEqual:
3705 case OO_LessLessEqual:
3706 case OO_GreaterGreaterEqual:
3707 case OO_AmpEqual:
3708 case OO_CaretEqual:
3709 case OO_PipeEqual:
3710 // C++ [over.built]p22:
3711 //
3712 // For every triple (L, VQ, R), where L is an integral type, VQ
3713 // is either volatile or empty, and R is a promoted integral
3714 // type, there exist candidate operator functions of the form
3715 //
3716 // VQ L& operator%=(VQ L&, R);
3717 // VQ L& operator<<=(VQ L&, R);
3718 // VQ L& operator>>=(VQ L&, R);
3719 // VQ L& operator&=(VQ L&, R);
3720 // VQ L& operator^=(VQ L&, R);
3721 // VQ L& operator|=(VQ L&, R);
3722 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003723 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003724 Right < LastPromotedIntegralType; ++Right) {
3725 QualType ParamTypes[2];
3726 ParamTypes[1] = ArithmeticTypes[Right];
3727
3728 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003729 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003730 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00003731 if (VisibleTypeConversionsQuals.hasVolatile()) {
3732 // Add this built-in operator as a candidate (VQ is 'volatile').
3733 ParamTypes[0] = ArithmeticTypes[Left];
3734 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3735 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3736 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3737 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003738 }
3739 }
3740 break;
3741
Douglas Gregord08452f2008-11-19 15:42:04 +00003742 case OO_Exclaim: {
3743 // C++ [over.operator]p23:
3744 //
3745 // There also exist candidate operator functions of the form
3746 //
Mike Stump11289f42009-09-09 15:08:12 +00003747 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00003748 // bool operator&&(bool, bool); [BELOW]
3749 // bool operator||(bool, bool); [BELOW]
3750 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003751 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3752 /*IsAssignmentOperator=*/false,
3753 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003754 break;
3755 }
3756
Douglas Gregora11693b2008-11-12 17:17:38 +00003757 case OO_AmpAmp:
3758 case OO_PipePipe: {
3759 // C++ [over.operator]p23:
3760 //
3761 // There also exist candidate operator functions of the form
3762 //
Douglas Gregord08452f2008-11-19 15:42:04 +00003763 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00003764 // bool operator&&(bool, bool);
3765 // bool operator||(bool, bool);
3766 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00003767 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3768 /*IsAssignmentOperator=*/false,
3769 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00003770 break;
3771 }
3772
3773 case OO_Subscript:
3774 // C++ [over.built]p13:
3775 //
3776 // For every cv-qualified or cv-unqualified object type T there
3777 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003778 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003779 // T* operator+(T*, ptrdiff_t); [ABOVE]
3780 // T& operator[](T*, ptrdiff_t);
3781 // T* operator-(T*, ptrdiff_t); [ABOVE]
3782 // T* operator+(ptrdiff_t, T*); [ABOVE]
3783 // T& operator[](ptrdiff_t, T*);
3784 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3785 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3786 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003787 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003788 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00003789
3790 // T& operator[](T*, ptrdiff_t)
3791 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3792
3793 // T& operator[](ptrdiff_t, T*);
3794 ParamTypes[0] = ParamTypes[1];
3795 ParamTypes[1] = *Ptr;
3796 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3797 }
3798 break;
3799
3800 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003801 // C++ [over.built]p11:
3802 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
3803 // C1 is the same type as C2 or is a derived class of C2, T is an object
3804 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
3805 // there exist candidate operator functions of the form
3806 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
3807 // where CV12 is the union of CV1 and CV2.
3808 {
3809 for (BuiltinCandidateTypeSet::iterator Ptr =
3810 CandidateTypes.pointer_begin();
3811 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3812 QualType C1Ty = (*Ptr);
3813 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003814 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003815 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003816 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003817 if (!isa<RecordType>(C1))
3818 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003819 // heuristic to reduce number of builtin candidates in the set.
3820 // Add volatile/restrict version only if there are conversions to a
3821 // volatile/restrict type.
3822 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
3823 continue;
3824 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
3825 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003826 }
3827 for (BuiltinCandidateTypeSet::iterator
3828 MemPtr = CandidateTypes.member_pointer_begin(),
3829 MemPtrEnd = CandidateTypes.member_pointer_end();
3830 MemPtr != MemPtrEnd; ++MemPtr) {
3831 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
3832 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00003833 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003834 if (C1 != C2 && !IsDerivedFrom(C1, C2))
3835 break;
3836 QualType ParamTypes[2] = { *Ptr, *MemPtr };
3837 // build CV12 T&
3838 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003839 if (!VisibleTypeConversionsQuals.hasVolatile() &&
3840 T.isVolatileQualified())
3841 continue;
3842 if (!VisibleTypeConversionsQuals.hasRestrict() &&
3843 T.isRestrictQualified())
3844 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003845 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003846 QualType ResultTy = Context.getLValueReferenceType(T);
3847 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3848 }
3849 }
3850 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003851 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003852
3853 case OO_Conditional:
3854 // Note that we don't consider the first argument, since it has been
3855 // contextually converted to bool long ago. The candidates below are
3856 // therefore added as binary.
3857 //
3858 // C++ [over.built]p24:
3859 // For every type T, where T is a pointer or pointer-to-member type,
3860 // there exist candidate operator functions of the form
3861 //
3862 // T operator?(bool, T, T);
3863 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00003864 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3865 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3866 QualType ParamTypes[2] = { *Ptr, *Ptr };
3867 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3868 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003869 for (BuiltinCandidateTypeSet::iterator Ptr =
3870 CandidateTypes.member_pointer_begin(),
3871 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3872 QualType ParamTypes[2] = { *Ptr, *Ptr };
3873 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3874 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003875 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00003876 }
3877}
3878
Douglas Gregore254f902009-02-04 00:32:51 +00003879/// \brief Add function candidates found via argument-dependent lookup
3880/// to the set of overloading candidates.
3881///
3882/// This routine performs argument-dependent name lookup based on the
3883/// given function name (which may also be an operator name) and adds
3884/// all of the overload candidates found by ADL to the overload
3885/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00003886void
Douglas Gregore254f902009-02-04 00:32:51 +00003887Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3888 Expr **Args, unsigned NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00003889 bool HasExplicitTemplateArgs,
John McCall0ad16662009-10-29 08:12:44 +00003890 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00003891 unsigned NumExplicitTemplateArgs,
3892 OverloadCandidateSet& CandidateSet,
3893 bool PartialOverloading) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003894 FunctionSet Functions;
Douglas Gregore254f902009-02-04 00:32:51 +00003895
Douglas Gregorcabea402009-09-22 15:41:20 +00003896 // FIXME: Should we be trafficking in canonical function decls throughout?
3897
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003898 // Record all of the function candidates that we've already
3899 // added to the overload set, so that we don't add those same
3900 // candidates a second time.
3901 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3902 CandEnd = CandidateSet.end();
3903 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003904 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003905 Functions.insert(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003906 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3907 Functions.insert(FunTmpl);
3908 }
Douglas Gregore254f902009-02-04 00:32:51 +00003909
Douglas Gregorcabea402009-09-22 15:41:20 +00003910 // FIXME: Pass in the explicit template arguments?
Sebastian Redlc057f422009-10-23 19:23:15 +00003911 ArgumentDependentLookup(Name, /*Operator*/false, Args, NumArgs, Functions);
Douglas Gregore254f902009-02-04 00:32:51 +00003912
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003913 // Erase all of the candidates we already knew about.
3914 // FIXME: This is suboptimal. Is there a better way?
3915 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3916 CandEnd = CandidateSet.end();
3917 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003918 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003919 Functions.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003920 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3921 Functions.erase(FunTmpl);
3922 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003923
3924 // For each of the ADL candidates we found, add it to the overload
3925 // set.
3926 for (FunctionSet::iterator Func = Functions.begin(),
3927 FuncEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00003928 Func != FuncEnd; ++Func) {
Douglas Gregorcabea402009-09-22 15:41:20 +00003929 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
3930 if (HasExplicitTemplateArgs)
3931 continue;
3932
3933 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
3934 false, false, PartialOverloading);
3935 } else
Mike Stump11289f42009-09-09 15:08:12 +00003936 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregorcabea402009-09-22 15:41:20 +00003937 HasExplicitTemplateArgs,
3938 ExplicitTemplateArgs,
3939 NumExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003940 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00003941 }
Douglas Gregore254f902009-02-04 00:32:51 +00003942}
3943
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003944/// isBetterOverloadCandidate - Determines whether the first overload
3945/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00003946bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003947Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump11289f42009-09-09 15:08:12 +00003948 const OverloadCandidate& Cand2) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003949 // Define viable functions to be better candidates than non-viable
3950 // functions.
3951 if (!Cand2.Viable)
3952 return Cand1.Viable;
3953 else if (!Cand1.Viable)
3954 return false;
3955
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003956 // C++ [over.match.best]p1:
3957 //
3958 // -- if F is a static member function, ICS1(F) is defined such
3959 // that ICS1(F) is neither better nor worse than ICS1(G) for
3960 // any function G, and, symmetrically, ICS1(G) is neither
3961 // better nor worse than ICS1(F).
3962 unsigned StartArg = 0;
3963 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3964 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003965
Douglas Gregord3cb3562009-07-07 23:38:56 +00003966 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00003967 // A viable function F1 is defined to be a better function than another
3968 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00003969 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003970 unsigned NumArgs = Cand1.Conversions.size();
3971 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3972 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003973 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003974 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3975 Cand2.Conversions[ArgIdx])) {
3976 case ImplicitConversionSequence::Better:
3977 // Cand1 has a better conversion sequence.
3978 HasBetterConversion = true;
3979 break;
3980
3981 case ImplicitConversionSequence::Worse:
3982 // Cand1 can't be better than Cand2.
3983 return false;
3984
3985 case ImplicitConversionSequence::Indistinguishable:
3986 // Do nothing.
3987 break;
3988 }
3989 }
3990
Mike Stump11289f42009-09-09 15:08:12 +00003991 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00003992 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003993 if (HasBetterConversion)
3994 return true;
3995
Mike Stump11289f42009-09-09 15:08:12 +00003996 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00003997 // specialization, or, if not that,
3998 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
3999 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4000 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004001
4002 // -- F1 and F2 are function template specializations, and the function
4003 // template for F1 is more specialized than the template for F2
4004 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004005 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004006 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4007 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004008 if (FunctionTemplateDecl *BetterTemplate
4009 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4010 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor6010da02009-09-14 23:02:14 +00004011 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4012 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004013 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004014
Douglas Gregora1f013e2008-11-07 22:36:19 +00004015 // -- the context is an initialization by user-defined conversion
4016 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4017 // from the return type of F1 to the destination type (i.e.,
4018 // the type of the entity being initialized) is a better
4019 // conversion sequence than the standard conversion sequence
4020 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004021 if (Cand1.Function && Cand2.Function &&
4022 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004023 isa<CXXConversionDecl>(Cand2.Function)) {
4024 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4025 Cand2.FinalConversion)) {
4026 case ImplicitConversionSequence::Better:
4027 // Cand1 has a better conversion sequence.
4028 return true;
4029
4030 case ImplicitConversionSequence::Worse:
4031 // Cand1 can't be better than Cand2.
4032 return false;
4033
4034 case ImplicitConversionSequence::Indistinguishable:
4035 // Do nothing
4036 break;
4037 }
4038 }
4039
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004040 return false;
4041}
4042
Mike Stump11289f42009-09-09 15:08:12 +00004043/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004044/// within an overload candidate set.
4045///
4046/// \param CandidateSet the set of candidate functions.
4047///
4048/// \param Loc the location of the function name (or operator symbol) for
4049/// which overload resolution occurs.
4050///
Mike Stump11289f42009-09-09 15:08:12 +00004051/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004052/// function, Best points to the candidate function found.
4053///
4054/// \returns The result of overload resolution.
Mike Stump11289f42009-09-09 15:08:12 +00004055Sema::OverloadingResult
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004056Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004057 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00004058 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004059 // Find the best viable function.
4060 Best = CandidateSet.end();
4061 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4062 Cand != CandidateSet.end(); ++Cand) {
4063 if (Cand->Viable) {
4064 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4065 Best = Cand;
4066 }
4067 }
4068
4069 // If we didn't find any viable functions, abort.
4070 if (Best == CandidateSet.end())
4071 return OR_No_Viable_Function;
4072
4073 // Make sure that this function is better than every other viable
4074 // function. If not, we have an ambiguity.
4075 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4076 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004077 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004078 Cand != Best &&
Douglas Gregorab7897a2008-11-19 22:57:39 +00004079 !isBetterOverloadCandidate(*Best, *Cand)) {
4080 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004081 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004082 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004083 }
Mike Stump11289f42009-09-09 15:08:12 +00004084
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004085 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004086 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004087 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004088 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004089 return OR_Deleted;
4090
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004091 // C++ [basic.def.odr]p2:
4092 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004093 // when referred to from a potentially-evaluated expression. [Note: this
4094 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004095 // (clause 13), user-defined conversions (12.3.2), allocation function for
4096 // placement new (5.3.4), as well as non-default initialization (8.5).
4097 if (Best->Function)
4098 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004099 return OR_Success;
4100}
4101
4102/// PrintOverloadCandidates - When overload resolution fails, prints
4103/// diagnostic messages containing the candidates in the candidate
4104/// set. If OnlyViable is true, only viable candidates will be printed.
Mike Stump11289f42009-09-09 15:08:12 +00004105void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004106Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004107 bool OnlyViable,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004108 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004109 SourceLocation OpLoc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004110 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4111 LastCand = CandidateSet.end();
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004112 bool Reported = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004113 for (; Cand != LastCand; ++Cand) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004114 if (Cand->Viable || !OnlyViable) {
4115 if (Cand->Function) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00004116 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004117 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00004118 // Deleted or "unavailable" function.
4119 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
4120 << Cand->Function->isDeleted();
Douglas Gregor4fb9cde8e2009-09-15 20:11:42 +00004121 } else if (FunctionTemplateDecl *FunTmpl
4122 = Cand->Function->getPrimaryTemplate()) {
4123 // Function template specialization
4124 // FIXME: Give a better reason!
4125 Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate)
4126 << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
4127 *Cand->Function->getTemplateSpecializationArgs());
Douglas Gregor171c45a2009-02-18 21:56:37 +00004128 } else {
4129 // Normal function
Fariborz Jahanian21ccf062009-09-23 00:58:07 +00004130 bool errReported = false;
4131 if (!Cand->Viable && Cand->Conversions.size() > 0) {
4132 for (int i = Cand->Conversions.size()-1; i >= 0; i--) {
4133 const ImplicitConversionSequence &Conversion =
4134 Cand->Conversions[i];
4135 if ((Conversion.ConversionKind !=
4136 ImplicitConversionSequence::BadConversion) ||
4137 Conversion.ConversionFunctionSet.size() == 0)
4138 continue;
4139 Diag(Cand->Function->getLocation(),
4140 diag::err_ovl_candidate_not_viable) << (i+1);
4141 errReported = true;
4142 for (int j = Conversion.ConversionFunctionSet.size()-1;
4143 j >= 0; j--) {
4144 FunctionDecl *Func = Conversion.ConversionFunctionSet[j];
4145 Diag(Func->getLocation(), diag::err_ovl_candidate);
4146 }
4147 }
4148 }
4149 if (!errReported)
4150 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor171c45a2009-02-18 21:56:37 +00004151 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00004152 } else if (Cand->IsSurrogate) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004153 // Desugar the type of the surrogate down to a function type,
4154 // retaining as many typedefs as possible while still showing
4155 // the function type (and, therefore, its parameter types).
4156 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004157 bool isLValueReference = false;
4158 bool isRValueReference = false;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004159 bool isPointer = false;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004160 if (const LValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004161 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004162 FnType = FnTypeRef->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004163 isLValueReference = true;
4164 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004165 FnType->getAs<RValueReferenceType>()) {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004166 FnType = FnTypeRef->getPointeeType();
4167 isRValueReference = true;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004168 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004169 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004170 FnType = FnTypePtr->getPointeeType();
4171 isPointer = true;
4172 }
4173 // Desugar down to a function type.
John McCall9dd450b2009-09-21 23:43:11 +00004174 FnType = QualType(FnType->getAs<FunctionType>(), 0);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004175 // Reconstruct the pointer/reference as appropriate.
4176 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004177 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
4178 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004179
Douglas Gregorab7897a2008-11-19 22:57:39 +00004180 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004181 << FnType;
Douglas Gregor66950a32009-09-30 21:46:01 +00004182 } else if (OnlyViable) {
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004183 assert(Cand->Conversions.size() <= 2 &&
Fariborz Jahanian0fe5e032009-10-09 17:09:58 +00004184 "builtin-binary-operator-not-binary");
Fariborz Jahanian956127d2009-10-16 23:25:02 +00004185 std::string TypeStr("operator");
4186 TypeStr += Opc;
4187 TypeStr += "(";
4188 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4189 if (Cand->Conversions.size() == 1) {
4190 TypeStr += ")";
4191 Diag(OpLoc, diag::err_ovl_builtin_unary_candidate) << TypeStr;
4192 }
4193 else {
4194 TypeStr += ", ";
4195 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4196 TypeStr += ")";
4197 Diag(OpLoc, diag::err_ovl_builtin_binary_candidate) << TypeStr;
4198 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004199 }
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004200 else if (!Cand->Viable && !Reported) {
4201 // Non-viability might be due to ambiguous user-defined conversions,
4202 // needed for built-in operators. Report them as well, but only once
4203 // as we have typically many built-in candidates.
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004204 unsigned NoOperands = Cand->Conversions.size();
4205 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004206 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
4207 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion ||
4208 ICS.ConversionFunctionSet.empty())
4209 continue;
4210 if (CXXConversionDecl *Func = dyn_cast<CXXConversionDecl>(
4211 Cand->Conversions[ArgIdx].ConversionFunctionSet[0])) {
4212 QualType FromTy =
4213 QualType(
4214 static_cast<Type*>(ICS.UserDefined.Before.FromTypePtr),0);
4215 Diag(OpLoc,diag::note_ambiguous_type_conversion)
4216 << FromTy << Func->getConversionType();
4217 }
4218 for (unsigned j = 0; j < ICS.ConversionFunctionSet.size(); j++) {
4219 FunctionDecl *Func =
4220 Cand->Conversions[ArgIdx].ConversionFunctionSet[j];
4221 Diag(Func->getLocation(),diag::err_ovl_candidate);
4222 }
4223 }
4224 Reported = true;
4225 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004226 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004227 }
4228}
4229
Douglas Gregorcd695e52008-11-10 20:40:00 +00004230/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4231/// an overloaded function (C++ [over.over]), where @p From is an
4232/// expression with overloaded function type and @p ToType is the type
4233/// we're trying to resolve to. For example:
4234///
4235/// @code
4236/// int f(double);
4237/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00004238///
Douglas Gregorcd695e52008-11-10 20:40:00 +00004239/// int (*pfd)(double) = f; // selects f(double)
4240/// @endcode
4241///
4242/// This routine returns the resulting FunctionDecl if it could be
4243/// resolved, and NULL otherwise. When @p Complain is true, this
4244/// routine will emit diagnostics if there is an error.
4245FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004246Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00004247 bool Complain) {
4248 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004249 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004250 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004251 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004252 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00004253 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004254 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004255 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004256 FunctionType = MemTypePtr->getPointeeType();
4257 IsMember = true;
4258 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004259
4260 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00004261 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00004262 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004263 return 0;
4264
4265 // Find the actual overloaded function declaration.
4266 OverloadedFunctionDecl *Ovl = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004267
Douglas Gregorcd695e52008-11-10 20:40:00 +00004268 // C++ [over.over]p1:
4269 // [...] [Note: any redundant set of parentheses surrounding the
4270 // overloaded function name is ignored (5.1). ]
4271 Expr *OvlExpr = From->IgnoreParens();
4272
4273 // C++ [over.over]p1:
4274 // [...] The overloaded function name can be preceded by the &
4275 // operator.
4276 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4277 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4278 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4279 }
4280
Anders Carlssonb68b0282009-10-20 22:53:47 +00004281 bool HasExplicitTemplateArgs = false;
John McCall0ad16662009-10-29 08:12:44 +00004282 const TemplateArgumentLoc *ExplicitTemplateArgs = 0;
Anders Carlssonb68b0282009-10-20 22:53:47 +00004283 unsigned NumExplicitTemplateArgs = 0;
4284
Douglas Gregorcd695e52008-11-10 20:40:00 +00004285 // Try to dig out the overloaded function.
Douglas Gregor9b146582009-07-08 20:55:45 +00004286 FunctionTemplateDecl *FunctionTemplate = 0;
4287 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00004288 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
Douglas Gregor9b146582009-07-08 20:55:45 +00004289 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
Douglas Gregord3319842009-10-24 04:59:53 +00004290 HasExplicitTemplateArgs = DR->hasExplicitTemplateArgumentList();
4291 ExplicitTemplateArgs = DR->getTemplateArgs();
4292 NumExplicitTemplateArgs = DR->getNumTemplateArgs();
Anders Carlsson6c966c42009-10-07 22:26:29 +00004293 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(OvlExpr)) {
4294 Ovl = dyn_cast<OverloadedFunctionDecl>(ME->getMemberDecl());
4295 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(ME->getMemberDecl());
Douglas Gregord3319842009-10-24 04:59:53 +00004296 HasExplicitTemplateArgs = ME->hasExplicitTemplateArgumentList();
4297 ExplicitTemplateArgs = ME->getTemplateArgs();
4298 NumExplicitTemplateArgs = ME->getNumTemplateArgs();
Anders Carlssonb68b0282009-10-20 22:53:47 +00004299 } else if (TemplateIdRefExpr *TIRE = dyn_cast<TemplateIdRefExpr>(OvlExpr)) {
4300 TemplateName Name = TIRE->getTemplateName();
4301 Ovl = Name.getAsOverloadedFunctionDecl();
4302 FunctionTemplate =
4303 dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4304
4305 HasExplicitTemplateArgs = true;
4306 ExplicitTemplateArgs = TIRE->getTemplateArgs();
4307 NumExplicitTemplateArgs = TIRE->getNumTemplateArgs();
Douglas Gregor9b146582009-07-08 20:55:45 +00004308 }
Anders Carlssonb68b0282009-10-20 22:53:47 +00004309
Mike Stump11289f42009-09-09 15:08:12 +00004310 // If there's no overloaded function declaration or function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00004311 // we're done.
4312 if (!Ovl && !FunctionTemplate)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004313 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004314
Douglas Gregor9b146582009-07-08 20:55:45 +00004315 OverloadIterator Fun;
4316 if (Ovl)
4317 Fun = Ovl;
4318 else
4319 Fun = FunctionTemplate;
Mike Stump11289f42009-09-09 15:08:12 +00004320
Douglas Gregorcd695e52008-11-10 20:40:00 +00004321 // Look through all of the overloaded functions, searching for one
4322 // whose type matches exactly.
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004323 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004324 bool FoundNonTemplateFunction = false;
Douglas Gregor9b146582009-07-08 20:55:45 +00004325 for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00004326 // C++ [over.over]p3:
4327 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00004328 // targets of type "pointer-to-function" or "reference-to-function."
4329 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004330 // type "pointer-to-member-function."
4331 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00004332
Mike Stump11289f42009-09-09 15:08:12 +00004333 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregor9b146582009-07-08 20:55:45 +00004334 = dyn_cast<FunctionTemplateDecl>(*Fun)) {
Mike Stump11289f42009-09-09 15:08:12 +00004335 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004336 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00004337 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004338 // static when converting to member pointer.
4339 if (Method->isStatic() == IsMember)
4340 continue;
4341 } else if (IsMember)
4342 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004343
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004344 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004345 // If the name is a function template, template argument deduction is
4346 // done (14.8.2.2), and if the argument deduction succeeds, the
4347 // resulting template argument list is used to generate a single
4348 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004349 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004350 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00004351 FunctionDecl *Specialization = 0;
4352 TemplateDeductionInfo Info(Context);
4353 if (TemplateDeductionResult Result
Anders Carlssonb68b0282009-10-20 22:53:47 +00004354 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
4355 ExplicitTemplateArgs,
4356 NumExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00004357 FunctionType, Specialization, Info)) {
4358 // FIXME: make a note of the failed deduction for diagnostics.
4359 (void)Result;
4360 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004361 // FIXME: If the match isn't exact, shouldn't we just drop this as
4362 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00004363 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00004364 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004365 Matches.insert(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004366 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor9b146582009-07-08 20:55:45 +00004367 }
4368 }
Mike Stump11289f42009-09-09 15:08:12 +00004369
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004370 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
4371 // Skip non-static functions when converting to pointer, and static
4372 // when converting to member pointer.
4373 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004374 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00004375
4376 // If we have explicit template arguments, skip non-templates.
4377 if (HasExplicitTemplateArgs)
4378 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004379 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004380 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00004381
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004382 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004383 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004384 Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004385 FoundNonTemplateFunction = true;
4386 }
Mike Stump11289f42009-09-09 15:08:12 +00004387 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004388 }
4389
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004390 // If there were 0 or 1 matches, we're done.
4391 if (Matches.empty())
4392 return 0;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004393 else if (Matches.size() == 1) {
4394 FunctionDecl *Result = *Matches.begin();
4395 MarkDeclarationReferenced(From->getLocStart(), Result);
4396 return Result;
4397 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004398
4399 // C++ [over.over]p4:
4400 // If more than one function is selected, [...]
Douglas Gregor05155d82009-08-21 23:19:43 +00004401 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregorfae1d712009-09-26 03:56:17 +00004402 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004403 // [...] and any given function template specialization F1 is
4404 // eliminated if the set contains a second function template
4405 // specialization whose function template is more specialized
4406 // than the function template of F1 according to the partial
4407 // ordering rules of 14.5.5.2.
4408
4409 // The algorithm specified above is quadratic. We instead use a
4410 // two-pass algorithm (similar to the one used to identify the
4411 // best viable function in an overload set) that identifies the
4412 // best function template (if it exists).
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004413 llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
Douglas Gregorfae1d712009-09-26 03:56:17 +00004414 Matches.end());
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004415 FunctionDecl *Result =
4416 getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4417 TPOC_Other, From->getLocStart(),
4418 PDiag(),
4419 PDiag(diag::err_addr_ovl_ambiguous)
4420 << TemplateMatches[0]->getDeclName(),
4421 PDiag(diag::err_ovl_template_candidate));
4422 MarkDeclarationReferenced(From->getLocStart(), Result);
4423 return Result;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004424 }
Mike Stump11289f42009-09-09 15:08:12 +00004425
Douglas Gregorfae1d712009-09-26 03:56:17 +00004426 // [...] any function template specializations in the set are
4427 // eliminated if the set also contains a non-template function, [...]
4428 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4429 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4430 if ((*M)->getPrimaryTemplate() == 0)
4431 RemainingMatches.push_back(*M);
4432
Mike Stump11289f42009-09-09 15:08:12 +00004433 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004434 // selected function.
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004435 if (RemainingMatches.size() == 1) {
4436 FunctionDecl *Result = RemainingMatches.front();
4437 MarkDeclarationReferenced(From->getLocStart(), Result);
4438 return Result;
4439 }
Mike Stump11289f42009-09-09 15:08:12 +00004440
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004441 // FIXME: We should probably return the same thing that BestViableFunction
4442 // returns (even if we issue the diagnostics here).
4443 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4444 << RemainingMatches[0]->getDeclName();
4445 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4446 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregorcd695e52008-11-10 20:40:00 +00004447 return 0;
4448}
4449
Douglas Gregorcabea402009-09-22 15:41:20 +00004450/// \brief Add a single candidate to the overload set.
4451static void AddOverloadedCallCandidate(Sema &S,
4452 AnyFunctionDecl Callee,
4453 bool &ArgumentDependentLookup,
4454 bool HasExplicitTemplateArgs,
John McCall0ad16662009-10-29 08:12:44 +00004455 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004456 unsigned NumExplicitTemplateArgs,
4457 Expr **Args, unsigned NumArgs,
4458 OverloadCandidateSet &CandidateSet,
4459 bool PartialOverloading) {
4460 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
4461 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
4462 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4463 PartialOverloading);
4464
4465 if (Func->getDeclContext()->isRecord() ||
4466 Func->getDeclContext()->isFunctionOrMethod())
4467 ArgumentDependentLookup = false;
4468 return;
4469 }
4470
4471 FunctionTemplateDecl *FuncTemplate = cast<FunctionTemplateDecl>(Callee);
4472 S.AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4473 ExplicitTemplateArgs,
4474 NumExplicitTemplateArgs,
4475 Args, NumArgs, CandidateSet);
4476
4477 if (FuncTemplate->getDeclContext()->isRecord())
4478 ArgumentDependentLookup = false;
4479}
4480
4481/// \brief Add the overload candidates named by callee and/or found by argument
4482/// dependent lookup to the given overload set.
4483void Sema::AddOverloadedCallCandidates(NamedDecl *Callee,
4484 DeclarationName &UnqualifiedName,
4485 bool &ArgumentDependentLookup,
4486 bool HasExplicitTemplateArgs,
John McCall0ad16662009-10-29 08:12:44 +00004487 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004488 unsigned NumExplicitTemplateArgs,
4489 Expr **Args, unsigned NumArgs,
4490 OverloadCandidateSet &CandidateSet,
4491 bool PartialOverloading) {
4492 // Add the functions denoted by Callee to the set of candidate
4493 // functions. While we're doing so, track whether argument-dependent
4494 // lookup still applies, per:
4495 //
4496 // C++0x [basic.lookup.argdep]p3:
4497 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4498 // and let Y be the lookup set produced by argument dependent
4499 // lookup (defined as follows). If X contains
4500 //
4501 // -- a declaration of a class member, or
4502 //
4503 // -- a block-scope function declaration that is not a
4504 // using-declaration (FIXME: check for using declaration), or
4505 //
4506 // -- a declaration that is neither a function or a function
4507 // template
4508 //
4509 // then Y is empty.
4510 if (!Callee) {
4511 // Nothing to do.
4512 } else if (OverloadedFunctionDecl *Ovl
4513 = dyn_cast<OverloadedFunctionDecl>(Callee)) {
4514 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4515 FuncEnd = Ovl->function_end();
4516 Func != FuncEnd; ++Func)
4517 AddOverloadedCallCandidate(*this, *Func, ArgumentDependentLookup,
4518 HasExplicitTemplateArgs,
4519 ExplicitTemplateArgs, NumExplicitTemplateArgs,
4520 Args, NumArgs, CandidateSet,
4521 PartialOverloading);
4522 } else if (isa<FunctionDecl>(Callee) || isa<FunctionTemplateDecl>(Callee))
4523 AddOverloadedCallCandidate(*this,
4524 AnyFunctionDecl::getFromNamedDecl(Callee),
4525 ArgumentDependentLookup,
4526 HasExplicitTemplateArgs,
4527 ExplicitTemplateArgs, NumExplicitTemplateArgs,
4528 Args, NumArgs, CandidateSet,
4529 PartialOverloading);
4530 // FIXME: assert isa<FunctionDecl> || isa<FunctionTemplateDecl> rather than
4531 // checking dynamically.
4532
4533 if (Callee)
4534 UnqualifiedName = Callee->getDeclName();
4535
4536 if (ArgumentDependentLookup)
4537 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
4538 HasExplicitTemplateArgs,
4539 ExplicitTemplateArgs,
4540 NumExplicitTemplateArgs,
4541 CandidateSet,
4542 PartialOverloading);
4543}
4544
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004545/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00004546/// (which eventually refers to the declaration Func) and the call
4547/// arguments Args/NumArgs, attempt to resolve the function call down
4548/// to a specific function. If overload resolution succeeds, returns
4549/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00004550/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004551/// arguments and Fn, and returns NULL.
Douglas Gregore254f902009-02-04 00:32:51 +00004552FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004553 DeclarationName UnqualifiedName,
Douglas Gregor89026b52009-06-30 23:57:56 +00004554 bool HasExplicitTemplateArgs,
John McCall0ad16662009-10-29 08:12:44 +00004555 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004556 unsigned NumExplicitTemplateArgs,
Douglas Gregora60a6912008-11-26 06:01:48 +00004557 SourceLocation LParenLoc,
4558 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004559 SourceLocation *CommaLocs,
Douglas Gregore254f902009-02-04 00:32:51 +00004560 SourceLocation RParenLoc,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004561 bool &ArgumentDependentLookup) {
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004562 OverloadCandidateSet CandidateSet;
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004563
4564 // Add the functions denoted by Callee to the set of candidate
Douglas Gregorcabea402009-09-22 15:41:20 +00004565 // functions.
4566 AddOverloadedCallCandidates(Callee, UnqualifiedName, ArgumentDependentLookup,
4567 HasExplicitTemplateArgs, ExplicitTemplateArgs,
4568 NumExplicitTemplateArgs, Args, NumArgs,
4569 CandidateSet);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004570 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004571 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregora60a6912008-11-26 06:01:48 +00004572 case OR_Success:
4573 return Best->Function;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004574
4575 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00004576 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004577 diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00004578 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004579 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4580 break;
4581
4582 case OR_Ambiguous:
4583 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004584 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004585 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4586 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004587
4588 case OR_Deleted:
4589 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4590 << Best->Function->isDeleted()
4591 << UnqualifiedName
4592 << Fn->getSourceRange();
4593 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4594 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004595 }
4596
4597 // Overload resolution failed. Destroy all of the subexpressions and
4598 // return NULL.
4599 Fn->Destroy(Context);
4600 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4601 Args[Arg]->Destroy(Context);
4602 return 0;
4603}
4604
Douglas Gregor084d8552009-03-13 23:49:33 +00004605/// \brief Create a unary operation that may resolve to an overloaded
4606/// operator.
4607///
4608/// \param OpLoc The location of the operator itself (e.g., '*').
4609///
4610/// \param OpcIn The UnaryOperator::Opcode that describes this
4611/// operator.
4612///
4613/// \param Functions The set of non-member functions that will be
4614/// considered by overload resolution. The caller needs to build this
4615/// set based on the context using, e.g.,
4616/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4617/// set should not contain any member functions; those will be added
4618/// by CreateOverloadedUnaryOp().
4619///
4620/// \param input The input argument.
4621Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4622 unsigned OpcIn,
4623 FunctionSet &Functions,
Mike Stump11289f42009-09-09 15:08:12 +00004624 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004625 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4626 Expr *Input = (Expr *)input.get();
4627
4628 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4629 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4630 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4631
4632 Expr *Args[2] = { Input, 0 };
4633 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004634
Douglas Gregor084d8552009-03-13 23:49:33 +00004635 // For post-increment and post-decrement, add the implicit '0' as
4636 // the second argument, so that we know this is a post-increment or
4637 // post-decrement.
4638 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4639 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00004640 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00004641 SourceLocation());
4642 NumArgs = 2;
4643 }
4644
4645 if (Input->isTypeDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00004646 OverloadedFunctionDecl *Overloads
Douglas Gregor084d8552009-03-13 23:49:33 +00004647 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump11289f42009-09-09 15:08:12 +00004648 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor084d8552009-03-13 23:49:33 +00004649 FuncEnd = Functions.end();
4650 Func != FuncEnd; ++Func)
4651 Overloads->addOverload(*Func);
4652
4653 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4654 OpLoc, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00004655
Douglas Gregor084d8552009-03-13 23:49:33 +00004656 input.release();
4657 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4658 &Args[0], NumArgs,
4659 Context.DependentTy,
4660 OpLoc));
4661 }
4662
4663 // Build an empty overload set.
4664 OverloadCandidateSet CandidateSet;
4665
4666 // Add the candidates from the given function set.
4667 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4668
4669 // Add operator candidates that are member functions.
4670 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4671
4672 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004673 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00004674
4675 // Perform overload resolution.
4676 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004677 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004678 case OR_Success: {
4679 // We found a built-in operator or an overloaded operator.
4680 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00004681
Douglas Gregor084d8552009-03-13 23:49:33 +00004682 if (FnDecl) {
4683 // We matched an overloaded operator. Build a call to that
4684 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00004685
Douglas Gregor084d8552009-03-13 23:49:33 +00004686 // Convert the arguments.
4687 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4688 if (PerformObjectArgumentInitialization(Input, Method))
4689 return ExprError();
4690 } else {
4691 // Convert the arguments.
4692 if (PerformCopyInitialization(Input,
4693 FnDecl->getParamDecl(0)->getType(),
4694 "passing"))
4695 return ExprError();
4696 }
4697
4698 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00004699 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00004700
Douglas Gregor084d8552009-03-13 23:49:33 +00004701 // Build the actual expression node.
4702 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4703 SourceLocation());
4704 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004705
Douglas Gregor084d8552009-03-13 23:49:33 +00004706 input.release();
Mike Stump11289f42009-09-09 15:08:12 +00004707
Anders Carlssonf64a3da2009-10-13 21:19:37 +00004708 ExprOwningPtr<CallExpr> TheCall(this,
4709 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4710 &Input, 1, ResultTy, OpLoc));
4711
4712 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4713 FnDecl))
4714 return ExprError();
4715
4716 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00004717 } else {
4718 // We matched a built-in operator. Convert the arguments, then
4719 // break out so that we will build the appropriate built-in
4720 // operator node.
4721 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4722 Best->Conversions[0], "passing"))
4723 return ExprError();
4724
4725 break;
4726 }
4727 }
4728
4729 case OR_No_Viable_Function:
4730 // No viable function; fall through to handling this as a
4731 // built-in operator, which will produce an error message for us.
4732 break;
4733
4734 case OR_Ambiguous:
4735 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4736 << UnaryOperator::getOpcodeStr(Opc)
4737 << Input->getSourceRange();
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004738 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
4739 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00004740 return ExprError();
4741
4742 case OR_Deleted:
4743 Diag(OpLoc, diag::err_ovl_deleted_oper)
4744 << Best->Function->isDeleted()
4745 << UnaryOperator::getOpcodeStr(Opc)
4746 << Input->getSourceRange();
4747 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4748 return ExprError();
4749 }
4750
4751 // Either we found no viable overloaded operator or we matched a
4752 // built-in operator. In either case, fall through to trying to
4753 // build a built-in operation.
4754 input.release();
4755 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4756}
4757
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004758/// \brief Create a binary operation that may resolve to an overloaded
4759/// operator.
4760///
4761/// \param OpLoc The location of the operator itself (e.g., '+').
4762///
4763/// \param OpcIn The BinaryOperator::Opcode that describes this
4764/// operator.
4765///
4766/// \param Functions The set of non-member functions that will be
4767/// considered by overload resolution. The caller needs to build this
4768/// set based on the context using, e.g.,
4769/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4770/// set should not contain any member functions; those will be added
4771/// by CreateOverloadedBinOp().
4772///
4773/// \param LHS Left-hand argument.
4774/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00004775Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004776Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004777 unsigned OpcIn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004778 FunctionSet &Functions,
4779 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004780 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00004781 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004782
4783 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4784 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4785 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4786
4787 // If either side is type-dependent, create an appropriate dependent
4788 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00004789 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00004790 if (Functions.empty()) {
4791 // If there are no functions to store, just build a dependent
4792 // BinaryOperator or CompoundAssignment.
4793 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
4794 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
4795 Context.DependentTy, OpLoc));
4796
4797 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
4798 Context.DependentTy,
4799 Context.DependentTy,
4800 Context.DependentTy,
4801 OpLoc));
4802 }
4803
Mike Stump11289f42009-09-09 15:08:12 +00004804 OverloadedFunctionDecl *Overloads
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004805 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump11289f42009-09-09 15:08:12 +00004806 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004807 FuncEnd = Functions.end();
4808 Func != FuncEnd; ++Func)
4809 Overloads->addOverload(*Func);
4810
4811 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4812 OpLoc, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00004813
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004814 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00004815 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004816 Context.DependentTy,
4817 OpLoc));
4818 }
4819
4820 // If this is the .* operator, which is not overloadable, just
4821 // create a built-in binary operator.
4822 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00004823 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004824
4825 // If this is one of the assignment operators, we only perform
4826 // overload resolution if the left-hand side is a class or
4827 // enumeration type (C++ [expr.ass]p3).
4828 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
Douglas Gregore9899d92009-08-26 17:08:25 +00004829 !Args[0]->getType()->isOverloadableType())
4830 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004831
Douglas Gregor084d8552009-03-13 23:49:33 +00004832 // Build an empty overload set.
4833 OverloadCandidateSet CandidateSet;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004834
4835 // Add the candidates from the given function set.
4836 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4837
4838 // Add operator candidates that are member functions.
4839 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4840
4841 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004842 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004843
4844 // Perform overload resolution.
4845 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004846 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004847 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004848 // We found a built-in operator or an overloaded operator.
4849 FunctionDecl *FnDecl = Best->Function;
4850
4851 if (FnDecl) {
4852 // We matched an overloaded operator. Build a call to that
4853 // operator.
4854
4855 // Convert the arguments.
4856 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregore9899d92009-08-26 17:08:25 +00004857 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4858 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004859 "passing"))
4860 return ExprError();
4861 } else {
4862 // Convert the arguments.
Douglas Gregore9899d92009-08-26 17:08:25 +00004863 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004864 "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004865 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004866 "passing"))
4867 return ExprError();
4868 }
4869
4870 // Determine the result type
4871 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00004872 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004873 ResultTy = ResultTy.getNonReferenceType();
4874
4875 // Build the actual expression node.
4876 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00004877 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004878 UsualUnaryConversions(FnExpr);
4879
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00004880 ExprOwningPtr<CXXOperatorCallExpr>
4881 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4882 Args, 2, ResultTy,
4883 OpLoc));
4884
4885 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4886 FnDecl))
4887 return ExprError();
4888
4889 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004890 } else {
4891 // We matched a built-in operator. Convert the arguments, then
4892 // break out so that we will build the appropriate built-in
4893 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00004894 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004895 Best->Conversions[0], "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004896 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004897 Best->Conversions[1], "passing"))
4898 return ExprError();
4899
4900 break;
4901 }
4902 }
4903
Douglas Gregor66950a32009-09-30 21:46:01 +00004904 case OR_No_Viable_Function: {
4905 // C++ [over.match.oper]p9:
4906 // If the operator is the operator , [...] and there are no
4907 // viable functions, then the operator is assumed to be the
4908 // built-in operator and interpreted according to clause 5.
4909 if (Opc == BinaryOperator::Comma)
4910 break;
4911
Sebastian Redl027de2a2009-05-21 11:50:50 +00004912 // For class as left operand for assignment or compound assigment operator
4913 // do not fall through to handling in built-in, but report that no overloaded
4914 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00004915 OwningExprResult Result = ExprError();
4916 if (Args[0]->getType()->isRecordType() &&
4917 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00004918 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4919 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004920 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00004921 } else {
4922 // No viable function; try to create a built-in operation, which will
4923 // produce an error. Then, show the non-viable candidates.
4924 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00004925 }
Douglas Gregor66950a32009-09-30 21:46:01 +00004926 assert(Result.isInvalid() &&
4927 "C++ binary operator overloading is missing candidates!");
4928 if (Result.isInvalid())
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004929 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
4930 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00004931 return move(Result);
4932 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004933
4934 case OR_Ambiguous:
4935 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4936 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004937 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004938 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
4939 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004940 return ExprError();
4941
4942 case OR_Deleted:
4943 Diag(OpLoc, diag::err_ovl_deleted_oper)
4944 << Best->Function->isDeleted()
4945 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004946 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004947 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4948 return ExprError();
4949 }
4950
Douglas Gregor66950a32009-09-30 21:46:01 +00004951 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00004952 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004953}
4954
Sebastian Redladba46e2009-10-29 20:17:01 +00004955Action::OwningExprResult
4956Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
4957 SourceLocation RLoc,
4958 ExprArg Base, ExprArg Idx) {
4959 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
4960 static_cast<Expr*>(Idx.get()) };
4961 DeclarationName OpName =
4962 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
4963
4964 // If either side is type-dependent, create an appropriate dependent
4965 // expression.
4966 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
4967
4968 OverloadedFunctionDecl *Overloads
4969 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4970
4971 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4972 LLoc, false, false);
4973
4974 Base.release();
4975 Idx.release();
4976 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
4977 Args, 2,
4978 Context.DependentTy,
4979 RLoc));
4980 }
4981
4982 // Build an empty overload set.
4983 OverloadCandidateSet CandidateSet;
4984
4985 // Subscript can only be overloaded as a member function.
4986
4987 // Add operator candidates that are member functions.
4988 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
4989
4990 // Add builtin operator candidates.
4991 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
4992
4993 // Perform overload resolution.
4994 OverloadCandidateSet::iterator Best;
4995 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
4996 case OR_Success: {
4997 // We found a built-in operator or an overloaded operator.
4998 FunctionDecl *FnDecl = Best->Function;
4999
5000 if (FnDecl) {
5001 // We matched an overloaded operator. Build a call to that
5002 // operator.
5003
5004 // Convert the arguments.
5005 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5006 if (PerformObjectArgumentInitialization(Args[0], Method) ||
5007 PerformCopyInitialization(Args[1],
5008 FnDecl->getParamDecl(0)->getType(),
5009 "passing"))
5010 return ExprError();
5011
5012 // Determine the result type
5013 QualType ResultTy
5014 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5015 ResultTy = ResultTy.getNonReferenceType();
5016
5017 // Build the actual expression node.
5018 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5019 LLoc);
5020 UsualUnaryConversions(FnExpr);
5021
5022 Base.release();
5023 Idx.release();
5024 ExprOwningPtr<CXXOperatorCallExpr>
5025 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5026 FnExpr, Args, 2,
5027 ResultTy, RLoc));
5028
5029 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5030 FnDecl))
5031 return ExprError();
5032
5033 return MaybeBindToTemporary(TheCall.release());
5034 } else {
5035 // We matched a built-in operator. Convert the arguments, then
5036 // break out so that we will build the appropriate built-in
5037 // operator node.
5038 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
5039 Best->Conversions[0], "passing") ||
5040 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
5041 Best->Conversions[1], "passing"))
5042 return ExprError();
5043
5044 break;
5045 }
5046 }
5047
5048 case OR_No_Viable_Function: {
5049 // No viable function; try to create a built-in operation, which will
5050 // produce an error. Then, show the non-viable candidates.
5051 OwningExprResult Result =
5052 CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
5053 assert(Result.isInvalid() &&
5054 "C++ subscript operator overloading is missing candidates!");
5055 if (Result.isInvalid())
5056 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
5057 "[]", LLoc);
5058 return move(Result);
5059 }
5060
5061 case OR_Ambiguous:
5062 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5063 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5064 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5065 "[]", LLoc);
5066 return ExprError();
5067
5068 case OR_Deleted:
5069 Diag(LLoc, diag::err_ovl_deleted_oper)
5070 << Best->Function->isDeleted() << "[]"
5071 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5072 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5073 return ExprError();
5074 }
5075
5076 // We matched a built-in operator; build it.
5077 Base.release();
5078 Idx.release();
5079 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5080 Owned(Args[1]), RLoc);
5081}
5082
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005083/// BuildCallToMemberFunction - Build a call to a member
5084/// function. MemExpr is the expression that refers to the member
5085/// function (and includes the object parameter), Args/NumArgs are the
5086/// arguments to the function call (not including the object
5087/// parameter). The caller needs to validate that the member
5088/// expression refers to a member function or an overloaded member
5089/// function.
5090Sema::ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00005091Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5092 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005093 unsigned NumArgs, SourceLocation *CommaLocs,
5094 SourceLocation RParenLoc) {
5095 // Dig out the member expression. This holds both the object
5096 // argument and the member function we're referring to.
5097 MemberExpr *MemExpr = 0;
5098 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
5099 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
5100 else
5101 MemExpr = dyn_cast<MemberExpr>(MemExprE);
5102 assert(MemExpr && "Building member call without member expression");
5103
5104 // Extract the object argument.
5105 Expr *ObjectArg = MemExpr->getBase();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005106
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005107 CXXMethodDecl *Method = 0;
Douglas Gregor97628d62009-08-21 00:16:32 +00005108 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
5109 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005110 // Add overload candidates
5111 OverloadCandidateSet CandidateSet;
Douglas Gregor97628d62009-08-21 00:16:32 +00005112 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00005113
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005114 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
5115 Func != FuncEnd; ++Func) {
Douglas Gregord3319842009-10-24 04:59:53 +00005116 if ((Method = dyn_cast<CXXMethodDecl>(*Func))) {
5117 // If explicit template arguments were provided, we can't call a
5118 // non-template member function.
5119 if (MemExpr->hasExplicitTemplateArgumentList())
5120 continue;
5121
Mike Stump11289f42009-09-09 15:08:12 +00005122 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005123 /*SuppressUserConversions=*/false);
Douglas Gregord3319842009-10-24 04:59:53 +00005124 } else
Douglas Gregor84f14dd2009-09-01 00:37:14 +00005125 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
5126 MemExpr->hasExplicitTemplateArgumentList(),
5127 MemExpr->getTemplateArgs(),
5128 MemExpr->getNumTemplateArgs(),
5129 ObjectArg, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005130 CandidateSet,
5131 /*SuppressUsedConversions=*/false);
5132 }
Mike Stump11289f42009-09-09 15:08:12 +00005133
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005134 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005135 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005136 case OR_Success:
5137 Method = cast<CXXMethodDecl>(Best->Function);
5138 break;
5139
5140 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00005141 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005142 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005143 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005144 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5145 // FIXME: Leaking incoming expressions!
5146 return true;
5147
5148 case OR_Ambiguous:
Mike Stump11289f42009-09-09 15:08:12 +00005149 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005150 diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005151 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005152 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5153 // FIXME: Leaking incoming expressions!
5154 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005155
5156 case OR_Deleted:
Mike Stump11289f42009-09-09 15:08:12 +00005157 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +00005158 diag::err_ovl_deleted_member_call)
5159 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00005160 << DeclName << MemExprE->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005161 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5162 // FIXME: Leaking incoming expressions!
5163 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005164 }
5165
5166 FixOverloadedFunctionReference(MemExpr, Method);
5167 } else {
5168 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
5169 }
5170
5171 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00005172 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005173 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
Mike Stump11289f42009-09-09 15:08:12 +00005174 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005175 Method->getResultType().getNonReferenceType(),
5176 RParenLoc));
5177
Anders Carlssonc4859ba2009-10-10 00:06:20 +00005178 // Check for a valid return type.
5179 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
5180 TheCall.get(), Method))
5181 return true;
5182
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005183 // Convert the object argument (for a non-static member function call).
Mike Stump11289f42009-09-09 15:08:12 +00005184 if (!Method->isStatic() &&
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005185 PerformObjectArgumentInitialization(ObjectArg, Method))
5186 return true;
5187 MemExpr->setBase(ObjectArg);
5188
5189 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005190 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00005191 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005192 RParenLoc))
5193 return true;
5194
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005195 if (CheckFunctionCall(Method, TheCall.get()))
5196 return true;
Anders Carlsson8c84c202009-08-16 03:42:12 +00005197
5198 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005199}
5200
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005201/// BuildCallToObjectOfClassType - Build a call to an object of class
5202/// type (C++ [over.call.object]), which can end up invoking an
5203/// overloaded function call operator (@c operator()) or performing a
5204/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00005205Sema::ExprResult
5206Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00005207 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005208 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00005209 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005210 SourceLocation RParenLoc) {
5211 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005212 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00005213
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005214 // C++ [over.call.object]p1:
5215 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00005216 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005217 // candidate functions includes at least the function call
5218 // operators of T. The function call operators of T are obtained by
5219 // ordinary lookup of the name operator() in the context of
5220 // (E).operator().
5221 OverloadCandidateSet CandidateSet;
Douglas Gregor91f84212008-12-11 16:49:14 +00005222 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor55297ac2008-12-23 00:26:44 +00005223 DeclContext::lookup_const_iterator Oper, OperEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005224 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregor55297ac2008-12-23 00:26:44 +00005225 Oper != OperEnd; ++Oper)
Mike Stump11289f42009-09-09 15:08:12 +00005226 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
Douglas Gregor55297ac2008-12-23 00:26:44 +00005227 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005228
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005229 if (RequireCompleteType(LParenLoc, Object->getType(),
5230 PartialDiagnostic(diag::err_incomplete_object_call)
5231 << Object->getSourceRange()))
5232 return true;
5233
Douglas Gregorab7897a2008-11-19 22:57:39 +00005234 // C++ [over.call.object]p2:
5235 // In addition, for each conversion function declared in T of the
5236 // form
5237 //
5238 // operator conversion-type-id () cv-qualifier;
5239 //
5240 // where cv-qualifier is the same cv-qualification as, or a
5241 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00005242 // denotes the type "pointer to function of (P1,...,Pn) returning
5243 // R", or the type "reference to pointer to function of
5244 // (P1,...,Pn) returning R", or the type "reference to function
5245 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00005246 // is also considered as a candidate function. Similarly,
5247 // surrogate call functions are added to the set of candidate
5248 // functions for each conversion function declared in an
5249 // accessible base class provided the function is not hidden
5250 // within T by another intervening declaration.
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005251 // FIXME: Look in base classes for more conversion operators!
5252 OverloadedFunctionDecl *Conversions
5253 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
5254 for (OverloadedFunctionDecl::function_iterator
5255 Func = Conversions->function_begin(),
5256 FuncEnd = Conversions->function_end();
5257 Func != FuncEnd; ++Func) {
5258 CXXConversionDecl *Conv;
5259 FunctionTemplateDecl *ConvTemplate;
5260 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
Mike Stump11289f42009-09-09 15:08:12 +00005261
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005262 // Skip over templated conversion functions; they aren't
5263 // surrogates.
5264 if (ConvTemplate)
5265 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005266
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005267 // Strip the reference type (if any) and then the pointer type (if
5268 // any) to get down to what might be a function type.
5269 QualType ConvType = Conv->getConversionType().getNonReferenceType();
5270 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5271 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005272
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005273 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
5274 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00005275 }
Mike Stump11289f42009-09-09 15:08:12 +00005276
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005277 // Perform overload resolution.
5278 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005279 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005280 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00005281 // Overload resolution succeeded; we'll build the appropriate call
5282 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005283 break;
5284
5285 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00005286 Diag(Object->getSourceRange().getBegin(),
Sebastian Redl15b02d22008-11-22 13:44:36 +00005287 diag::err_ovl_no_viable_object_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00005288 << Object->getType() << Object->getSourceRange();
Sebastian Redl15b02d22008-11-22 13:44:36 +00005289 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005290 break;
5291
5292 case OR_Ambiguous:
5293 Diag(Object->getSourceRange().getBegin(),
5294 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005295 << Object->getType() << Object->getSourceRange();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005296 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5297 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005298
5299 case OR_Deleted:
5300 Diag(Object->getSourceRange().getBegin(),
5301 diag::err_ovl_deleted_object_call)
5302 << Best->Function->isDeleted()
5303 << Object->getType() << Object->getSourceRange();
5304 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5305 break;
Mike Stump11289f42009-09-09 15:08:12 +00005306 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005307
Douglas Gregorab7897a2008-11-19 22:57:39 +00005308 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005309 // We had an error; delete all of the subexpressions and return
5310 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00005311 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005312 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00005313 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005314 return true;
5315 }
5316
Douglas Gregorab7897a2008-11-19 22:57:39 +00005317 if (Best->Function == 0) {
5318 // Since there is no function declaration, this is one of the
5319 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00005320 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00005321 = cast<CXXConversionDecl>(
5322 Best->Conversions[0].UserDefined.ConversionFunction);
5323
5324 // We selected one of the surrogate functions that converts the
5325 // object parameter to a function pointer. Perform the conversion
5326 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005327
5328 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005329 // and then call it.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005330 CXXMemberCallExpr *CE =
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005331 BuildCXXMemberCallExpr(Object, Conv);
5332
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005333 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005334 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
5335 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005336 }
5337
5338 // We found an overloaded operator(). Build a CXXOperatorCallExpr
5339 // that calls this method, using Object for the implicit object
5340 // parameter and passing along the remaining arguments.
5341 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00005342 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005343
5344 unsigned NumArgsInProto = Proto->getNumArgs();
5345 unsigned NumArgsToCheck = NumArgs;
5346
5347 // Build the full argument list for the method call (the
5348 // implicit object parameter is placed at the beginning of the
5349 // list).
5350 Expr **MethodArgs;
5351 if (NumArgs < NumArgsInProto) {
5352 NumArgsToCheck = NumArgsInProto;
5353 MethodArgs = new Expr*[NumArgsInProto + 1];
5354 } else {
5355 MethodArgs = new Expr*[NumArgs + 1];
5356 }
5357 MethodArgs[0] = Object;
5358 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5359 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00005360
5361 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00005362 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005363 UsualUnaryConversions(NewFn);
5364
5365 // Once we've built TheCall, all of the expressions are properly
5366 // owned.
5367 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005368 ExprOwningPtr<CXXOperatorCallExpr>
5369 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005370 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00005371 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005372 delete [] MethodArgs;
5373
Anders Carlsson3d5829c2009-10-13 21:49:31 +00005374 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
5375 Method))
5376 return true;
5377
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005378 // We may have default arguments. If so, we need to allocate more
5379 // slots in the call for them.
5380 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00005381 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005382 else if (NumArgs > NumArgsInProto)
5383 NumArgsToCheck = NumArgsInProto;
5384
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005385 bool IsError = false;
5386
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005387 // Initialize the implicit object parameter.
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005388 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005389 TheCall->setArg(0, Object);
5390
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005391
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005392 // Check the argument types.
5393 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005394 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005395 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005396 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00005397
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005398 // Pass the argument.
5399 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005400 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005401 } else {
Anders Carlssone8271232009-08-14 18:30:22 +00005402 Arg = CXXDefaultArgExpr::Create(Context, Method->getParamDecl(i));
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005403 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005404
5405 TheCall->setArg(i + 1, Arg);
5406 }
5407
5408 // If this is a variadic call, handle args passed through "...".
5409 if (Proto->isVariadic()) {
5410 // Promote the arguments (C99 6.5.2.2p7).
5411 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
5412 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005413 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005414 TheCall->setArg(i + 1, Arg);
5415 }
5416 }
5417
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005418 if (IsError) return true;
5419
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005420 if (CheckFunctionCall(Method, TheCall.get()))
5421 return true;
5422
Anders Carlsson1c83deb2009-08-16 03:53:54 +00005423 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005424}
5425
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005426/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00005427/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005428/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00005429Sema::OwningExprResult
5430Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
5431 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005432 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00005433
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005434 // C++ [over.ref]p1:
5435 //
5436 // [...] An expression x->m is interpreted as (x.operator->())->m
5437 // for a class object x of type T if T::operator->() exists and if
5438 // the operator is selected as the best match function by the
5439 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005440 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
5441 OverloadCandidateSet CandidateSet;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005442 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00005443
John McCall9f3059a2009-10-09 21:13:30 +00005444 LookupResult R;
5445 LookupQualifiedName(R, BaseRecord->getDecl(), OpName, LookupOrdinaryName);
Anders Carlsson78b54932009-09-10 23:18:36 +00005446
5447 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
5448 Oper != OperEnd; ++Oper)
Douglas Gregor55297ac2008-12-23 00:26:44 +00005449 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005450 /*SuppressUserConversions=*/false);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005451
5452 // Perform overload resolution.
5453 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005454 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005455 case OR_Success:
5456 // Overload resolution succeeded; we'll build the call below.
5457 break;
5458
5459 case OR_No_Viable_Function:
5460 if (CandidateSet.empty())
5461 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00005462 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005463 else
5464 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00005465 << "operator->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005466 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregord8061562009-08-06 03:17:00 +00005467 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005468
5469 case OR_Ambiguous:
5470 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00005471 << "->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005472 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005473 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005474
5475 case OR_Deleted:
5476 Diag(OpLoc, diag::err_ovl_deleted_oper)
5477 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00005478 << "->" << Base->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005479 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005480 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005481 }
5482
5483 // Convert the object parameter.
5484 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9ecea262008-11-21 03:04:22 +00005485 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00005486 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00005487
5488 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00005489 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005490
5491 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00005492 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
5493 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005494 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00005495
5496 QualType ResultTy = Method->getResultType().getNonReferenceType();
5497 ExprOwningPtr<CXXOperatorCallExpr>
5498 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
5499 &Base, 1, ResultTy, OpLoc));
5500
5501 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
5502 Method))
5503 return ExprError();
5504 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005505}
5506
Douglas Gregorcd695e52008-11-10 20:40:00 +00005507/// FixOverloadedFunctionReference - E is an expression that refers to
5508/// a C++ overloaded function (possibly with some parentheses and
5509/// perhaps a '&' around it). We have resolved the overloaded function
5510/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005511/// refer (possibly indirectly) to Fn. Returns the new expr.
5512Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005513 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005514 Expr *NewExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00005515 PE->setSubExpr(NewExpr);
5516 PE->setType(NewExpr->getType());
5517 } else if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5518 Expr *NewExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
5519 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
5520 NewExpr->getType()) &&
5521 "Implicit cast type cannot be determined from overload");
5522 ICE->setSubExpr(NewExpr);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005523 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00005524 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00005525 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005526 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5527 if (Method->isStatic()) {
5528 // Do nothing: static member functions aren't any different
5529 // from non-member functions.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005530 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr())) {
5531 if (DRE->getQualifier()) {
5532 // We have taken the address of a pointer to member
5533 // function. Perform the computation here so that we get the
5534 // appropriate pointer to member type.
5535 DRE->setDecl(Fn);
5536 DRE->setType(Fn->getType());
5537 QualType ClassType
5538 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
5539 E->setType(Context.getMemberPointerType(Fn->getType(),
5540 ClassType.getTypePtr()));
5541 return E;
5542 }
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005543 }
Douglas Gregor6a573fe2009-10-22 18:02:20 +00005544 // FIXME: TemplateIdRefExpr referring to a member function template
5545 // specialization!
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005546 }
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005547 Expr *NewExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5548 UnOp->setSubExpr(NewExpr);
5549 UnOp->setType(Context.getPointerType(NewExpr->getType()));
5550
5551 return UnOp;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005552 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
Douglas Gregor9b146582009-07-08 20:55:45 +00005553 assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
Douglas Gregor091f0422009-10-23 22:18:25 +00005554 isa<FunctionTemplateDecl>(DR->getDecl()) ||
5555 isa<FunctionDecl>(DR->getDecl())) &&
5556 "Expected function or function template");
Douglas Gregorcd695e52008-11-10 20:40:00 +00005557 DR->setDecl(Fn);
5558 E->setType(Fn->getType());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005559 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
5560 MemExpr->setMemberDecl(Fn);
5561 E->setType(Fn->getType());
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005562 } else if (TemplateIdRefExpr *TID = dyn_cast<TemplateIdRefExpr>(E)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005563 E = DeclRefExpr::Create(Context,
5564 TID->getQualifier(), TID->getQualifierRange(),
5565 Fn, TID->getTemplateNameLoc(),
5566 true,
5567 TID->getLAngleLoc(),
5568 TID->getTemplateArgs(),
5569 TID->getNumTemplateArgs(),
5570 TID->getRAngleLoc(),
5571 Fn->getType(),
5572 /*FIXME?*/false, /*FIXME?*/false);
Douglas Gregor6a573fe2009-10-22 18:02:20 +00005573
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005574 // FIXME: Don't destroy TID here, since we need its template arguments
5575 // to survive.
5576 // TID->Destroy(Context);
Douglas Gregor091f0422009-10-23 22:18:25 +00005577 } else if (isa<UnresolvedFunctionNameExpr>(E)) {
5578 return DeclRefExpr::Create(Context,
5579 /*Qualifier=*/0,
5580 /*QualifierRange=*/SourceRange(),
5581 Fn, E->getLocStart(),
5582 Fn->getType(), false, false);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005583 } else {
5584 assert(false && "Invalid reference to overloaded function");
5585 }
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005586
5587 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005588}
5589
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005590} // end namespace clang