blob: 24c3ae391b56dc7507c619b4530988a58bac3bfc [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>()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001390 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1391 // We're not going to find any constructors.
1392 } else if (CXXRecordDecl *ToRecordDecl
1393 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001394 // C++ [over.match.ctor]p1:
1395 // When objects of class type are direct-initialized (8.5), or
1396 // copy-initialized from an expression of the same or a
1397 // derived class type (8.5), overload resolution selects the
1398 // constructor. [...] For copy-initialization, the candidate
1399 // functions are all the converting constructors (12.3.1) of
1400 // that class. The argument list is the expression-list within
1401 // the parentheses of the initializer.
Mike Stump11289f42009-09-09 15:08:12 +00001402 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001403 = Context.DeclarationNames.getCXXConstructorName(
1404 Context.getCanonicalType(ToType).getUnqualifiedType());
1405 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001406 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001407 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001408 Con != ConEnd; ++Con) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001409 // Find the constructor (which may be a template).
1410 CXXConstructorDecl *Constructor = 0;
1411 FunctionTemplateDecl *ConstructorTmpl
1412 = dyn_cast<FunctionTemplateDecl>(*Con);
1413 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001414 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001415 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1416 else
1417 Constructor = cast<CXXConstructorDecl>(*Con);
Mike Stump11289f42009-09-09 15:08:12 +00001418
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001419 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001420 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001421 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001422 AddTemplateOverloadCandidate(ConstructorTmpl, false, 0, 0, &From,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001423 1, CandidateSet,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001424 /*SuppressUserConversions=*/!UserCast,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001425 ForceRValue);
1426 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001427 // Allow one user-defined conversion when user specifies a
1428 // From->ToType conversion via an static cast (c-style, etc).
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001429 AddOverloadCandidate(Constructor, &From, 1, CandidateSet,
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001430 /*SuppressUserConversions=*/!UserCast,
1431 ForceRValue);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001432 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001433 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001434 }
1435 }
1436
Douglas Gregor576e98c2009-01-30 23:27:23 +00001437 if (!AllowConversionFunctions) {
1438 // Don't allow any conversion functions to enter the overload set.
Mike Stump11289f42009-09-09 15:08:12 +00001439 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
1440 PDiag(0)
Anders Carlssond624e162009-08-26 23:45:07 +00001441 << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001442 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001443 } else if (const RecordType *FromRecordType
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001444 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001445 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001446 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1447 // Add all of the conversion functions as candidates.
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001448 OverloadedFunctionDecl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001449 = FromRecordDecl->getVisibleConversionFunctions();
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001450 for (OverloadedFunctionDecl::function_iterator Func
1451 = Conversions->function_begin();
1452 Func != Conversions->function_end(); ++Func) {
1453 CXXConversionDecl *Conv;
1454 FunctionTemplateDecl *ConvTemplate;
1455 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
1456 if (ConvTemplate)
1457 Conv = dyn_cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
1458 else
1459 Conv = dyn_cast<CXXConversionDecl>(*Func);
1460
1461 if (AllowExplicit || !Conv->isExplicit()) {
1462 if (ConvTemplate)
1463 AddTemplateConversionCandidate(ConvTemplate, From, ToType,
1464 CandidateSet);
1465 else
1466 AddConversionCandidate(Conv, From, ToType, CandidateSet);
1467 }
1468 }
1469 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001470 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001471
1472 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001473 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001474 case OR_Success:
1475 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001476 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001477 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1478 // C++ [over.ics.user]p1:
1479 // If the user-defined conversion is specified by a
1480 // constructor (12.3.1), the initial standard conversion
1481 // sequence converts the source type to the type required by
1482 // the argument of the constructor.
1483 //
1484 // FIXME: What about ellipsis conversions?
1485 QualType ThisType = Constructor->getThisType(Context);
1486 User.Before = Best->Conversions[0].Standard;
1487 User.ConversionFunction = Constructor;
1488 User.After.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00001489 User.After.FromTypePtr
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001490 = ThisType->getAs<PointerType>()->getPointeeType().getAsOpaquePtr();
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001491 User.After.ToTypePtr = ToType.getAsOpaquePtr();
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001492 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001493 } else if (CXXConversionDecl *Conversion
1494 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1495 // C++ [over.ics.user]p1:
1496 //
1497 // [...] If the user-defined conversion is specified by a
1498 // conversion function (12.3.2), the initial standard
1499 // conversion sequence converts the source type to the
1500 // implicit object parameter of the conversion function.
1501 User.Before = Best->Conversions[0].Standard;
1502 User.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00001503
1504 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001505 // The second standard conversion sequence converts the
1506 // result of the user-defined conversion to the target type
1507 // for the sequence. Since an implicit conversion sequence
1508 // is an initialization, the special rules for
1509 // initialization by user-defined conversion apply when
1510 // selecting the best user-defined conversion for a
1511 // user-defined conversion sequence (see 13.3.3 and
1512 // 13.3.3.1).
1513 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001514 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001515 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001516 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001517 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001518 }
Mike Stump11289f42009-09-09 15:08:12 +00001519
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001520 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001521 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001522 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001523 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001524 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001525
1526 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001527 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001528 }
1529
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001530 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001531}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001532
1533bool
1534Sema::DiagnoseAmbiguousUserDefinedConversion(Expr *From, QualType ToType) {
1535 ImplicitConversionSequence ICS;
1536 OverloadCandidateSet CandidateSet;
1537 OverloadingResult OvResult =
1538 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
1539 CandidateSet, true, false, false);
1540 if (OvResult != OR_Ambiguous)
1541 return false;
1542 Diag(From->getSourceRange().getBegin(),
1543 diag::err_typecheck_ambiguous_condition)
1544 << From->getType() << ToType << From->getSourceRange();
1545 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
1546 return true;
1547}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001548
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001549/// CompareImplicitConversionSequences - Compare two implicit
1550/// conversion sequences to determine whether one is better than the
1551/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001552ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001553Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1554 const ImplicitConversionSequence& ICS2)
1555{
1556 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1557 // conversion sequences (as defined in 13.3.3.1)
1558 // -- a standard conversion sequence (13.3.3.1.1) is a better
1559 // conversion sequence than a user-defined conversion sequence or
1560 // an ellipsis conversion sequence, and
1561 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1562 // conversion sequence than an ellipsis conversion sequence
1563 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001564 //
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001565 if (ICS1.ConversionKind < ICS2.ConversionKind)
1566 return ImplicitConversionSequence::Better;
1567 else if (ICS2.ConversionKind < ICS1.ConversionKind)
1568 return ImplicitConversionSequence::Worse;
1569
1570 // Two implicit conversion sequences of the same form are
1571 // indistinguishable conversion sequences unless one of the
1572 // following rules apply: (C++ 13.3.3.2p3):
1573 if (ICS1.ConversionKind == ImplicitConversionSequence::StandardConversion)
1574 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
Mike Stump11289f42009-09-09 15:08:12 +00001575 else if (ICS1.ConversionKind ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001576 ImplicitConversionSequence::UserDefinedConversion) {
1577 // User-defined conversion sequence U1 is a better conversion
1578 // sequence than another user-defined conversion sequence U2 if
1579 // they contain the same user-defined conversion function or
1580 // constructor and if the second standard conversion sequence of
1581 // U1 is better than the second standard conversion sequence of
1582 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001583 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001584 ICS2.UserDefined.ConversionFunction)
1585 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1586 ICS2.UserDefined.After);
1587 }
1588
1589 return ImplicitConversionSequence::Indistinguishable;
1590}
1591
1592/// CompareStandardConversionSequences - Compare two standard
1593/// conversion sequences to determine whether one is better than the
1594/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001595ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001596Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
1597 const StandardConversionSequence& SCS2)
1598{
1599 // Standard conversion sequence S1 is a better conversion sequence
1600 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
1601
1602 // -- S1 is a proper subsequence of S2 (comparing the conversion
1603 // sequences in the canonical form defined by 13.3.3.1.1,
1604 // excluding any Lvalue Transformation; the identity conversion
1605 // sequence is considered to be a subsequence of any
1606 // non-identity conversion sequence) or, if not that,
1607 if (SCS1.Second == SCS2.Second && SCS1.Third == SCS2.Third)
1608 // Neither is a proper subsequence of the other. Do nothing.
1609 ;
1610 else if ((SCS1.Second == ICK_Identity && SCS1.Third == SCS2.Third) ||
1611 (SCS1.Third == ICK_Identity && SCS1.Second == SCS2.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001612 (SCS1.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001613 SCS1.Third == ICK_Identity))
1614 // SCS1 is a proper subsequence of SCS2.
1615 return ImplicitConversionSequence::Better;
1616 else if ((SCS2.Second == ICK_Identity && SCS2.Third == SCS1.Third) ||
1617 (SCS2.Third == ICK_Identity && SCS2.Second == SCS1.Second) ||
Mike Stump11289f42009-09-09 15:08:12 +00001618 (SCS2.Second == ICK_Identity &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001619 SCS2.Third == ICK_Identity))
1620 // SCS2 is a proper subsequence of SCS1.
1621 return ImplicitConversionSequence::Worse;
1622
1623 // -- the rank of S1 is better than the rank of S2 (by the rules
1624 // defined below), or, if not that,
1625 ImplicitConversionRank Rank1 = SCS1.getRank();
1626 ImplicitConversionRank Rank2 = SCS2.getRank();
1627 if (Rank1 < Rank2)
1628 return ImplicitConversionSequence::Better;
1629 else if (Rank2 < Rank1)
1630 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001631
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001632 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
1633 // are indistinguishable unless one of the following rules
1634 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00001635
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001636 // A conversion that is not a conversion of a pointer, or
1637 // pointer to member, to bool is better than another conversion
1638 // that is such a conversion.
1639 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
1640 return SCS2.isPointerConversionToBool()
1641 ? ImplicitConversionSequence::Better
1642 : ImplicitConversionSequence::Worse;
1643
Douglas Gregor5c407d92008-10-23 00:40:37 +00001644 // C++ [over.ics.rank]p4b2:
1645 //
1646 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001647 // conversion of B* to A* is better than conversion of B* to
1648 // void*, and conversion of A* to void* is better than conversion
1649 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00001650 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001651 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00001652 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00001653 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001654 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
1655 // Exactly one of the conversion sequences is a conversion to
1656 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001657 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
1658 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001659 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
1660 // Neither conversion sequence converts to a void pointer; compare
1661 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001662 if (ImplicitConversionSequence::CompareKind DerivedCK
1663 = CompareDerivedToBaseConversions(SCS1, SCS2))
1664 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001665 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
1666 // Both conversion sequences are conversions to void
1667 // pointers. Compare the source types to determine if there's an
1668 // inheritance relationship in their sources.
1669 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1670 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1671
1672 // Adjust the types we're converting from via the array-to-pointer
1673 // conversion, if we need to.
1674 if (SCS1.First == ICK_Array_To_Pointer)
1675 FromType1 = Context.getArrayDecayedType(FromType1);
1676 if (SCS2.First == ICK_Array_To_Pointer)
1677 FromType2 = Context.getArrayDecayedType(FromType2);
1678
Mike Stump11289f42009-09-09 15:08:12 +00001679 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001680 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001681 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001682 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001683
1684 if (IsDerivedFrom(FromPointee2, FromPointee1))
1685 return ImplicitConversionSequence::Better;
1686 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1687 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001688
1689 // Objective-C++: If one interface is more specific than the
1690 // other, it is the better one.
John McCall9dd450b2009-09-21 23:43:11 +00001691 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1692 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001693 if (FromIface1 && FromIface1) {
1694 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1695 return ImplicitConversionSequence::Better;
1696 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1697 return ImplicitConversionSequence::Worse;
1698 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001699 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001700
1701 // Compare based on qualification conversions (C++ 13.3.3.2p3,
1702 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00001703 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001704 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00001705 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001706
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001707 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00001708 // C++0x [over.ics.rank]p3b4:
1709 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
1710 // implicit object parameter of a non-static member function declared
1711 // without a ref-qualifier, and S1 binds an rvalue reference to an
1712 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001713 // FIXME: We don't know if we're dealing with the implicit object parameter,
1714 // or if the member function in this case has a ref qualifier.
1715 // (Of course, we don't have ref qualifiers yet.)
1716 if (SCS1.RRefBinding != SCS2.RRefBinding)
1717 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
1718 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00001719
1720 // C++ [over.ics.rank]p3b4:
1721 // -- S1 and S2 are reference bindings (8.5.3), and the types to
1722 // which the references refer are the same type except for
1723 // top-level cv-qualifiers, and the type to which the reference
1724 // initialized by S2 refers is more cv-qualified than the type
1725 // to which the reference initialized by S1 refers.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00001726 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1727 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001728 T1 = Context.getCanonicalType(T1);
1729 T2 = Context.getCanonicalType(T2);
1730 if (T1.getUnqualifiedType() == T2.getUnqualifiedType()) {
1731 if (T2.isMoreQualifiedThan(T1))
1732 return ImplicitConversionSequence::Better;
1733 else if (T1.isMoreQualifiedThan(T2))
1734 return ImplicitConversionSequence::Worse;
1735 }
1736 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001737
1738 return ImplicitConversionSequence::Indistinguishable;
1739}
1740
1741/// CompareQualificationConversions - Compares two standard conversion
1742/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00001743/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
1744ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001745Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00001746 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00001747 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001748 // -- S1 and S2 differ only in their qualification conversion and
1749 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
1750 // cv-qualification signature of type T1 is a proper subset of
1751 // the cv-qualification signature of type T2, and S1 is not the
1752 // deprecated string literal array-to-pointer conversion (4.2).
1753 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
1754 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
1755 return ImplicitConversionSequence::Indistinguishable;
1756
1757 // FIXME: the example in the standard doesn't use a qualification
1758 // conversion (!)
1759 QualType T1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1760 QualType T2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1761 T1 = Context.getCanonicalType(T1);
1762 T2 = Context.getCanonicalType(T2);
1763
1764 // If the types are the same, we won't learn anything by unwrapped
1765 // them.
1766 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1767 return ImplicitConversionSequence::Indistinguishable;
1768
Mike Stump11289f42009-09-09 15:08:12 +00001769 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001770 = ImplicitConversionSequence::Indistinguishable;
1771 while (UnwrapSimilarPointerTypes(T1, T2)) {
1772 // Within each iteration of the loop, we check the qualifiers to
1773 // determine if this still looks like a qualification
1774 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001775 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001776 // until there are no more pointers or pointers-to-members left
1777 // to unwrap. This essentially mimics what
1778 // IsQualificationConversion does, but here we're checking for a
1779 // strict subset of qualifiers.
1780 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
1781 // The qualifiers are the same, so this doesn't tell us anything
1782 // about how the sequences rank.
1783 ;
1784 else if (T2.isMoreQualifiedThan(T1)) {
1785 // T1 has fewer qualifiers, so it could be the better sequence.
1786 if (Result == ImplicitConversionSequence::Worse)
1787 // Neither has qualifiers that are a subset of the other's
1788 // qualifiers.
1789 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001790
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001791 Result = ImplicitConversionSequence::Better;
1792 } else if (T1.isMoreQualifiedThan(T2)) {
1793 // T2 has fewer qualifiers, so it could be the better sequence.
1794 if (Result == ImplicitConversionSequence::Better)
1795 // Neither has qualifiers that are a subset of the other's
1796 // qualifiers.
1797 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00001798
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001799 Result = ImplicitConversionSequence::Worse;
1800 } else {
1801 // Qualifiers are disjoint.
1802 return ImplicitConversionSequence::Indistinguishable;
1803 }
1804
1805 // If the types after this point are equivalent, we're done.
1806 if (T1.getUnqualifiedType() == T2.getUnqualifiedType())
1807 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001808 }
1809
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001810 // Check that the winning standard conversion sequence isn't using
1811 // the deprecated string literal array to pointer conversion.
1812 switch (Result) {
1813 case ImplicitConversionSequence::Better:
1814 if (SCS1.Deprecated)
1815 Result = ImplicitConversionSequence::Indistinguishable;
1816 break;
1817
1818 case ImplicitConversionSequence::Indistinguishable:
1819 break;
1820
1821 case ImplicitConversionSequence::Worse:
1822 if (SCS2.Deprecated)
1823 Result = ImplicitConversionSequence::Indistinguishable;
1824 break;
1825 }
1826
1827 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001828}
1829
Douglas Gregor5c407d92008-10-23 00:40:37 +00001830/// CompareDerivedToBaseConversions - Compares two standard conversion
1831/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00001832/// various kinds of derived-to-base conversions (C++
1833/// [over.ics.rank]p4b3). As part of these checks, we also look at
1834/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00001835ImplicitConversionSequence::CompareKind
1836Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
1837 const StandardConversionSequence& SCS2) {
1838 QualType FromType1 = QualType::getFromOpaquePtr(SCS1.FromTypePtr);
1839 QualType ToType1 = QualType::getFromOpaquePtr(SCS1.ToTypePtr);
1840 QualType FromType2 = QualType::getFromOpaquePtr(SCS2.FromTypePtr);
1841 QualType ToType2 = QualType::getFromOpaquePtr(SCS2.ToTypePtr);
1842
1843 // Adjust the types we're converting from via the array-to-pointer
1844 // conversion, if we need to.
1845 if (SCS1.First == ICK_Array_To_Pointer)
1846 FromType1 = Context.getArrayDecayedType(FromType1);
1847 if (SCS2.First == ICK_Array_To_Pointer)
1848 FromType2 = Context.getArrayDecayedType(FromType2);
1849
1850 // Canonicalize all of the types.
1851 FromType1 = Context.getCanonicalType(FromType1);
1852 ToType1 = Context.getCanonicalType(ToType1);
1853 FromType2 = Context.getCanonicalType(FromType2);
1854 ToType2 = Context.getCanonicalType(ToType2);
1855
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001856 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00001857 //
1858 // If class B is derived directly or indirectly from class A and
1859 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001860 //
1861 // For Objective-C, we let A, B, and C also be Objective-C
1862 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001863
1864 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00001865 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00001866 SCS2.Second == ICK_Pointer_Conversion &&
1867 /*FIXME: Remove if Objective-C id conversions get their own rank*/
1868 FromType1->isPointerType() && FromType2->isPointerType() &&
1869 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001870 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001871 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001872 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001873 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001874 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001875 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00001876 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001877 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001878
John McCall9dd450b2009-09-21 23:43:11 +00001879 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
1880 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
1881 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
1882 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001883
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001884 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00001885 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1886 if (IsDerivedFrom(ToPointee1, ToPointee2))
1887 return ImplicitConversionSequence::Better;
1888 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1889 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00001890
1891 if (ToIface1 && ToIface2) {
1892 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
1893 return ImplicitConversionSequence::Better;
1894 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
1895 return ImplicitConversionSequence::Worse;
1896 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001897 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001898
1899 // -- conversion of B* to A* is better than conversion of C* to A*,
1900 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
1901 if (IsDerivedFrom(FromPointee2, FromPointee1))
1902 return ImplicitConversionSequence::Better;
1903 else if (IsDerivedFrom(FromPointee1, FromPointee2))
1904 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00001905
Douglas Gregor237f96c2008-11-26 23:31:11 +00001906 if (FromIface1 && FromIface2) {
1907 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
1908 return ImplicitConversionSequence::Better;
1909 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
1910 return ImplicitConversionSequence::Worse;
1911 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001912 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001913 }
1914
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001915 // Compare based on reference bindings.
1916 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding &&
1917 SCS1.Second == ICK_Derived_To_Base) {
1918 // -- binding of an expression of type C to a reference of type
1919 // B& is better than binding an expression of type C to a
1920 // reference of type A&,
1921 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1922 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1923 if (IsDerivedFrom(ToType1, ToType2))
1924 return ImplicitConversionSequence::Better;
1925 else if (IsDerivedFrom(ToType2, ToType1))
1926 return ImplicitConversionSequence::Worse;
1927 }
1928
Douglas Gregor2fe98832008-11-03 19:09:14 +00001929 // -- binding of an expression of type B to a reference of type
1930 // A& is better than binding an expression of type C to a
1931 // reference of type A&,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001932 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1933 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1934 if (IsDerivedFrom(FromType2, FromType1))
1935 return ImplicitConversionSequence::Better;
1936 else if (IsDerivedFrom(FromType1, FromType2))
1937 return ImplicitConversionSequence::Worse;
1938 }
1939 }
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00001940
1941 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00001942 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
1943 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
1944 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
1945 const MemberPointerType * FromMemPointer1 =
1946 FromType1->getAs<MemberPointerType>();
1947 const MemberPointerType * ToMemPointer1 =
1948 ToType1->getAs<MemberPointerType>();
1949 const MemberPointerType * FromMemPointer2 =
1950 FromType2->getAs<MemberPointerType>();
1951 const MemberPointerType * ToMemPointer2 =
1952 ToType2->getAs<MemberPointerType>();
1953 const Type *FromPointeeType1 = FromMemPointer1->getClass();
1954 const Type *ToPointeeType1 = ToMemPointer1->getClass();
1955 const Type *FromPointeeType2 = FromMemPointer2->getClass();
1956 const Type *ToPointeeType2 = ToMemPointer2->getClass();
1957 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
1958 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
1959 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
1960 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00001961 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00001962 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
1963 if (IsDerivedFrom(ToPointee1, ToPointee2))
1964 return ImplicitConversionSequence::Worse;
1965 else if (IsDerivedFrom(ToPointee2, ToPointee1))
1966 return ImplicitConversionSequence::Better;
1967 }
1968 // conversion of B::* to C::* is better than conversion of A::* to C::*
1969 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
1970 if (IsDerivedFrom(FromPointee1, FromPointee2))
1971 return ImplicitConversionSequence::Better;
1972 else if (IsDerivedFrom(FromPointee2, FromPointee1))
1973 return ImplicitConversionSequence::Worse;
1974 }
1975 }
1976
Douglas Gregor2fe98832008-11-03 19:09:14 +00001977 if (SCS1.CopyConstructor && SCS2.CopyConstructor &&
1978 SCS1.Second == ICK_Derived_To_Base) {
1979 // -- conversion of C to B is better than conversion of C to A,
1980 if (FromType1.getUnqualifiedType() == FromType2.getUnqualifiedType() &&
1981 ToType1.getUnqualifiedType() != ToType2.getUnqualifiedType()) {
1982 if (IsDerivedFrom(ToType1, ToType2))
1983 return ImplicitConversionSequence::Better;
1984 else if (IsDerivedFrom(ToType2, ToType1))
1985 return ImplicitConversionSequence::Worse;
1986 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001987
Douglas Gregor2fe98832008-11-03 19:09:14 +00001988 // -- conversion of B to A is better than conversion of C to A.
1989 if (FromType1.getUnqualifiedType() != FromType2.getUnqualifiedType() &&
1990 ToType1.getUnqualifiedType() == ToType2.getUnqualifiedType()) {
1991 if (IsDerivedFrom(FromType2, FromType1))
1992 return ImplicitConversionSequence::Better;
1993 else if (IsDerivedFrom(FromType1, FromType2))
1994 return ImplicitConversionSequence::Worse;
1995 }
1996 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00001997
Douglas Gregor5c407d92008-10-23 00:40:37 +00001998 return ImplicitConversionSequence::Indistinguishable;
1999}
2000
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002001/// TryCopyInitialization - Try to copy-initialize a value of type
2002/// ToType from the expression From. Return the implicit conversion
2003/// sequence required to pass this argument, which may be a bad
2004/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002005/// a parameter of this type). If @p SuppressUserConversions, then we
Sebastian Redl42e92c42009-04-12 17:16:29 +00002006/// do not permit any user-defined conversion sequences. If @p ForceRValue,
2007/// then we treat @p From as an rvalue, even if it is an lvalue.
Mike Stump11289f42009-09-09 15:08:12 +00002008ImplicitConversionSequence
2009Sema::TryCopyInitialization(Expr *From, QualType ToType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002010 bool SuppressUserConversions, bool ForceRValue,
2011 bool InOverloadResolution) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00002012 if (ToType->isReferenceType()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002013 ImplicitConversionSequence ICS;
Mike Stump11289f42009-09-09 15:08:12 +00002014 CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002015 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002016 SuppressUserConversions,
2017 /*AllowExplicit=*/false,
2018 ForceRValue,
2019 &ICS);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002020 return ICS;
2021 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002022 return TryImplicitConversion(From, ToType,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002023 SuppressUserConversions,
2024 /*AllowExplicit=*/false,
Anders Carlsson228eea32009-08-28 15:33:32 +00002025 ForceRValue,
2026 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002027 }
2028}
2029
Sebastian Redl42e92c42009-04-12 17:16:29 +00002030/// PerformCopyInitialization - Copy-initialize an object of type @p ToType with
2031/// the expression @p From. Returns true (and emits a diagnostic) if there was
2032/// an error, returns false if the initialization succeeded. Elidable should
2033/// be true when the copy may be elided (C++ 12.8p15). Overload resolution works
2034/// differently in C++0x for this case.
Mike Stump11289f42009-09-09 15:08:12 +00002035bool Sema::PerformCopyInitialization(Expr *&From, QualType ToType,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002036 const char* Flavor, bool Elidable) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002037 if (!getLangOptions().CPlusPlus) {
2038 // In C, argument passing is the same as performing an assignment.
2039 QualType FromType = From->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002040
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002041 AssignConvertType ConvTy =
2042 CheckSingleAssignmentConstraints(ToType, From);
Douglas Gregor0cfbdab2009-04-29 22:16:16 +00002043 if (ConvTy != Compatible &&
2044 CheckTransparentUnionArgumentConstraints(ToType, From) == Compatible)
2045 ConvTy = Compatible;
Mike Stump11289f42009-09-09 15:08:12 +00002046
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002047 return DiagnoseAssignmentResult(ConvTy, From->getLocStart(), ToType,
2048 FromType, From, Flavor);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002049 }
Sebastian Redl42e92c42009-04-12 17:16:29 +00002050
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002051 if (ToType->isReferenceType())
Anders Carlsson271e3a42009-08-27 17:30:43 +00002052 return CheckReferenceInit(From, ToType,
Douglas Gregorc809cc22009-09-23 23:04:10 +00002053 /*FIXME:*/From->getLocStart(),
Anders Carlsson271e3a42009-08-27 17:30:43 +00002054 /*SuppressUserConversions=*/false,
2055 /*AllowExplicit=*/false,
2056 /*ForceRValue=*/false);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002057
Sebastian Redl42e92c42009-04-12 17:16:29 +00002058 if (!PerformImplicitConversion(From, ToType, Flavor,
2059 /*AllowExplicit=*/false, Elidable))
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002060 return false;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002061 if (!DiagnoseAmbiguousUserDefinedConversion(From, ToType))
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002062 return Diag(From->getSourceRange().getBegin(),
2063 diag::err_typecheck_convert_incompatible)
2064 << ToType << From->getType() << Flavor << From->getSourceRange();
Fariborz Jahanian0b51c722009-09-22 19:53:15 +00002065 return true;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002066}
2067
Douglas Gregor436424c2008-11-18 23:14:02 +00002068/// TryObjectArgumentInitialization - Try to initialize the object
2069/// parameter of the given member function (@c Method) from the
2070/// expression @p From.
2071ImplicitConversionSequence
2072Sema::TryObjectArgumentInitialization(Expr *From, CXXMethodDecl *Method) {
2073 QualType ClassType = Context.getTypeDeclType(Method->getParent());
John McCall8ccfcb52009-09-24 19:53:00 +00002074 QualType ImplicitParamType
2075 = Context.getCVRQualifiedType(ClassType, Method->getTypeQualifiers());
Douglas Gregor436424c2008-11-18 23:14:02 +00002076
2077 // Set up the conversion sequence as a "bad" conversion, to allow us
2078 // to exit early.
2079 ImplicitConversionSequence ICS;
2080 ICS.Standard.setAsIdentityConversion();
2081 ICS.ConversionKind = ImplicitConversionSequence::BadConversion;
2082
2083 // We need to have an object of class type.
2084 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002085 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002086 FromType = PT->getPointeeType();
2087
2088 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002089
2090 // The implicit object parmeter is has the type "reference to cv X",
2091 // where X is the class of which the function is a member
2092 // (C++ [over.match.funcs]p4). However, when finding an implicit
2093 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002094 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002095 // (C++ [over.match.funcs]p5). We perform a simplified version of
2096 // reference binding here, that allows class rvalues to bind to
2097 // non-constant references.
2098
2099 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2100 // with the implicit object parameter (C++ [over.match.funcs]p5).
2101 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor01df9462009-11-05 00:07:36 +00002102 if (ImplicitParamType.getCVRQualifiers() != FromTypeCanon.getCVRQualifiers() &&
2103 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon))
Douglas Gregor436424c2008-11-18 23:14:02 +00002104 return ICS;
2105
2106 // Check that we have either the same type or a derived type. It
2107 // affects the conversion rank.
2108 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
2109 if (ClassTypeCanon == FromTypeCanon.getUnqualifiedType())
2110 ICS.Standard.Second = ICK_Identity;
2111 else if (IsDerivedFrom(FromType, ClassType))
2112 ICS.Standard.Second = ICK_Derived_To_Base;
2113 else
2114 return ICS;
2115
2116 // Success. Mark this as a reference binding.
2117 ICS.ConversionKind = ImplicitConversionSequence::StandardConversion;
2118 ICS.Standard.FromTypePtr = FromType.getAsOpaquePtr();
2119 ICS.Standard.ToTypePtr = ImplicitParamType.getAsOpaquePtr();
2120 ICS.Standard.ReferenceBinding = true;
2121 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002122 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002123 return ICS;
2124}
2125
2126/// PerformObjectArgumentInitialization - Perform initialization of
2127/// the implicit object parameter for the given Method with the given
2128/// expression.
2129bool
2130Sema::PerformObjectArgumentInitialization(Expr *&From, CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002131 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002132 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002133 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002134
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002135 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002136 FromRecordType = PT->getPointeeType();
2137 DestType = Method->getThisType(Context);
2138 } else {
2139 FromRecordType = From->getType();
2140 DestType = ImplicitParamRecordType;
2141 }
2142
Mike Stump11289f42009-09-09 15:08:12 +00002143 ImplicitConversionSequence ICS
Douglas Gregor436424c2008-11-18 23:14:02 +00002144 = TryObjectArgumentInitialization(From, Method);
2145 if (ICS.ConversionKind == ImplicitConversionSequence::BadConversion)
2146 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002147 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002148 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002149
Douglas Gregor436424c2008-11-18 23:14:02 +00002150 if (ICS.Standard.Second == ICK_Derived_To_Base &&
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002151 CheckDerivedToBaseConversion(FromRecordType,
2152 ImplicitParamRecordType,
Douglas Gregor436424c2008-11-18 23:14:02 +00002153 From->getSourceRange().getBegin(),
2154 From->getSourceRange()))
2155 return true;
2156
Mike Stump11289f42009-09-09 15:08:12 +00002157 ImpCastExprToType(From, DestType, CastExpr::CK_DerivedToBase,
Anders Carlsson4f4aab22009-08-07 18:45:49 +00002158 /*isLvalue=*/true);
Douglas Gregor436424c2008-11-18 23:14:02 +00002159 return false;
2160}
2161
Douglas Gregor5fb53972009-01-14 15:45:31 +00002162/// TryContextuallyConvertToBool - Attempt to contextually convert the
2163/// expression From to bool (C++0x [conv]p3).
2164ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002165 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002166 // FIXME: Are these flags correct?
2167 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002168 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002169 /*ForceRValue=*/false,
2170 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002171}
2172
2173/// PerformContextuallyConvertToBool - Perform a contextual conversion
2174/// of the expression From to bool (C++0x [conv]p3).
2175bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2176 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
2177 if (!PerformImplicitConversion(From, Context.BoolTy, ICS, "converting"))
2178 return false;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002179
2180 if (!DiagnoseAmbiguousUserDefinedConversion(From, Context.BoolTy))
2181 return Diag(From->getSourceRange().getBegin(),
2182 diag::err_typecheck_bool_condition)
2183 << From->getType() << From->getSourceRange();
2184 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002185}
2186
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002187/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002188/// candidate functions, using the given function call arguments. If
2189/// @p SuppressUserConversions, then don't allow user-defined
2190/// conversions via constructors or conversion operators.
Sebastian Redl42e92c42009-04-12 17:16:29 +00002191/// If @p ForceRValue, treat all arguments as rvalues. This is a slightly
2192/// hacky way to implement the overloading rules for elidable copy
2193/// initialization in C++0x (C++0x 12.8p15).
Douglas Gregorcabea402009-09-22 15:41:20 +00002194///
2195/// \para PartialOverloading true if we are performing "partial" overloading
2196/// based on an incomplete set of function arguments. This feature is used by
2197/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002198void
2199Sema::AddOverloadCandidate(FunctionDecl *Function,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002200 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002201 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002202 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002203 bool ForceRValue,
2204 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002205 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002206 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002207 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002208 assert(!isa<CXXConversionDecl>(Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002209 "Use AddConversionCandidate for conversion functions");
Mike Stump11289f42009-09-09 15:08:12 +00002210 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002211 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002212
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002213 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002214 if (!isa<CXXConstructorDecl>(Method)) {
2215 // If we get here, it's because we're calling a member function
2216 // that is named without a member access expression (e.g.,
2217 // "this->f") that was either written explicitly or created
2218 // implicitly. This can happen with a qualified call to a member
2219 // function, e.g., X::f(). We use a NULL object as the implied
2220 // object argument (C++ [over.call.func]p3).
Mike Stump11289f42009-09-09 15:08:12 +00002221 AddMethodCandidate(Method, 0, Args, NumArgs, CandidateSet,
Sebastian Redl1a99f442009-04-16 17:51:27 +00002222 SuppressUserConversions, ForceRValue);
2223 return;
2224 }
2225 // We treat a constructor like a non-member function, since its object
2226 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002227 }
2228
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002229 if (!CandidateSet.isNewCandidate(Function))
2230 return;
2231
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002232 // Add this candidate
2233 CandidateSet.push_back(OverloadCandidate());
2234 OverloadCandidate& Candidate = CandidateSet.back();
2235 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002236 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002237 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002238 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002239
2240 unsigned NumArgsInProto = Proto->getNumArgs();
2241
2242 // (C++ 13.3.2p2): A candidate function having fewer than m
2243 // parameters is viable only if it has an ellipsis in its parameter
2244 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002245 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2246 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002247 Candidate.Viable = false;
2248 return;
2249 }
2250
2251 // (C++ 13.3.2p2): A candidate function having more than m parameters
2252 // is viable only if the (m+1)st parameter has a default argument
2253 // (8.3.6). For the purposes of overload resolution, the
2254 // parameter list is truncated on the right, so that there are
2255 // exactly m parameters.
2256 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002257 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002258 // Not enough arguments.
2259 Candidate.Viable = false;
2260 return;
2261 }
2262
2263 // Determine the implicit conversion sequences for each of the
2264 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002265 Candidate.Conversions.resize(NumArgs);
2266 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2267 if (ArgIdx < NumArgsInProto) {
2268 // (C++ 13.3.2p3): for F to be a viable function, there shall
2269 // exist for each argument an implicit conversion sequence
2270 // (13.3.3.1) that converts that argument to the corresponding
2271 // parameter of F.
2272 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002273 Candidate.Conversions[ArgIdx]
2274 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002275 SuppressUserConversions, ForceRValue,
2276 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002277 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002278 == ImplicitConversionSequence::BadConversion) {
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002279 // 13.3.3.1-p10 If several different sequences of conversions exist that
2280 // each convert the argument to the parameter type, the implicit conversion
2281 // sequence associated with the parameter is defined to be the unique conversion
2282 // sequence designated the ambiguous conversion sequence. For the purpose of
2283 // ranking implicit conversion sequences as described in 13.3.3.2, the ambiguous
2284 // conversion sequence is treated as a user-defined sequence that is
2285 // indistinguishable from any other user-defined conversion sequence
Fariborz Jahanian91ae9fd2009-09-29 17:31:54 +00002286 if (!Candidate.Conversions[ArgIdx].ConversionFunctionSet.empty()) {
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002287 Candidate.Conversions[ArgIdx].ConversionKind =
2288 ImplicitConversionSequence::UserDefinedConversion;
Fariborz Jahanian91ae9fd2009-09-29 17:31:54 +00002289 // Set the conversion function to one of them. As due to ambiguity,
2290 // they carry the same weight and is needed for overload resolution
2291 // later.
2292 Candidate.Conversions[ArgIdx].UserDefined.ConversionFunction =
2293 Candidate.Conversions[ArgIdx].ConversionFunctionSet[0];
2294 }
Fariborz Jahanianc9c39172009-09-28 19:06:58 +00002295 else {
2296 Candidate.Viable = false;
2297 break;
2298 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002299 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002300 } else {
2301 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2302 // argument for which there is no corresponding parameter is
2303 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002304 Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002305 = ImplicitConversionSequence::EllipsisConversion;
2306 }
2307 }
2308}
2309
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002310/// \brief Add all of the function declarations in the given function set to
2311/// the overload canddiate set.
2312void Sema::AddFunctionCandidates(const FunctionSet &Functions,
2313 Expr **Args, unsigned NumArgs,
2314 OverloadCandidateSet& CandidateSet,
2315 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00002316 for (FunctionSet::const_iterator F = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002317 FEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00002318 F != FEnd; ++F) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002319 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*F)) {
2320 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
2321 AddMethodCandidate(cast<CXXMethodDecl>(FD),
2322 Args[0], Args + 1, NumArgs - 1,
2323 CandidateSet, SuppressUserConversions);
2324 else
2325 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
2326 SuppressUserConversions);
2327 } else {
2328 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(*F);
2329 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
2330 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
2331 AddMethodTemplateCandidate(FunTmpl,
Douglas Gregor89026b52009-06-30 23:57:56 +00002332 /*FIXME: explicit args */false, 0, 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002333 Args[0], Args + 1, NumArgs - 1,
2334 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00002335 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002336 else
2337 AddTemplateOverloadCandidate(FunTmpl,
2338 /*FIXME: explicit args */false, 0, 0,
2339 Args, NumArgs, CandidateSet,
2340 SuppressUserConversions);
2341 }
Douglas Gregor15448f82009-06-27 21:05:07 +00002342 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002343}
2344
Douglas Gregor436424c2008-11-18 23:14:02 +00002345/// AddMethodCandidate - Adds the given C++ member function to the set
2346/// of candidate functions, using the given function call arguments
2347/// and the object argument (@c Object). For example, in a call
2348/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
2349/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
2350/// allow user-defined conversions via constructors or conversion
Sebastian Redl42e92c42009-04-12 17:16:29 +00002351/// operators. If @p ForceRValue, treat all arguments as rvalues. This is
2352/// a slightly hacky way to implement the overloading rules for elidable copy
2353/// initialization in C++0x (C++0x 12.8p15).
Mike Stump11289f42009-09-09 15:08:12 +00002354void
Douglas Gregor436424c2008-11-18 23:14:02 +00002355Sema::AddMethodCandidate(CXXMethodDecl *Method, Expr *Object,
2356 Expr **Args, unsigned NumArgs,
2357 OverloadCandidateSet& CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00002358 bool SuppressUserConversions, bool ForceRValue) {
2359 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002360 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00002361 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002362 assert(!isa<CXXConversionDecl>(Method) &&
Douglas Gregor436424c2008-11-18 23:14:02 +00002363 "Use AddConversionCandidate for conversion functions");
Sebastian Redl1a99f442009-04-16 17:51:27 +00002364 assert(!isa<CXXConstructorDecl>(Method) &&
2365 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00002366
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002367 if (!CandidateSet.isNewCandidate(Method))
2368 return;
2369
Douglas Gregor436424c2008-11-18 23:14:02 +00002370 // Add this candidate
2371 CandidateSet.push_back(OverloadCandidate());
2372 OverloadCandidate& Candidate = CandidateSet.back();
2373 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002374 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002375 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002376
2377 unsigned NumArgsInProto = Proto->getNumArgs();
2378
2379 // (C++ 13.3.2p2): A candidate function having fewer than m
2380 // parameters is viable only if it has an ellipsis in its parameter
2381 // list (8.3.5).
2382 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2383 Candidate.Viable = false;
2384 return;
2385 }
2386
2387 // (C++ 13.3.2p2): A candidate function having more than m parameters
2388 // is viable only if the (m+1)st parameter has a default argument
2389 // (8.3.6). For the purposes of overload resolution, the
2390 // parameter list is truncated on the right, so that there are
2391 // exactly m parameters.
2392 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
2393 if (NumArgs < MinRequiredArgs) {
2394 // Not enough arguments.
2395 Candidate.Viable = false;
2396 return;
2397 }
2398
2399 Candidate.Viable = true;
2400 Candidate.Conversions.resize(NumArgs + 1);
2401
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002402 if (Method->isStatic() || !Object)
2403 // The implicit object argument is ignored.
2404 Candidate.IgnoreObjectArgument = true;
2405 else {
2406 // Determine the implicit conversion sequence for the object
2407 // parameter.
2408 Candidate.Conversions[0] = TryObjectArgumentInitialization(Object, Method);
Mike Stump11289f42009-09-09 15:08:12 +00002409 if (Candidate.Conversions[0].ConversionKind
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002410 == ImplicitConversionSequence::BadConversion) {
2411 Candidate.Viable = false;
2412 return;
2413 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002414 }
2415
2416 // Determine the implicit conversion sequences for each of the
2417 // arguments.
2418 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2419 if (ArgIdx < NumArgsInProto) {
2420 // (C++ 13.3.2p3): for F to be a viable function, there shall
2421 // exist for each argument an implicit conversion sequence
2422 // (13.3.3.1) that converts that argument to the corresponding
2423 // parameter of F.
2424 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002425 Candidate.Conversions[ArgIdx + 1]
2426 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson20d13322009-08-27 17:37:39 +00002427 SuppressUserConversions, ForceRValue,
Anders Carlsson228eea32009-08-28 15:33:32 +00002428 /*InOverloadResolution=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00002429 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002430 == ImplicitConversionSequence::BadConversion) {
2431 Candidate.Viable = false;
2432 break;
2433 }
2434 } else {
2435 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2436 // argument for which there is no corresponding parameter is
2437 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002438 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002439 = ImplicitConversionSequence::EllipsisConversion;
2440 }
2441 }
2442}
2443
Douglas Gregor97628d62009-08-21 00:16:32 +00002444/// \brief Add a C++ member function template as a candidate to the candidate
2445/// set, using template argument deduction to produce an appropriate member
2446/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002447void
Douglas Gregor97628d62009-08-21 00:16:32 +00002448Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
2449 bool HasExplicitTemplateArgs,
John McCall0ad16662009-10-29 08:12:44 +00002450 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002451 unsigned NumExplicitTemplateArgs,
2452 Expr *Object, Expr **Args, unsigned NumArgs,
2453 OverloadCandidateSet& CandidateSet,
2454 bool SuppressUserConversions,
2455 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002456 if (!CandidateSet.isNewCandidate(MethodTmpl))
2457 return;
2458
Douglas Gregor97628d62009-08-21 00:16:32 +00002459 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002460 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00002461 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002462 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00002463 // candidate functions in the usual way.113) A given name can refer to one
2464 // or more function templates and also to a set of overloaded non-template
2465 // functions. In such a case, the candidate functions generated from each
2466 // function template are combined with the set of non-template candidate
2467 // functions.
2468 TemplateDeductionInfo Info(Context);
2469 FunctionDecl *Specialization = 0;
2470 if (TemplateDeductionResult Result
2471 = DeduceTemplateArguments(MethodTmpl, HasExplicitTemplateArgs,
2472 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2473 Args, NumArgs, Specialization, Info)) {
2474 // FIXME: Record what happened with template argument deduction, so
2475 // that we can give the user a beautiful diagnostic.
2476 (void)Result;
2477 return;
2478 }
Mike Stump11289f42009-09-09 15:08:12 +00002479
Douglas Gregor97628d62009-08-21 00:16:32 +00002480 // Add the function template specialization produced by template argument
2481 // deduction as a candidate.
2482 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00002483 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00002484 "Specialization is not a member function?");
Mike Stump11289f42009-09-09 15:08:12 +00002485 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), Object, Args, NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00002486 CandidateSet, SuppressUserConversions, ForceRValue);
2487}
2488
Douglas Gregor05155d82009-08-21 23:19:43 +00002489/// \brief Add a C++ function template specialization as a candidate
2490/// in the candidate set, using template argument deduction to produce
2491/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00002492void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002493Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
Douglas Gregor89026b52009-06-30 23:57:56 +00002494 bool HasExplicitTemplateArgs,
John McCall0ad16662009-10-29 08:12:44 +00002495 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00002496 unsigned NumExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002497 Expr **Args, unsigned NumArgs,
2498 OverloadCandidateSet& CandidateSet,
2499 bool SuppressUserConversions,
2500 bool ForceRValue) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002501 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2502 return;
2503
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002504 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00002505 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002506 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00002507 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002508 // candidate functions in the usual way.113) A given name can refer to one
2509 // or more function templates and also to a set of overloaded non-template
2510 // functions. In such a case, the candidate functions generated from each
2511 // function template are combined with the set of non-template candidate
2512 // functions.
2513 TemplateDeductionInfo Info(Context);
2514 FunctionDecl *Specialization = 0;
2515 if (TemplateDeductionResult Result
Douglas Gregor89026b52009-06-30 23:57:56 +00002516 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
2517 ExplicitTemplateArgs, NumExplicitTemplateArgs,
2518 Args, NumArgs, Specialization, Info)) {
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002519 // FIXME: Record what happened with template argument deduction, so
2520 // that we can give the user a beautiful diagnostic.
2521 (void)Result;
2522 return;
2523 }
Mike Stump11289f42009-09-09 15:08:12 +00002524
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002525 // Add the function template specialization produced by template argument
2526 // deduction as a candidate.
2527 assert(Specialization && "Missing function template specialization?");
2528 AddOverloadCandidate(Specialization, Args, NumArgs, CandidateSet,
2529 SuppressUserConversions, ForceRValue);
2530}
Mike Stump11289f42009-09-09 15:08:12 +00002531
Douglas Gregora1f013e2008-11-07 22:36:19 +00002532/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00002533/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00002534/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00002535/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00002536/// (which may or may not be the same type as the type that the
2537/// conversion function produces).
2538void
2539Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
2540 Expr *From, QualType ToType,
2541 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00002542 assert(!Conversion->getDescribedFunctionTemplate() &&
2543 "Conversion function templates use AddTemplateConversionCandidate");
2544
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002545 if (!CandidateSet.isNewCandidate(Conversion))
2546 return;
2547
Douglas Gregora1f013e2008-11-07 22:36:19 +00002548 // Add this candidate
2549 CandidateSet.push_back(OverloadCandidate());
2550 OverloadCandidate& Candidate = CandidateSet.back();
2551 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002552 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002553 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002554 Candidate.FinalConversion.setAsIdentityConversion();
Mike Stump11289f42009-09-09 15:08:12 +00002555 Candidate.FinalConversion.FromTypePtr
Douglas Gregora1f013e2008-11-07 22:36:19 +00002556 = Conversion->getConversionType().getAsOpaquePtr();
2557 Candidate.FinalConversion.ToTypePtr = ToType.getAsOpaquePtr();
2558
Douglas Gregor436424c2008-11-18 23:14:02 +00002559 // Determine the implicit conversion sequence for the implicit
2560 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00002561 Candidate.Viable = true;
2562 Candidate.Conversions.resize(1);
Douglas Gregor436424c2008-11-18 23:14:02 +00002563 Candidate.Conversions[0] = TryObjectArgumentInitialization(From, Conversion);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002564 // Conversion functions to a different type in the base class is visible in
2565 // the derived class. So, a derived to base conversion should not participate
2566 // in overload resolution.
2567 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
2568 Candidate.Conversions[0].Standard.Second = ICK_Identity;
Mike Stump11289f42009-09-09 15:08:12 +00002569 if (Candidate.Conversions[0].ConversionKind
Douglas Gregora1f013e2008-11-07 22:36:19 +00002570 == ImplicitConversionSequence::BadConversion) {
2571 Candidate.Viable = false;
2572 return;
2573 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00002574
2575 // We won't go through a user-define type conversion function to convert a
2576 // derived to base as such conversions are given Conversion Rank. They only
2577 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
2578 QualType FromCanon
2579 = Context.getCanonicalType(From->getType().getUnqualifiedType());
2580 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
2581 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
2582 Candidate.Viable = false;
2583 return;
2584 }
2585
Douglas Gregora1f013e2008-11-07 22:36:19 +00002586
2587 // To determine what the conversion from the result of calling the
2588 // conversion function to the type we're eventually trying to
2589 // convert to (ToType), we need to synthesize a call to the
2590 // conversion function and attempt copy initialization from it. This
2591 // makes sure that we get the right semantics with respect to
2592 // lvalues/rvalues and the type. Fortunately, we can allocate this
2593 // call on the stack and we don't need its arguments to be
2594 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00002595 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregora1f013e2008-11-07 22:36:19 +00002596 SourceLocation());
2597 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00002598 CastExpr::CK_FunctionToPointerDecay,
Douglas Gregora11693b2008-11-12 17:17:38 +00002599 &ConversionRef, false);
Mike Stump11289f42009-09-09 15:08:12 +00002600
2601 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002602 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
2603 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00002604 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00002605 Conversion->getConversionType().getNonReferenceType(),
2606 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002607 ImplicitConversionSequence ICS =
2608 TryCopyInitialization(&Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002609 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00002610 /*ForceRValue=*/false,
2611 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002612
Douglas Gregora1f013e2008-11-07 22:36:19 +00002613 switch (ICS.ConversionKind) {
2614 case ImplicitConversionSequence::StandardConversion:
2615 Candidate.FinalConversion = ICS.Standard;
2616 break;
2617
2618 case ImplicitConversionSequence::BadConversion:
2619 Candidate.Viable = false;
2620 break;
2621
2622 default:
Mike Stump11289f42009-09-09 15:08:12 +00002623 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00002624 "Can only end up with a standard conversion sequence or failure");
2625 }
2626}
2627
Douglas Gregor05155d82009-08-21 23:19:43 +00002628/// \brief Adds a conversion function template specialization
2629/// candidate to the overload set, using template argument deduction
2630/// to deduce the template arguments of the conversion function
2631/// template from the type that we are converting to (C++
2632/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00002633void
Douglas Gregor05155d82009-08-21 23:19:43 +00002634Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
2635 Expr *From, QualType ToType,
2636 OverloadCandidateSet &CandidateSet) {
2637 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
2638 "Only conversion function templates permitted here");
2639
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002640 if (!CandidateSet.isNewCandidate(FunctionTemplate))
2641 return;
2642
Douglas Gregor05155d82009-08-21 23:19:43 +00002643 TemplateDeductionInfo Info(Context);
2644 CXXConversionDecl *Specialization = 0;
2645 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00002646 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00002647 Specialization, Info)) {
2648 // FIXME: Record what happened with template argument deduction, so
2649 // that we can give the user a beautiful diagnostic.
2650 (void)Result;
2651 return;
2652 }
Mike Stump11289f42009-09-09 15:08:12 +00002653
Douglas Gregor05155d82009-08-21 23:19:43 +00002654 // Add the conversion function template specialization produced by
2655 // template argument deduction as a candidate.
2656 assert(Specialization && "Missing function template specialization?");
2657 AddConversionCandidate(Specialization, From, ToType, CandidateSet);
2658}
2659
Douglas Gregorab7897a2008-11-19 22:57:39 +00002660/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
2661/// converts the given @c Object to a function pointer via the
2662/// conversion function @c Conversion, and then attempts to call it
2663/// with the given arguments (C++ [over.call.object]p2-4). Proto is
2664/// the type of function that we'll eventually be calling.
2665void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00002666 const FunctionProtoType *Proto,
Douglas Gregorab7897a2008-11-19 22:57:39 +00002667 Expr *Object, Expr **Args, unsigned NumArgs,
2668 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002669 if (!CandidateSet.isNewCandidate(Conversion))
2670 return;
2671
Douglas Gregorab7897a2008-11-19 22:57:39 +00002672 CandidateSet.push_back(OverloadCandidate());
2673 OverloadCandidate& Candidate = CandidateSet.back();
2674 Candidate.Function = 0;
2675 Candidate.Surrogate = Conversion;
2676 Candidate.Viable = true;
2677 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002678 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002679 Candidate.Conversions.resize(NumArgs + 1);
2680
2681 // Determine the implicit conversion sequence for the implicit
2682 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00002683 ImplicitConversionSequence ObjectInit
Douglas Gregorab7897a2008-11-19 22:57:39 +00002684 = TryObjectArgumentInitialization(Object, Conversion);
2685 if (ObjectInit.ConversionKind == ImplicitConversionSequence::BadConversion) {
2686 Candidate.Viable = false;
2687 return;
2688 }
2689
2690 // The first conversion is actually a user-defined conversion whose
2691 // first conversion is ObjectInit's standard conversion (which is
2692 // effectively a reference binding). Record it as such.
Mike Stump11289f42009-09-09 15:08:12 +00002693 Candidate.Conversions[0].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002694 = ImplicitConversionSequence::UserDefinedConversion;
2695 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
2696 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00002697 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00002698 = Candidate.Conversions[0].UserDefined.Before;
2699 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
2700
Mike Stump11289f42009-09-09 15:08:12 +00002701 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00002702 unsigned NumArgsInProto = Proto->getNumArgs();
2703
2704 // (C++ 13.3.2p2): A candidate function having fewer than m
2705 // parameters is viable only if it has an ellipsis in its parameter
2706 // list (8.3.5).
2707 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
2708 Candidate.Viable = false;
2709 return;
2710 }
2711
2712 // Function types don't have any default arguments, so just check if
2713 // we have enough arguments.
2714 if (NumArgs < NumArgsInProto) {
2715 // Not enough arguments.
2716 Candidate.Viable = false;
2717 return;
2718 }
2719
2720 // Determine the implicit conversion sequences for each of the
2721 // arguments.
2722 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
2723 if (ArgIdx < NumArgsInProto) {
2724 // (C++ 13.3.2p3): for F to be a viable function, there shall
2725 // exist for each argument an implicit conversion sequence
2726 // (13.3.3.1) that converts that argument to the corresponding
2727 // parameter of F.
2728 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00002729 Candidate.Conversions[ArgIdx + 1]
2730 = TryCopyInitialization(Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00002731 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00002732 /*ForceRValue=*/false,
2733 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00002734 if (Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002735 == ImplicitConversionSequence::BadConversion) {
2736 Candidate.Viable = false;
2737 break;
2738 }
2739 } else {
2740 // (C++ 13.3.2p2): For the purposes of overload resolution, any
2741 // argument for which there is no corresponding parameter is
2742 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002743 Candidate.Conversions[ArgIdx + 1].ConversionKind
Douglas Gregorab7897a2008-11-19 22:57:39 +00002744 = ImplicitConversionSequence::EllipsisConversion;
2745 }
2746 }
2747}
2748
Mike Stump87c57ac2009-05-16 07:39:55 +00002749// FIXME: This will eventually be removed, once we've migrated all of the
2750// operator overloading logic over to the scheme used by binary operators, which
2751// works for template instantiation.
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002752void Sema::AddOperatorCandidates(OverloadedOperatorKind Op, Scope *S,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002753 SourceLocation OpLoc,
Douglas Gregor436424c2008-11-18 23:14:02 +00002754 Expr **Args, unsigned NumArgs,
Douglas Gregor94eabf32009-02-04 16:44:47 +00002755 OverloadCandidateSet& CandidateSet,
2756 SourceRange OpRange) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002757 FunctionSet Functions;
2758
2759 QualType T1 = Args[0]->getType();
2760 QualType T2;
2761 if (NumArgs > 1)
2762 T2 = Args[1]->getType();
2763
2764 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Douglas Gregor7a77a6b2009-05-19 00:01:19 +00002765 if (S)
2766 LookupOverloadedOperatorName(Op, S, T1, T2, Functions);
Sebastian Redlc057f422009-10-23 19:23:15 +00002767 ArgumentDependentLookup(OpName, /*Operator*/true, Args, NumArgs, Functions);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002768 AddFunctionCandidates(Functions, Args, NumArgs, CandidateSet);
2769 AddMemberOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet, OpRange);
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002770 AddBuiltinOperatorCandidates(Op, OpLoc, Args, NumArgs, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00002771}
2772
2773/// \brief Add overload candidates for overloaded operators that are
2774/// member functions.
2775///
2776/// Add the overloaded operator candidates that are member functions
2777/// for the operator Op that was used in an operator expression such
2778/// as "x Op y". , Args/NumArgs provides the operator arguments, and
2779/// CandidateSet will store the added overload candidates. (C++
2780/// [over.match.oper]).
2781void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
2782 SourceLocation OpLoc,
2783 Expr **Args, unsigned NumArgs,
2784 OverloadCandidateSet& CandidateSet,
2785 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00002786 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
2787
2788 // C++ [over.match.oper]p3:
2789 // For a unary operator @ with an operand of a type whose
2790 // cv-unqualified version is T1, and for a binary operator @ with
2791 // a left operand of a type whose cv-unqualified version is T1 and
2792 // a right operand of a type whose cv-unqualified version is T2,
2793 // three sets of candidate functions, designated member
2794 // candidates, non-member candidates and built-in candidates, are
2795 // constructed as follows:
2796 QualType T1 = Args[0]->getType();
2797 QualType T2;
2798 if (NumArgs > 1)
2799 T2 = Args[1]->getType();
2800
2801 // -- If T1 is a class type, the set of member candidates is the
2802 // result of the qualified lookup of T1::operator@
2803 // (13.3.1.1.1); otherwise, the set of member candidates is
2804 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002805 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002806 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00002807 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002808 return;
Mike Stump11289f42009-09-09 15:08:12 +00002809
John McCall9f3059a2009-10-09 21:13:30 +00002810 LookupResult Operators;
2811 LookupQualifiedName(Operators, T1Rec->getDecl(), OpName,
2812 LookupOrdinaryName, false);
Mike Stump11289f42009-09-09 15:08:12 +00002813 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00002814 OperEnd = Operators.end();
2815 Oper != OperEnd;
Douglas Gregor4aa2dc42009-10-14 16:50:13 +00002816 ++Oper) {
2817 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Oper)) {
2818 AddMethodCandidate(Method, Args[0], Args+1, NumArgs - 1, CandidateSet,
2819 /*SuppressUserConversions=*/false);
2820 continue;
2821 }
2822
2823 assert(isa<FunctionTemplateDecl>(*Oper) &&
2824 isa<CXXMethodDecl>(cast<FunctionTemplateDecl>(*Oper)
2825 ->getTemplatedDecl()) &&
2826 "Expected a member function template");
2827 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Oper), false, 0, 0,
2828 Args[0], Args+1, NumArgs - 1, CandidateSet,
2829 /*SuppressUserConversions=*/false);
2830 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002831 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002832}
2833
Douglas Gregora11693b2008-11-12 17:17:38 +00002834/// AddBuiltinCandidate - Add a candidate for a built-in
2835/// operator. ResultTy and ParamTys are the result and parameter types
2836/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00002837/// arguments being passed to the candidate. IsAssignmentOperator
2838/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00002839/// operator. NumContextualBoolArguments is the number of arguments
2840/// (at the beginning of the argument list) that will be contextually
2841/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00002842void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00002843 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00002844 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00002845 bool IsAssignmentOperator,
2846 unsigned NumContextualBoolArguments) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002847 // Add this candidate
2848 CandidateSet.push_back(OverloadCandidate());
2849 OverloadCandidate& Candidate = CandidateSet.back();
2850 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00002851 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002852 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00002853 Candidate.BuiltinTypes.ResultTy = ResultTy;
2854 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
2855 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
2856
2857 // Determine the implicit conversion sequences for each of the
2858 // arguments.
2859 Candidate.Viable = true;
2860 Candidate.Conversions.resize(NumArgs);
2861 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00002862 // C++ [over.match.oper]p4:
2863 // For the built-in assignment operators, conversions of the
2864 // left operand are restricted as follows:
2865 // -- no temporaries are introduced to hold the left operand, and
2866 // -- no user-defined conversions are applied to the left
2867 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00002868 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00002869 //
2870 // We block these conversions by turning off user-defined
2871 // conversions, since that is the only way that initialization of
2872 // a reference to a non-class type can occur from something that
2873 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00002874 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00002875 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00002876 "Contextual conversion to bool requires bool type");
2877 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
2878 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002879 Candidate.Conversions[ArgIdx]
2880 = TryCopyInitialization(Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00002881 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00002882 /*ForceRValue=*/false,
2883 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002884 }
Mike Stump11289f42009-09-09 15:08:12 +00002885 if (Candidate.Conversions[ArgIdx].ConversionKind
Douglas Gregor436424c2008-11-18 23:14:02 +00002886 == ImplicitConversionSequence::BadConversion) {
Douglas Gregora11693b2008-11-12 17:17:38 +00002887 Candidate.Viable = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002888 break;
2889 }
Douglas Gregora11693b2008-11-12 17:17:38 +00002890 }
2891}
2892
2893/// BuiltinCandidateTypeSet - A set of types that will be used for the
2894/// candidate operator functions for built-in operators (C++
2895/// [over.built]). The types are separated into pointer types and
2896/// enumeration types.
2897class BuiltinCandidateTypeSet {
2898 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002899 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00002900
2901 /// PointerTypes - The set of pointer types that will be used in the
2902 /// built-in candidates.
2903 TypeSet PointerTypes;
2904
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002905 /// MemberPointerTypes - The set of member pointer types that will be
2906 /// used in the built-in candidates.
2907 TypeSet MemberPointerTypes;
2908
Douglas Gregora11693b2008-11-12 17:17:38 +00002909 /// EnumerationTypes - The set of enumeration types that will be
2910 /// used in the built-in candidates.
2911 TypeSet EnumerationTypes;
2912
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002913 /// Sema - The semantic analysis instance where we are building the
2914 /// candidate type set.
2915 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00002916
Douglas Gregora11693b2008-11-12 17:17:38 +00002917 /// Context - The AST context in which we will build the type sets.
2918 ASTContext &Context;
2919
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00002920 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
2921 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002922 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00002923
2924public:
2925 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002926 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00002927
Mike Stump11289f42009-09-09 15:08:12 +00002928 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002929 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00002930
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002931 void AddTypesConvertedFrom(QualType Ty,
2932 SourceLocation Loc,
2933 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00002934 bool AllowExplicitConversions,
2935 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00002936
2937 /// pointer_begin - First pointer type found;
2938 iterator pointer_begin() { return PointerTypes.begin(); }
2939
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002940 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00002941 iterator pointer_end() { return PointerTypes.end(); }
2942
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002943 /// member_pointer_begin - First member pointer type found;
2944 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
2945
2946 /// member_pointer_end - Past the last member pointer type found;
2947 iterator member_pointer_end() { return MemberPointerTypes.end(); }
2948
Douglas Gregora11693b2008-11-12 17:17:38 +00002949 /// enumeration_begin - First enumeration type found;
2950 iterator enumeration_begin() { return EnumerationTypes.begin(); }
2951
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002952 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00002953 iterator enumeration_end() { return EnumerationTypes.end(); }
2954};
2955
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002956/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00002957/// the set of pointer types along with any more-qualified variants of
2958/// that type. For example, if @p Ty is "int const *", this routine
2959/// will add "int const *", "int const volatile *", "int const
2960/// restrict *", and "int const volatile restrict *" to the set of
2961/// pointer types. Returns true if the add of @p Ty itself succeeded,
2962/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00002963///
2964/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002965bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00002966BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
2967 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00002968
Douglas Gregora11693b2008-11-12 17:17:38 +00002969 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00002970 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00002971 return false;
2972
John McCall8ccfcb52009-09-24 19:53:00 +00002973 const PointerType *PointerTy = Ty->getAs<PointerType>();
2974 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00002975
John McCall8ccfcb52009-09-24 19:53:00 +00002976 QualType PointeeTy = PointerTy->getPointeeType();
2977 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00002978 bool hasVolatile = VisibleQuals.hasVolatile();
2979 bool hasRestrict = VisibleQuals.hasRestrict();
2980
John McCall8ccfcb52009-09-24 19:53:00 +00002981 // Iterate through all strict supersets of BaseCVR.
2982 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
2983 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00002984 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
2985 // in the types.
2986 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
2987 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00002988 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
2989 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00002990 }
2991
2992 return true;
2993}
2994
Sebastian Redl8ce189f2009-04-19 21:53:20 +00002995/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
2996/// to the set of pointer types along with any more-qualified variants of
2997/// that type. For example, if @p Ty is "int const *", this routine
2998/// will add "int const *", "int const volatile *", "int const
2999/// restrict *", and "int const volatile restrict *" to the set of
3000/// pointer types. Returns true if the add of @p Ty itself succeeded,
3001/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003002///
3003/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003004bool
3005BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3006 QualType Ty) {
3007 // Insert this type.
3008 if (!MemberPointerTypes.insert(Ty))
3009 return false;
3010
John McCall8ccfcb52009-09-24 19:53:00 +00003011 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3012 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003013
John McCall8ccfcb52009-09-24 19:53:00 +00003014 QualType PointeeTy = PointerTy->getPointeeType();
3015 const Type *ClassTy = PointerTy->getClass();
3016
3017 // Iterate through all strict supersets of the pointee type's CVR
3018 // qualifiers.
3019 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3020 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3021 if ((CVR | BaseCVR) != CVR) continue;
3022
3023 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3024 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003025 }
3026
3027 return true;
3028}
3029
Douglas Gregora11693b2008-11-12 17:17:38 +00003030/// AddTypesConvertedFrom - Add each of the types to which the type @p
3031/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003032/// primarily interested in pointer types and enumeration types. We also
3033/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003034/// AllowUserConversions is true if we should look at the conversion
3035/// functions of a class type, and AllowExplicitConversions if we
3036/// should also include the explicit conversion functions of a class
3037/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003038void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003039BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003040 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003041 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003042 bool AllowExplicitConversions,
3043 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003044 // Only deal with canonical types.
3045 Ty = Context.getCanonicalType(Ty);
3046
3047 // Look through reference types; they aren't part of the type of an
3048 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003049 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003050 Ty = RefTy->getPointeeType();
3051
3052 // We don't care about qualifiers on the type.
3053 Ty = Ty.getUnqualifiedType();
3054
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003055 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003056 QualType PointeeTy = PointerTy->getPointeeType();
3057
3058 // Insert our type, and its more-qualified variants, into the set
3059 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003060 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003061 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003062 } else if (Ty->isMemberPointerType()) {
3063 // Member pointers are far easier, since the pointee can't be converted.
3064 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3065 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003066 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003067 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003068 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003069 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003070 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003071 // No conversion functions in incomplete types.
3072 return;
3073 }
Mike Stump11289f42009-09-09 15:08:12 +00003074
Douglas Gregora11693b2008-11-12 17:17:38 +00003075 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
Mike Stump11289f42009-09-09 15:08:12 +00003076 OverloadedFunctionDecl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003077 = ClassDecl->getVisibleConversionFunctions();
Mike Stump11289f42009-09-09 15:08:12 +00003078 for (OverloadedFunctionDecl::function_iterator Func
Douglas Gregora11693b2008-11-12 17:17:38 +00003079 = Conversions->function_begin();
3080 Func != Conversions->function_end(); ++Func) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003081 CXXConversionDecl *Conv;
3082 FunctionTemplateDecl *ConvTemplate;
3083 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
3084
Mike Stump11289f42009-09-09 15:08:12 +00003085 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003086 // about which builtin types we can convert to.
3087 if (ConvTemplate)
3088 continue;
3089
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003090 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003091 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003092 VisibleQuals);
3093 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003094 }
3095 }
3096 }
3097}
3098
Douglas Gregor84605ae2009-08-24 13:43:27 +00003099/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3100/// the volatile- and non-volatile-qualified assignment operators for the
3101/// given type to the candidate set.
3102static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3103 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003104 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003105 unsigned NumArgs,
3106 OverloadCandidateSet &CandidateSet) {
3107 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003108
Douglas Gregor84605ae2009-08-24 13:43:27 +00003109 // T& operator=(T&, T)
3110 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3111 ParamTypes[1] = T;
3112 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3113 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003114
Douglas Gregor84605ae2009-08-24 13:43:27 +00003115 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3116 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003117 ParamTypes[0]
3118 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003119 ParamTypes[1] = T;
3120 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003121 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003122 }
3123}
Mike Stump11289f42009-09-09 15:08:12 +00003124
Sebastian Redl1054fae2009-10-25 17:03:50 +00003125/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3126/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003127static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3128 Qualifiers VRQuals;
3129 const RecordType *TyRec;
3130 if (const MemberPointerType *RHSMPType =
3131 ArgExpr->getType()->getAs<MemberPointerType>())
3132 TyRec = cast<RecordType>(RHSMPType->getClass());
3133 else
3134 TyRec = ArgExpr->getType()->getAs<RecordType>();
3135 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003136 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003137 VRQuals.addVolatile();
3138 VRQuals.addRestrict();
3139 return VRQuals;
3140 }
3141
3142 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
3143 OverloadedFunctionDecl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003144 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003145
3146 for (OverloadedFunctionDecl::function_iterator Func
3147 = Conversions->function_begin();
3148 Func != Conversions->function_end(); ++Func) {
3149 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(*Func)) {
3150 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3151 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3152 CanTy = ResTypeRef->getPointeeType();
3153 // Need to go down the pointer/mempointer chain and add qualifiers
3154 // as see them.
3155 bool done = false;
3156 while (!done) {
3157 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3158 CanTy = ResTypePtr->getPointeeType();
3159 else if (const MemberPointerType *ResTypeMPtr =
3160 CanTy->getAs<MemberPointerType>())
3161 CanTy = ResTypeMPtr->getPointeeType();
3162 else
3163 done = true;
3164 if (CanTy.isVolatileQualified())
3165 VRQuals.addVolatile();
3166 if (CanTy.isRestrictQualified())
3167 VRQuals.addRestrict();
3168 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3169 return VRQuals;
3170 }
3171 }
3172 }
3173 return VRQuals;
3174}
3175
Douglas Gregord08452f2008-11-19 15:42:04 +00003176/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3177/// operator overloads to the candidate set (C++ [over.built]), based
3178/// on the operator @p Op and the arguments given. For example, if the
3179/// operator is a binary '+', this routine might add "int
3180/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003181void
Mike Stump11289f42009-09-09 15:08:12 +00003182Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003183 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003184 Expr **Args, unsigned NumArgs,
3185 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003186 // The set of "promoted arithmetic types", which are the arithmetic
3187 // types are that preserved by promotion (C++ [over.built]p2). Note
3188 // that the first few of these types are the promoted integral
3189 // types; these types need to be first.
3190 // FIXME: What about complex?
3191 const unsigned FirstIntegralType = 0;
3192 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003193 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003194 LastPromotedIntegralType = 13;
3195 const unsigned FirstPromotedArithmeticType = 7,
3196 LastPromotedArithmeticType = 16;
3197 const unsigned NumArithmeticTypes = 16;
3198 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003199 Context.BoolTy, Context.CharTy, Context.WCharTy,
3200// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003201 Context.SignedCharTy, Context.ShortTy,
3202 Context.UnsignedCharTy, Context.UnsignedShortTy,
3203 Context.IntTy, Context.LongTy, Context.LongLongTy,
3204 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3205 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3206 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003207 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3208 "Invalid first promoted integral type");
3209 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3210 == Context.UnsignedLongLongTy &&
3211 "Invalid last promoted integral type");
3212 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3213 "Invalid first promoted arithmetic type");
3214 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3215 == Context.LongDoubleTy &&
3216 "Invalid last promoted arithmetic type");
3217
Douglas Gregora11693b2008-11-12 17:17:38 +00003218 // Find all of the types that the arguments can convert to, but only
3219 // if the operator we're looking at has built-in operator candidates
3220 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003221 Qualifiers VisibleTypeConversionsQuals;
3222 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003223 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3224 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3225
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003226 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003227 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
3228 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003229 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00003230 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00003231 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00003232 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003233 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00003234 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003235 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003236 true,
3237 (Op == OO_Exclaim ||
3238 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003239 Op == OO_PipePipe),
3240 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003241 }
3242
3243 bool isComparison = false;
3244 switch (Op) {
3245 case OO_None:
3246 case NUM_OVERLOADED_OPERATORS:
3247 assert(false && "Expected an overloaded operator");
3248 break;
3249
Douglas Gregord08452f2008-11-19 15:42:04 +00003250 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00003251 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00003252 goto UnaryStar;
3253 else
3254 goto BinaryStar;
3255 break;
3256
3257 case OO_Plus: // '+' is either unary or binary
3258 if (NumArgs == 1)
3259 goto UnaryPlus;
3260 else
3261 goto BinaryPlus;
3262 break;
3263
3264 case OO_Minus: // '-' is either unary or binary
3265 if (NumArgs == 1)
3266 goto UnaryMinus;
3267 else
3268 goto BinaryMinus;
3269 break;
3270
3271 case OO_Amp: // '&' is either unary or binary
3272 if (NumArgs == 1)
3273 goto UnaryAmp;
3274 else
3275 goto BinaryAmp;
3276
3277 case OO_PlusPlus:
3278 case OO_MinusMinus:
3279 // C++ [over.built]p3:
3280 //
3281 // For every pair (T, VQ), where T is an arithmetic type, and VQ
3282 // is either volatile or empty, there exist candidate operator
3283 // functions of the form
3284 //
3285 // VQ T& operator++(VQ T&);
3286 // T operator++(VQ T&, int);
3287 //
3288 // C++ [over.built]p4:
3289 //
3290 // For every pair (T, VQ), where T is an arithmetic type other
3291 // than bool, and VQ is either volatile or empty, there exist
3292 // candidate operator functions of the form
3293 //
3294 // VQ T& operator--(VQ T&);
3295 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00003296 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003297 Arith < NumArithmeticTypes; ++Arith) {
3298 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00003299 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003300 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00003301
3302 // Non-volatile version.
3303 if (NumArgs == 1)
3304 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3305 else
3306 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003307 // heuristic to reduce number of builtin candidates in the set.
3308 // Add volatile version only if there are conversions to a volatile type.
3309 if (VisibleTypeConversionsQuals.hasVolatile()) {
3310 // Volatile version
3311 ParamTypes[0]
3312 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
3313 if (NumArgs == 1)
3314 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3315 else
3316 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
3317 }
Douglas Gregord08452f2008-11-19 15:42:04 +00003318 }
3319
3320 // C++ [over.built]p5:
3321 //
3322 // For every pair (T, VQ), where T is a cv-qualified or
3323 // cv-unqualified object type, and VQ is either volatile or
3324 // empty, there exist candidate operator functions of the form
3325 //
3326 // T*VQ& operator++(T*VQ&);
3327 // T*VQ& operator--(T*VQ&);
3328 // T* operator++(T*VQ&, int);
3329 // T* operator--(T*VQ&, int);
3330 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3331 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3332 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003333 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00003334 continue;
3335
Mike Stump11289f42009-09-09 15:08:12 +00003336 QualType ParamTypes[2] = {
3337 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00003338 };
Mike Stump11289f42009-09-09 15:08:12 +00003339
Douglas Gregord08452f2008-11-19 15:42:04 +00003340 // Without volatile
3341 if (NumArgs == 1)
3342 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3343 else
3344 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3345
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003346 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3347 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003348 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00003349 ParamTypes[0]
3350 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00003351 if (NumArgs == 1)
3352 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
3353 else
3354 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3355 }
3356 }
3357 break;
3358
3359 UnaryStar:
3360 // C++ [over.built]p6:
3361 // For every cv-qualified or cv-unqualified object type T, there
3362 // exist candidate operator functions of the form
3363 //
3364 // T& operator*(T*);
3365 //
3366 // C++ [over.built]p7:
3367 // For every function type T, there exist candidate operator
3368 // functions of the form
3369 // T& operator*(T*);
3370 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3371 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3372 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003373 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003374 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00003375 &ParamTy, Args, 1, CandidateSet);
3376 }
3377 break;
3378
3379 UnaryPlus:
3380 // C++ [over.built]p8:
3381 // For every type T, there exist candidate operator functions of
3382 // the form
3383 //
3384 // T* operator+(T*);
3385 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3386 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3387 QualType ParamTy = *Ptr;
3388 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
3389 }
Mike Stump11289f42009-09-09 15:08:12 +00003390
Douglas Gregord08452f2008-11-19 15:42:04 +00003391 // Fall through
3392
3393 UnaryMinus:
3394 // C++ [over.built]p9:
3395 // For every promoted arithmetic type T, there exist candidate
3396 // operator functions of the form
3397 //
3398 // T operator+(T);
3399 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00003400 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003401 Arith < LastPromotedArithmeticType; ++Arith) {
3402 QualType ArithTy = ArithmeticTypes[Arith];
3403 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
3404 }
3405 break;
3406
3407 case OO_Tilde:
3408 // C++ [over.built]p10:
3409 // For every promoted integral type T, there exist candidate
3410 // operator functions of the form
3411 //
3412 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00003413 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00003414 Int < LastPromotedIntegralType; ++Int) {
3415 QualType IntTy = ArithmeticTypes[Int];
3416 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
3417 }
3418 break;
3419
Douglas Gregora11693b2008-11-12 17:17:38 +00003420 case OO_New:
3421 case OO_Delete:
3422 case OO_Array_New:
3423 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00003424 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00003425 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00003426 break;
3427
3428 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00003429 UnaryAmp:
3430 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00003431 // C++ [over.match.oper]p3:
3432 // -- For the operator ',', the unary operator '&', or the
3433 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00003434 break;
3435
Douglas Gregor84605ae2009-08-24 13:43:27 +00003436 case OO_EqualEqual:
3437 case OO_ExclaimEqual:
3438 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00003439 // For every pointer to member type T, there exist candidate operator
3440 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00003441 //
3442 // bool operator==(T,T);
3443 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00003444 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00003445 MemPtr = CandidateTypes.member_pointer_begin(),
3446 MemPtrEnd = CandidateTypes.member_pointer_end();
3447 MemPtr != MemPtrEnd;
3448 ++MemPtr) {
3449 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
3450 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3451 }
Mike Stump11289f42009-09-09 15:08:12 +00003452
Douglas Gregor84605ae2009-08-24 13:43:27 +00003453 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00003454
Douglas Gregora11693b2008-11-12 17:17:38 +00003455 case OO_Less:
3456 case OO_Greater:
3457 case OO_LessEqual:
3458 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00003459 // C++ [over.built]p15:
3460 //
3461 // For every pointer or enumeration type T, there exist
3462 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003463 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003464 // bool operator<(T, T);
3465 // bool operator>(T, T);
3466 // bool operator<=(T, T);
3467 // bool operator>=(T, T);
3468 // bool operator==(T, T);
3469 // bool operator!=(T, T);
3470 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3471 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3472 QualType ParamTypes[2] = { *Ptr, *Ptr };
3473 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3474 }
Mike Stump11289f42009-09-09 15:08:12 +00003475 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00003476 = CandidateTypes.enumeration_begin();
3477 Enum != CandidateTypes.enumeration_end(); ++Enum) {
3478 QualType ParamTypes[2] = { *Enum, *Enum };
3479 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
3480 }
3481
3482 // Fall through.
3483 isComparison = true;
3484
Douglas Gregord08452f2008-11-19 15:42:04 +00003485 BinaryPlus:
3486 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00003487 if (!isComparison) {
3488 // We didn't fall through, so we must have OO_Plus or OO_Minus.
3489
3490 // C++ [over.built]p13:
3491 //
3492 // For every cv-qualified or cv-unqualified object type T
3493 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003494 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003495 // T* operator+(T*, ptrdiff_t);
3496 // T& operator[](T*, ptrdiff_t); [BELOW]
3497 // T* operator-(T*, ptrdiff_t);
3498 // T* operator+(ptrdiff_t, T*);
3499 // T& operator[](ptrdiff_t, T*); [BELOW]
3500 //
3501 // C++ [over.built]p14:
3502 //
3503 // For every T, where T is a pointer to object type, there
3504 // exist candidate operator functions of the form
3505 //
3506 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00003507 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00003508 = CandidateTypes.pointer_begin();
3509 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3510 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
3511
3512 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
3513 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3514
3515 if (Op == OO_Plus) {
3516 // T* operator+(ptrdiff_t, T*);
3517 ParamTypes[0] = ParamTypes[1];
3518 ParamTypes[1] = *Ptr;
3519 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3520 } else {
3521 // ptrdiff_t operator-(T, T);
3522 ParamTypes[1] = *Ptr;
3523 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
3524 Args, 2, CandidateSet);
3525 }
3526 }
3527 }
3528 // Fall through
3529
Douglas Gregora11693b2008-11-12 17:17:38 +00003530 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00003531 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00003532 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00003533 // C++ [over.built]p12:
3534 //
3535 // For every pair of promoted arithmetic types L and R, there
3536 // exist candidate operator functions of the form
3537 //
3538 // LR operator*(L, R);
3539 // LR operator/(L, R);
3540 // LR operator+(L, R);
3541 // LR operator-(L, R);
3542 // bool operator<(L, R);
3543 // bool operator>(L, R);
3544 // bool operator<=(L, R);
3545 // bool operator>=(L, R);
3546 // bool operator==(L, R);
3547 // bool operator!=(L, R);
3548 //
3549 // where LR is the result of the usual arithmetic conversions
3550 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00003551 //
3552 // C++ [over.built]p24:
3553 //
3554 // For every pair of promoted arithmetic types L and R, there exist
3555 // candidate operator functions of the form
3556 //
3557 // LR operator?(bool, L, R);
3558 //
3559 // where LR is the result of the usual arithmetic conversions
3560 // between types L and R.
3561 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003562 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003563 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003564 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003565 Right < LastPromotedArithmeticType; ++Right) {
3566 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003567 QualType Result
3568 = isComparison
3569 ? Context.BoolTy
3570 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003571 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3572 }
3573 }
3574 break;
3575
3576 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00003577 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00003578 case OO_Caret:
3579 case OO_Pipe:
3580 case OO_LessLess:
3581 case OO_GreaterGreater:
3582 // C++ [over.built]p17:
3583 //
3584 // For every pair of promoted integral types L and R, there
3585 // exist candidate operator functions of the form
3586 //
3587 // LR operator%(L, R);
3588 // LR operator&(L, R);
3589 // LR operator^(L, R);
3590 // LR operator|(L, R);
3591 // L operator<<(L, R);
3592 // L operator>>(L, R);
3593 //
3594 // where LR is the result of the usual arithmetic conversions
3595 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00003596 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003597 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003598 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003599 Right < LastPromotedIntegralType; ++Right) {
3600 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
3601 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
3602 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00003603 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003604 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
3605 }
3606 }
3607 break;
3608
3609 case OO_Equal:
3610 // C++ [over.built]p20:
3611 //
3612 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00003613 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00003614 // empty, there exist candidate operator functions of the form
3615 //
3616 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003617 for (BuiltinCandidateTypeSet::iterator
3618 Enum = CandidateTypes.enumeration_begin(),
3619 EnumEnd = CandidateTypes.enumeration_end();
3620 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00003621 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003622 CandidateSet);
3623 for (BuiltinCandidateTypeSet::iterator
3624 MemPtr = CandidateTypes.member_pointer_begin(),
3625 MemPtrEnd = CandidateTypes.member_pointer_end();
3626 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00003627 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003628 CandidateSet);
3629 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00003630
3631 case OO_PlusEqual:
3632 case OO_MinusEqual:
3633 // C++ [over.built]p19:
3634 //
3635 // For every pair (T, VQ), where T is any type and VQ is either
3636 // volatile or empty, there exist candidate operator functions
3637 // of the form
3638 //
3639 // T*VQ& operator=(T*VQ&, T*);
3640 //
3641 // C++ [over.built]p21:
3642 //
3643 // For every pair (T, VQ), where T is a cv-qualified or
3644 // cv-unqualified object type and VQ is either volatile or
3645 // empty, there exist candidate operator functions of the form
3646 //
3647 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
3648 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
3649 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3650 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3651 QualType ParamTypes[2];
3652 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
3653
3654 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003655 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003656 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3657 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003658
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003659 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
3660 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00003661 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00003662 ParamTypes[0]
3663 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00003664 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3665 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00003666 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003667 }
3668 // Fall through.
3669
3670 case OO_StarEqual:
3671 case OO_SlashEqual:
3672 // C++ [over.built]p18:
3673 //
3674 // For every triple (L, VQ, R), where L is an arithmetic type,
3675 // VQ is either volatile or empty, and R is a promoted
3676 // arithmetic type, there exist candidate operator functions of
3677 // the form
3678 //
3679 // VQ L& operator=(VQ L&, R);
3680 // VQ L& operator*=(VQ L&, R);
3681 // VQ L& operator/=(VQ L&, R);
3682 // VQ L& operator+=(VQ L&, R);
3683 // VQ L& operator-=(VQ L&, R);
3684 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003685 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003686 Right < LastPromotedArithmeticType; ++Right) {
3687 QualType ParamTypes[2];
3688 ParamTypes[1] = ArithmeticTypes[Right];
3689
3690 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003691 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00003692 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3693 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00003694
3695 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003696 if (VisibleTypeConversionsQuals.hasVolatile()) {
3697 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
3698 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3699 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3700 /*IsAssigmentOperator=*/Op == OO_Equal);
3701 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003702 }
3703 }
3704 break;
3705
3706 case OO_PercentEqual:
3707 case OO_LessLessEqual:
3708 case OO_GreaterGreaterEqual:
3709 case OO_AmpEqual:
3710 case OO_CaretEqual:
3711 case OO_PipeEqual:
3712 // C++ [over.built]p22:
3713 //
3714 // For every triple (L, VQ, R), where L is an integral type, VQ
3715 // is either volatile or empty, and R is a promoted integral
3716 // type, there exist candidate operator functions of the form
3717 //
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 // VQ L& operator^=(VQ L&, R);
3723 // VQ L& operator|=(VQ L&, R);
3724 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00003725 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00003726 Right < LastPromotedIntegralType; ++Right) {
3727 QualType ParamTypes[2];
3728 ParamTypes[1] = ArithmeticTypes[Right];
3729
3730 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003731 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00003732 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00003733 if (VisibleTypeConversionsQuals.hasVolatile()) {
3734 // Add this built-in operator as a candidate (VQ is 'volatile').
3735 ParamTypes[0] = ArithmeticTypes[Left];
3736 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
3737 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
3738 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
3739 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003740 }
3741 }
3742 break;
3743
Douglas Gregord08452f2008-11-19 15:42:04 +00003744 case OO_Exclaim: {
3745 // C++ [over.operator]p23:
3746 //
3747 // There also exist candidate operator functions of the form
3748 //
Mike Stump11289f42009-09-09 15:08:12 +00003749 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00003750 // bool operator&&(bool, bool); [BELOW]
3751 // bool operator||(bool, bool); [BELOW]
3752 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003753 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
3754 /*IsAssignmentOperator=*/false,
3755 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00003756 break;
3757 }
3758
Douglas Gregora11693b2008-11-12 17:17:38 +00003759 case OO_AmpAmp:
3760 case OO_PipePipe: {
3761 // C++ [over.operator]p23:
3762 //
3763 // There also exist candidate operator functions of the form
3764 //
Douglas Gregord08452f2008-11-19 15:42:04 +00003765 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00003766 // bool operator&&(bool, bool);
3767 // bool operator||(bool, bool);
3768 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00003769 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
3770 /*IsAssignmentOperator=*/false,
3771 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00003772 break;
3773 }
3774
3775 case OO_Subscript:
3776 // C++ [over.built]p13:
3777 //
3778 // For every cv-qualified or cv-unqualified object type T there
3779 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00003780 //
Douglas Gregora11693b2008-11-12 17:17:38 +00003781 // T* operator+(T*, ptrdiff_t); [ABOVE]
3782 // T& operator[](T*, ptrdiff_t);
3783 // T* operator-(T*, ptrdiff_t); [ABOVE]
3784 // T* operator+(ptrdiff_t, T*); [ABOVE]
3785 // T& operator[](ptrdiff_t, T*);
3786 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
3787 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3788 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003789 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00003790 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00003791
3792 // T& operator[](T*, ptrdiff_t)
3793 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3794
3795 // T& operator[](ptrdiff_t, T*);
3796 ParamTypes[0] = ParamTypes[1];
3797 ParamTypes[1] = *Ptr;
3798 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3799 }
3800 break;
3801
3802 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003803 // C++ [over.built]p11:
3804 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
3805 // C1 is the same type as C2 or is a derived class of C2, T is an object
3806 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
3807 // there exist candidate operator functions of the form
3808 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
3809 // where CV12 is the union of CV1 and CV2.
3810 {
3811 for (BuiltinCandidateTypeSet::iterator Ptr =
3812 CandidateTypes.pointer_begin();
3813 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
3814 QualType C1Ty = (*Ptr);
3815 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003816 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003817 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003818 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003819 if (!isa<RecordType>(C1))
3820 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003821 // heuristic to reduce number of builtin candidates in the set.
3822 // Add volatile/restrict version only if there are conversions to a
3823 // volatile/restrict type.
3824 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
3825 continue;
3826 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
3827 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003828 }
3829 for (BuiltinCandidateTypeSet::iterator
3830 MemPtr = CandidateTypes.member_pointer_begin(),
3831 MemPtrEnd = CandidateTypes.member_pointer_end();
3832 MemPtr != MemPtrEnd; ++MemPtr) {
3833 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
3834 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00003835 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003836 if (C1 != C2 && !IsDerivedFrom(C1, C2))
3837 break;
3838 QualType ParamTypes[2] = { *Ptr, *MemPtr };
3839 // build CV12 T&
3840 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003841 if (!VisibleTypeConversionsQuals.hasVolatile() &&
3842 T.isVolatileQualified())
3843 continue;
3844 if (!VisibleTypeConversionsQuals.hasRestrict() &&
3845 T.isRestrictQualified())
3846 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00003847 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00003848 QualType ResultTy = Context.getLValueReferenceType(T);
3849 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
3850 }
3851 }
3852 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003853 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00003854
3855 case OO_Conditional:
3856 // Note that we don't consider the first argument, since it has been
3857 // contextually converted to bool long ago. The candidates below are
3858 // therefore added as binary.
3859 //
3860 // C++ [over.built]p24:
3861 // For every type T, where T is a pointer or pointer-to-member type,
3862 // there exist candidate operator functions of the form
3863 //
3864 // T operator?(bool, T, T);
3865 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00003866 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
3867 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
3868 QualType ParamTypes[2] = { *Ptr, *Ptr };
3869 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3870 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003871 for (BuiltinCandidateTypeSet::iterator Ptr =
3872 CandidateTypes.member_pointer_begin(),
3873 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
3874 QualType ParamTypes[2] = { *Ptr, *Ptr };
3875 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
3876 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00003877 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00003878 }
3879}
3880
Douglas Gregore254f902009-02-04 00:32:51 +00003881/// \brief Add function candidates found via argument-dependent lookup
3882/// to the set of overloading candidates.
3883///
3884/// This routine performs argument-dependent name lookup based on the
3885/// given function name (which may also be an operator name) and adds
3886/// all of the overload candidates found by ADL to the overload
3887/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00003888void
Douglas Gregore254f902009-02-04 00:32:51 +00003889Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
3890 Expr **Args, unsigned NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00003891 bool HasExplicitTemplateArgs,
John McCall0ad16662009-10-29 08:12:44 +00003892 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00003893 unsigned NumExplicitTemplateArgs,
3894 OverloadCandidateSet& CandidateSet,
3895 bool PartialOverloading) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003896 FunctionSet Functions;
Douglas Gregore254f902009-02-04 00:32:51 +00003897
Douglas Gregorcabea402009-09-22 15:41:20 +00003898 // FIXME: Should we be trafficking in canonical function decls throughout?
3899
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003900 // Record all of the function candidates that we've already
3901 // added to the overload set, so that we don't add those same
3902 // candidates a second time.
3903 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3904 CandEnd = CandidateSet.end();
3905 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003906 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003907 Functions.insert(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003908 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3909 Functions.insert(FunTmpl);
3910 }
Douglas Gregore254f902009-02-04 00:32:51 +00003911
Douglas Gregorcabea402009-09-22 15:41:20 +00003912 // FIXME: Pass in the explicit template arguments?
Sebastian Redlc057f422009-10-23 19:23:15 +00003913 ArgumentDependentLookup(Name, /*Operator*/false, Args, NumArgs, Functions);
Douglas Gregore254f902009-02-04 00:32:51 +00003914
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003915 // Erase all of the candidates we already knew about.
3916 // FIXME: This is suboptimal. Is there a better way?
3917 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
3918 CandEnd = CandidateSet.end();
3919 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00003920 if (Cand->Function) {
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003921 Functions.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00003922 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
3923 Functions.erase(FunTmpl);
3924 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00003925
3926 // For each of the ADL candidates we found, add it to the overload
3927 // set.
3928 for (FunctionSet::iterator Func = Functions.begin(),
3929 FuncEnd = Functions.end();
Douglas Gregor15448f82009-06-27 21:05:07 +00003930 Func != FuncEnd; ++Func) {
Douglas Gregorcabea402009-09-22 15:41:20 +00003931 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*Func)) {
3932 if (HasExplicitTemplateArgs)
3933 continue;
3934
3935 AddOverloadCandidate(FD, Args, NumArgs, CandidateSet,
3936 false, false, PartialOverloading);
3937 } else
Mike Stump11289f42009-09-09 15:08:12 +00003938 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*Func),
Douglas Gregorcabea402009-09-22 15:41:20 +00003939 HasExplicitTemplateArgs,
3940 ExplicitTemplateArgs,
3941 NumExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003942 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00003943 }
Douglas Gregore254f902009-02-04 00:32:51 +00003944}
3945
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003946/// isBetterOverloadCandidate - Determines whether the first overload
3947/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00003948bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003949Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
Mike Stump11289f42009-09-09 15:08:12 +00003950 const OverloadCandidate& Cand2) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003951 // Define viable functions to be better candidates than non-viable
3952 // functions.
3953 if (!Cand2.Viable)
3954 return Cand1.Viable;
3955 else if (!Cand1.Viable)
3956 return false;
3957
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003958 // C++ [over.match.best]p1:
3959 //
3960 // -- if F is a static member function, ICS1(F) is defined such
3961 // that ICS1(F) is neither better nor worse than ICS1(G) for
3962 // any function G, and, symmetrically, ICS1(G) is neither
3963 // better nor worse than ICS1(F).
3964 unsigned StartArg = 0;
3965 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
3966 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003967
Douglas Gregord3cb3562009-07-07 23:38:56 +00003968 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00003969 // A viable function F1 is defined to be a better function than another
3970 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00003971 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003972 unsigned NumArgs = Cand1.Conversions.size();
3973 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
3974 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003975 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003976 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
3977 Cand2.Conversions[ArgIdx])) {
3978 case ImplicitConversionSequence::Better:
3979 // Cand1 has a better conversion sequence.
3980 HasBetterConversion = true;
3981 break;
3982
3983 case ImplicitConversionSequence::Worse:
3984 // Cand1 can't be better than Cand2.
3985 return false;
3986
3987 case ImplicitConversionSequence::Indistinguishable:
3988 // Do nothing.
3989 break;
3990 }
3991 }
3992
Mike Stump11289f42009-09-09 15:08:12 +00003993 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00003994 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003995 if (HasBetterConversion)
3996 return true;
3997
Mike Stump11289f42009-09-09 15:08:12 +00003998 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00003999 // specialization, or, if not that,
4000 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4001 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4002 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004003
4004 // -- F1 and F2 are function template specializations, and the function
4005 // template for F1 is more specialized than the template for F2
4006 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004007 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004008 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4009 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004010 if (FunctionTemplateDecl *BetterTemplate
4011 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4012 Cand2.Function->getPrimaryTemplate(),
Douglas Gregor6010da02009-09-14 23:02:14 +00004013 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4014 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004015 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004016
Douglas Gregora1f013e2008-11-07 22:36:19 +00004017 // -- the context is an initialization by user-defined conversion
4018 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4019 // from the return type of F1 to the destination type (i.e.,
4020 // the type of the entity being initialized) is a better
4021 // conversion sequence than the standard conversion sequence
4022 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004023 if (Cand1.Function && Cand2.Function &&
4024 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004025 isa<CXXConversionDecl>(Cand2.Function)) {
4026 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4027 Cand2.FinalConversion)) {
4028 case ImplicitConversionSequence::Better:
4029 // Cand1 has a better conversion sequence.
4030 return true;
4031
4032 case ImplicitConversionSequence::Worse:
4033 // Cand1 can't be better than Cand2.
4034 return false;
4035
4036 case ImplicitConversionSequence::Indistinguishable:
4037 // Do nothing
4038 break;
4039 }
4040 }
4041
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004042 return false;
4043}
4044
Mike Stump11289f42009-09-09 15:08:12 +00004045/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004046/// within an overload candidate set.
4047///
4048/// \param CandidateSet the set of candidate functions.
4049///
4050/// \param Loc the location of the function name (or operator symbol) for
4051/// which overload resolution occurs.
4052///
Mike Stump11289f42009-09-09 15:08:12 +00004053/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004054/// function, Best points to the candidate function found.
4055///
4056/// \returns The result of overload resolution.
Mike Stump11289f42009-09-09 15:08:12 +00004057Sema::OverloadingResult
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004058Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004059 SourceLocation Loc,
Mike Stump11289f42009-09-09 15:08:12 +00004060 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004061 // Find the best viable function.
4062 Best = CandidateSet.end();
4063 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4064 Cand != CandidateSet.end(); ++Cand) {
4065 if (Cand->Viable) {
4066 if (Best == CandidateSet.end() || isBetterOverloadCandidate(*Cand, *Best))
4067 Best = Cand;
4068 }
4069 }
4070
4071 // If we didn't find any viable functions, abort.
4072 if (Best == CandidateSet.end())
4073 return OR_No_Viable_Function;
4074
4075 // Make sure that this function is better than every other viable
4076 // function. If not, we have an ambiguity.
4077 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4078 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004079 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004080 Cand != Best &&
Douglas Gregorab7897a2008-11-19 22:57:39 +00004081 !isBetterOverloadCandidate(*Best, *Cand)) {
4082 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004083 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004084 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004085 }
Mike Stump11289f42009-09-09 15:08:12 +00004086
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004087 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004088 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004089 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004090 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004091 return OR_Deleted;
4092
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004093 // C++ [basic.def.odr]p2:
4094 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004095 // when referred to from a potentially-evaluated expression. [Note: this
4096 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004097 // (clause 13), user-defined conversions (12.3.2), allocation function for
4098 // placement new (5.3.4), as well as non-default initialization (8.5).
4099 if (Best->Function)
4100 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004101 return OR_Success;
4102}
4103
4104/// PrintOverloadCandidates - When overload resolution fails, prints
4105/// diagnostic messages containing the candidates in the candidate
4106/// set. If OnlyViable is true, only viable candidates will be printed.
Mike Stump11289f42009-09-09 15:08:12 +00004107void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004108Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004109 bool OnlyViable,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004110 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00004111 SourceLocation OpLoc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004112 OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4113 LastCand = CandidateSet.end();
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004114 bool Reported = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004115 for (; Cand != LastCand; ++Cand) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004116 if (Cand->Viable || !OnlyViable) {
4117 if (Cand->Function) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00004118 if (Cand->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004119 Cand->Function->getAttr<UnavailableAttr>()) {
Douglas Gregor171c45a2009-02-18 21:56:37 +00004120 // Deleted or "unavailable" function.
4121 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate_deleted)
4122 << Cand->Function->isDeleted();
Douglas Gregor4fb9cde8e2009-09-15 20:11:42 +00004123 } else if (FunctionTemplateDecl *FunTmpl
4124 = Cand->Function->getPrimaryTemplate()) {
4125 // Function template specialization
4126 // FIXME: Give a better reason!
4127 Diag(Cand->Function->getLocation(), diag::err_ovl_template_candidate)
4128 << getTemplateArgumentBindingsText(FunTmpl->getTemplateParameters(),
4129 *Cand->Function->getTemplateSpecializationArgs());
Douglas Gregor171c45a2009-02-18 21:56:37 +00004130 } else {
4131 // Normal function
Fariborz Jahanian21ccf062009-09-23 00:58:07 +00004132 bool errReported = false;
4133 if (!Cand->Viable && Cand->Conversions.size() > 0) {
4134 for (int i = Cand->Conversions.size()-1; i >= 0; i--) {
4135 const ImplicitConversionSequence &Conversion =
4136 Cand->Conversions[i];
4137 if ((Conversion.ConversionKind !=
4138 ImplicitConversionSequence::BadConversion) ||
4139 Conversion.ConversionFunctionSet.size() == 0)
4140 continue;
4141 Diag(Cand->Function->getLocation(),
4142 diag::err_ovl_candidate_not_viable) << (i+1);
4143 errReported = true;
4144 for (int j = Conversion.ConversionFunctionSet.size()-1;
4145 j >= 0; j--) {
4146 FunctionDecl *Func = Conversion.ConversionFunctionSet[j];
4147 Diag(Func->getLocation(), diag::err_ovl_candidate);
4148 }
4149 }
4150 }
4151 if (!errReported)
4152 Diag(Cand->Function->getLocation(), diag::err_ovl_candidate);
Douglas Gregor171c45a2009-02-18 21:56:37 +00004153 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00004154 } else if (Cand->IsSurrogate) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004155 // Desugar the type of the surrogate down to a function type,
4156 // retaining as many typedefs as possible while still showing
4157 // the function type (and, therefore, its parameter types).
4158 QualType FnType = Cand->Surrogate->getConversionType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004159 bool isLValueReference = false;
4160 bool isRValueReference = false;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004161 bool isPointer = false;
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004162 if (const LValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004163 FnType->getAs<LValueReferenceType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004164 FnType = FnTypeRef->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004165 isLValueReference = true;
4166 } else if (const RValueReferenceType *FnTypeRef =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004167 FnType->getAs<RValueReferenceType>()) {
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004168 FnType = FnTypeRef->getPointeeType();
4169 isRValueReference = true;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004170 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004171 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004172 FnType = FnTypePtr->getPointeeType();
4173 isPointer = true;
4174 }
4175 // Desugar down to a function type.
John McCall9dd450b2009-09-21 23:43:11 +00004176 FnType = QualType(FnType->getAs<FunctionType>(), 0);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004177 // Reconstruct the pointer/reference as appropriate.
4178 if (isPointer) FnType = Context.getPointerType(FnType);
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004179 if (isRValueReference) FnType = Context.getRValueReferenceType(FnType);
4180 if (isLValueReference) FnType = Context.getLValueReferenceType(FnType);
Douglas Gregor4fc308b2008-11-21 02:54:28 +00004181
Douglas Gregorab7897a2008-11-19 22:57:39 +00004182 Diag(Cand->Surrogate->getLocation(), diag::err_ovl_surrogate_cand)
Chris Lattner1e5665e2008-11-24 06:25:27 +00004183 << FnType;
Douglas Gregor66950a32009-09-30 21:46:01 +00004184 } else if (OnlyViable) {
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004185 assert(Cand->Conversions.size() <= 2 &&
Fariborz Jahanian0fe5e032009-10-09 17:09:58 +00004186 "builtin-binary-operator-not-binary");
Fariborz Jahanian956127d2009-10-16 23:25:02 +00004187 std::string TypeStr("operator");
4188 TypeStr += Opc;
4189 TypeStr += "(";
4190 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
4191 if (Cand->Conversions.size() == 1) {
4192 TypeStr += ")";
4193 Diag(OpLoc, diag::err_ovl_builtin_unary_candidate) << TypeStr;
4194 }
4195 else {
4196 TypeStr += ", ";
4197 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
4198 TypeStr += ")";
4199 Diag(OpLoc, diag::err_ovl_builtin_binary_candidate) << TypeStr;
4200 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004201 }
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004202 else if (!Cand->Viable && !Reported) {
4203 // Non-viability might be due to ambiguous user-defined conversions,
4204 // needed for built-in operators. Report them as well, but only once
4205 // as we have typically many built-in candidates.
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004206 unsigned NoOperands = Cand->Conversions.size();
4207 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
Fariborz Jahanian574de2c2009-10-12 17:51:19 +00004208 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
4209 if (ICS.ConversionKind != ImplicitConversionSequence::BadConversion ||
4210 ICS.ConversionFunctionSet.empty())
4211 continue;
4212 if (CXXConversionDecl *Func = dyn_cast<CXXConversionDecl>(
4213 Cand->Conversions[ArgIdx].ConversionFunctionSet[0])) {
4214 QualType FromTy =
4215 QualType(
4216 static_cast<Type*>(ICS.UserDefined.Before.FromTypePtr),0);
4217 Diag(OpLoc,diag::note_ambiguous_type_conversion)
4218 << FromTy << Func->getConversionType();
4219 }
4220 for (unsigned j = 0; j < ICS.ConversionFunctionSet.size(); j++) {
4221 FunctionDecl *Func =
4222 Cand->Conversions[ArgIdx].ConversionFunctionSet[j];
4223 Diag(Func->getLocation(),diag::err_ovl_candidate);
4224 }
4225 }
4226 Reported = true;
4227 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004228 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004229 }
4230}
4231
Douglas Gregorcd695e52008-11-10 20:40:00 +00004232/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
4233/// an overloaded function (C++ [over.over]), where @p From is an
4234/// expression with overloaded function type and @p ToType is the type
4235/// we're trying to resolve to. For example:
4236///
4237/// @code
4238/// int f(double);
4239/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00004240///
Douglas Gregorcd695e52008-11-10 20:40:00 +00004241/// int (*pfd)(double) = f; // selects f(double)
4242/// @endcode
4243///
4244/// This routine returns the resulting FunctionDecl if it could be
4245/// resolved, and NULL otherwise. When @p Complain is true, this
4246/// routine will emit diagnostics if there is an error.
4247FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004248Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
Douglas Gregorcd695e52008-11-10 20:40:00 +00004249 bool Complain) {
4250 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004251 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004252 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004253 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004254 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00004255 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004256 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004257 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004258 FunctionType = MemTypePtr->getPointeeType();
4259 IsMember = true;
4260 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004261
4262 // We only look at pointers or references to functions.
Douglas Gregor6b6ba8b2009-07-09 17:16:51 +00004263 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
Douglas Gregor9b146582009-07-08 20:55:45 +00004264 if (!FunctionType->isFunctionType())
Douglas Gregorcd695e52008-11-10 20:40:00 +00004265 return 0;
4266
4267 // Find the actual overloaded function declaration.
4268 OverloadedFunctionDecl *Ovl = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004269
Douglas Gregorcd695e52008-11-10 20:40:00 +00004270 // C++ [over.over]p1:
4271 // [...] [Note: any redundant set of parentheses surrounding the
4272 // overloaded function name is ignored (5.1). ]
4273 Expr *OvlExpr = From->IgnoreParens();
4274
4275 // C++ [over.over]p1:
4276 // [...] The overloaded function name can be preceded by the &
4277 // operator.
4278 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(OvlExpr)) {
4279 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
4280 OvlExpr = UnOp->getSubExpr()->IgnoreParens();
4281 }
4282
Anders Carlssonb68b0282009-10-20 22:53:47 +00004283 bool HasExplicitTemplateArgs = false;
John McCall0ad16662009-10-29 08:12:44 +00004284 const TemplateArgumentLoc *ExplicitTemplateArgs = 0;
Anders Carlssonb68b0282009-10-20 22:53:47 +00004285 unsigned NumExplicitTemplateArgs = 0;
4286
Douglas Gregorcd695e52008-11-10 20:40:00 +00004287 // Try to dig out the overloaded function.
Douglas Gregor9b146582009-07-08 20:55:45 +00004288 FunctionTemplateDecl *FunctionTemplate = 0;
4289 if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(OvlExpr)) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00004290 Ovl = dyn_cast<OverloadedFunctionDecl>(DR->getDecl());
Douglas Gregor9b146582009-07-08 20:55:45 +00004291 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(DR->getDecl());
Douglas Gregord3319842009-10-24 04:59:53 +00004292 HasExplicitTemplateArgs = DR->hasExplicitTemplateArgumentList();
4293 ExplicitTemplateArgs = DR->getTemplateArgs();
4294 NumExplicitTemplateArgs = DR->getNumTemplateArgs();
Anders Carlsson6c966c42009-10-07 22:26:29 +00004295 } else if (MemberExpr *ME = dyn_cast<MemberExpr>(OvlExpr)) {
4296 Ovl = dyn_cast<OverloadedFunctionDecl>(ME->getMemberDecl());
4297 FunctionTemplate = dyn_cast<FunctionTemplateDecl>(ME->getMemberDecl());
Douglas Gregord3319842009-10-24 04:59:53 +00004298 HasExplicitTemplateArgs = ME->hasExplicitTemplateArgumentList();
4299 ExplicitTemplateArgs = ME->getTemplateArgs();
4300 NumExplicitTemplateArgs = ME->getNumTemplateArgs();
Anders Carlssonb68b0282009-10-20 22:53:47 +00004301 } else if (TemplateIdRefExpr *TIRE = dyn_cast<TemplateIdRefExpr>(OvlExpr)) {
4302 TemplateName Name = TIRE->getTemplateName();
4303 Ovl = Name.getAsOverloadedFunctionDecl();
4304 FunctionTemplate =
4305 dyn_cast_or_null<FunctionTemplateDecl>(Name.getAsTemplateDecl());
4306
4307 HasExplicitTemplateArgs = true;
4308 ExplicitTemplateArgs = TIRE->getTemplateArgs();
4309 NumExplicitTemplateArgs = TIRE->getNumTemplateArgs();
Douglas Gregor9b146582009-07-08 20:55:45 +00004310 }
Anders Carlssonb68b0282009-10-20 22:53:47 +00004311
Mike Stump11289f42009-09-09 15:08:12 +00004312 // If there's no overloaded function declaration or function template,
Douglas Gregor9b146582009-07-08 20:55:45 +00004313 // we're done.
4314 if (!Ovl && !FunctionTemplate)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004315 return 0;
Mike Stump11289f42009-09-09 15:08:12 +00004316
Douglas Gregor9b146582009-07-08 20:55:45 +00004317 OverloadIterator Fun;
4318 if (Ovl)
4319 Fun = Ovl;
4320 else
4321 Fun = FunctionTemplate;
Mike Stump11289f42009-09-09 15:08:12 +00004322
Douglas Gregorcd695e52008-11-10 20:40:00 +00004323 // Look through all of the overloaded functions, searching for one
4324 // whose type matches exactly.
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004325 llvm::SmallPtrSet<FunctionDecl *, 4> Matches;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004326 bool FoundNonTemplateFunction = false;
Douglas Gregor9b146582009-07-08 20:55:45 +00004327 for (OverloadIterator FunEnd; Fun != FunEnd; ++Fun) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00004328 // C++ [over.over]p3:
4329 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00004330 // targets of type "pointer-to-function" or "reference-to-function."
4331 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004332 // type "pointer-to-member-function."
4333 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00004334
Mike Stump11289f42009-09-09 15:08:12 +00004335 if (FunctionTemplateDecl *FunctionTemplate
Douglas Gregor9b146582009-07-08 20:55:45 +00004336 = dyn_cast<FunctionTemplateDecl>(*Fun)) {
Mike Stump11289f42009-09-09 15:08:12 +00004337 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004338 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00004339 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004340 // static when converting to member pointer.
4341 if (Method->isStatic() == IsMember)
4342 continue;
4343 } else if (IsMember)
4344 continue;
Mike Stump11289f42009-09-09 15:08:12 +00004345
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004346 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00004347 // If the name is a function template, template argument deduction is
4348 // done (14.8.2.2), and if the argument deduction succeeds, the
4349 // resulting template argument list is used to generate a single
4350 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004351 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004352 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00004353 FunctionDecl *Specialization = 0;
4354 TemplateDeductionInfo Info(Context);
4355 if (TemplateDeductionResult Result
Anders Carlssonb68b0282009-10-20 22:53:47 +00004356 = DeduceTemplateArguments(FunctionTemplate, HasExplicitTemplateArgs,
4357 ExplicitTemplateArgs,
4358 NumExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00004359 FunctionType, Specialization, Info)) {
4360 // FIXME: make a note of the failed deduction for diagnostics.
4361 (void)Result;
4362 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00004363 // FIXME: If the match isn't exact, shouldn't we just drop this as
4364 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00004365 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00004366 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004367 Matches.insert(
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004368 cast<FunctionDecl>(Specialization->getCanonicalDecl()));
Douglas Gregor9b146582009-07-08 20:55:45 +00004369 }
4370 }
Mike Stump11289f42009-09-09 15:08:12 +00004371
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004372 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(*Fun)) {
4373 // Skip non-static functions when converting to pointer, and static
4374 // when converting to member pointer.
4375 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00004376 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00004377
4378 // If we have explicit template arguments, skip non-templates.
4379 if (HasExplicitTemplateArgs)
4380 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004381 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00004382 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00004383
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004384 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(*Fun)) {
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004385 if (FunctionType == Context.getCanonicalType(FunDecl->getType())) {
Argyrios Kyrtzidis6b7e3762009-07-18 00:34:25 +00004386 Matches.insert(cast<FunctionDecl>(Fun->getCanonicalDecl()));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004387 FoundNonTemplateFunction = true;
4388 }
Mike Stump11289f42009-09-09 15:08:12 +00004389 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00004390 }
4391
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004392 // If there were 0 or 1 matches, we're done.
4393 if (Matches.empty())
4394 return 0;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004395 else if (Matches.size() == 1) {
4396 FunctionDecl *Result = *Matches.begin();
4397 MarkDeclarationReferenced(From->getLocStart(), Result);
4398 return Result;
4399 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004400
4401 // C++ [over.over]p4:
4402 // If more than one function is selected, [...]
Douglas Gregor05155d82009-08-21 23:19:43 +00004403 typedef llvm::SmallPtrSet<FunctionDecl *, 4>::iterator MatchIter;
Douglas Gregorfae1d712009-09-26 03:56:17 +00004404 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004405 // [...] and any given function template specialization F1 is
4406 // eliminated if the set contains a second function template
4407 // specialization whose function template is more specialized
4408 // than the function template of F1 according to the partial
4409 // ordering rules of 14.5.5.2.
4410
4411 // The algorithm specified above is quadratic. We instead use a
4412 // two-pass algorithm (similar to the one used to identify the
4413 // best viable function in an overload set) that identifies the
4414 // best function template (if it exists).
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004415 llvm::SmallVector<FunctionDecl *, 8> TemplateMatches(Matches.begin(),
Douglas Gregorfae1d712009-09-26 03:56:17 +00004416 Matches.end());
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004417 FunctionDecl *Result =
4418 getMostSpecialized(TemplateMatches.data(), TemplateMatches.size(),
4419 TPOC_Other, From->getLocStart(),
4420 PDiag(),
4421 PDiag(diag::err_addr_ovl_ambiguous)
4422 << TemplateMatches[0]->getDeclName(),
4423 PDiag(diag::err_ovl_template_candidate));
4424 MarkDeclarationReferenced(From->getLocStart(), Result);
4425 return Result;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004426 }
Mike Stump11289f42009-09-09 15:08:12 +00004427
Douglas Gregorfae1d712009-09-26 03:56:17 +00004428 // [...] any function template specializations in the set are
4429 // eliminated if the set also contains a non-template function, [...]
4430 llvm::SmallVector<FunctionDecl *, 4> RemainingMatches;
4431 for (MatchIter M = Matches.begin(), MEnd = Matches.end(); M != MEnd; ++M)
4432 if ((*M)->getPrimaryTemplate() == 0)
4433 RemainingMatches.push_back(*M);
4434
Mike Stump11289f42009-09-09 15:08:12 +00004435 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004436 // selected function.
Sebastian Redldf4b80e2009-10-17 21:12:09 +00004437 if (RemainingMatches.size() == 1) {
4438 FunctionDecl *Result = RemainingMatches.front();
4439 MarkDeclarationReferenced(From->getLocStart(), Result);
4440 return Result;
4441 }
Mike Stump11289f42009-09-09 15:08:12 +00004442
Douglas Gregorb257e4f2009-07-08 23:33:52 +00004443 // FIXME: We should probably return the same thing that BestViableFunction
4444 // returns (even if we issue the diagnostics here).
4445 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
4446 << RemainingMatches[0]->getDeclName();
4447 for (unsigned I = 0, N = RemainingMatches.size(); I != N; ++I)
4448 Diag(RemainingMatches[I]->getLocation(), diag::err_ovl_candidate);
Douglas Gregorcd695e52008-11-10 20:40:00 +00004449 return 0;
4450}
4451
Douglas Gregorcabea402009-09-22 15:41:20 +00004452/// \brief Add a single candidate to the overload set.
4453static void AddOverloadedCallCandidate(Sema &S,
4454 AnyFunctionDecl Callee,
4455 bool &ArgumentDependentLookup,
4456 bool HasExplicitTemplateArgs,
John McCall0ad16662009-10-29 08:12:44 +00004457 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004458 unsigned NumExplicitTemplateArgs,
4459 Expr **Args, unsigned NumArgs,
4460 OverloadCandidateSet &CandidateSet,
4461 bool PartialOverloading) {
4462 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
4463 assert(!HasExplicitTemplateArgs && "Explicit template arguments?");
4464 S.AddOverloadCandidate(Func, Args, NumArgs, CandidateSet, false, false,
4465 PartialOverloading);
4466
4467 if (Func->getDeclContext()->isRecord() ||
4468 Func->getDeclContext()->isFunctionOrMethod())
4469 ArgumentDependentLookup = false;
4470 return;
4471 }
4472
4473 FunctionTemplateDecl *FuncTemplate = cast<FunctionTemplateDecl>(Callee);
4474 S.AddTemplateOverloadCandidate(FuncTemplate, HasExplicitTemplateArgs,
4475 ExplicitTemplateArgs,
4476 NumExplicitTemplateArgs,
4477 Args, NumArgs, CandidateSet);
4478
4479 if (FuncTemplate->getDeclContext()->isRecord())
4480 ArgumentDependentLookup = false;
4481}
4482
4483/// \brief Add the overload candidates named by callee and/or found by argument
4484/// dependent lookup to the given overload set.
4485void Sema::AddOverloadedCallCandidates(NamedDecl *Callee,
4486 DeclarationName &UnqualifiedName,
4487 bool &ArgumentDependentLookup,
4488 bool HasExplicitTemplateArgs,
John McCall0ad16662009-10-29 08:12:44 +00004489 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004490 unsigned NumExplicitTemplateArgs,
4491 Expr **Args, unsigned NumArgs,
4492 OverloadCandidateSet &CandidateSet,
4493 bool PartialOverloading) {
4494 // Add the functions denoted by Callee to the set of candidate
4495 // functions. While we're doing so, track whether argument-dependent
4496 // lookup still applies, per:
4497 //
4498 // C++0x [basic.lookup.argdep]p3:
4499 // Let X be the lookup set produced by unqualified lookup (3.4.1)
4500 // and let Y be the lookup set produced by argument dependent
4501 // lookup (defined as follows). If X contains
4502 //
4503 // -- a declaration of a class member, or
4504 //
4505 // -- a block-scope function declaration that is not a
4506 // using-declaration (FIXME: check for using declaration), or
4507 //
4508 // -- a declaration that is neither a function or a function
4509 // template
4510 //
4511 // then Y is empty.
4512 if (!Callee) {
4513 // Nothing to do.
4514 } else if (OverloadedFunctionDecl *Ovl
4515 = dyn_cast<OverloadedFunctionDecl>(Callee)) {
4516 for (OverloadedFunctionDecl::function_iterator Func = Ovl->function_begin(),
4517 FuncEnd = Ovl->function_end();
4518 Func != FuncEnd; ++Func)
4519 AddOverloadedCallCandidate(*this, *Func, ArgumentDependentLookup,
4520 HasExplicitTemplateArgs,
4521 ExplicitTemplateArgs, NumExplicitTemplateArgs,
4522 Args, NumArgs, CandidateSet,
4523 PartialOverloading);
4524 } else if (isa<FunctionDecl>(Callee) || isa<FunctionTemplateDecl>(Callee))
4525 AddOverloadedCallCandidate(*this,
4526 AnyFunctionDecl::getFromNamedDecl(Callee),
4527 ArgumentDependentLookup,
4528 HasExplicitTemplateArgs,
4529 ExplicitTemplateArgs, NumExplicitTemplateArgs,
4530 Args, NumArgs, CandidateSet,
4531 PartialOverloading);
4532 // FIXME: assert isa<FunctionDecl> || isa<FunctionTemplateDecl> rather than
4533 // checking dynamically.
4534
4535 if (Callee)
4536 UnqualifiedName = Callee->getDeclName();
4537
4538 if (ArgumentDependentLookup)
4539 AddArgumentDependentLookupCandidates(UnqualifiedName, Args, NumArgs,
4540 HasExplicitTemplateArgs,
4541 ExplicitTemplateArgs,
4542 NumExplicitTemplateArgs,
4543 CandidateSet,
4544 PartialOverloading);
4545}
4546
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004547/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00004548/// (which eventually refers to the declaration Func) and the call
4549/// arguments Args/NumArgs, attempt to resolve the function call down
4550/// to a specific function. If overload resolution succeeds, returns
4551/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00004552/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004553/// arguments and Fn, and returns NULL.
Douglas Gregore254f902009-02-04 00:32:51 +00004554FunctionDecl *Sema::ResolveOverloadedCallFn(Expr *Fn, NamedDecl *Callee,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004555 DeclarationName UnqualifiedName,
Douglas Gregor89026b52009-06-30 23:57:56 +00004556 bool HasExplicitTemplateArgs,
John McCall0ad16662009-10-29 08:12:44 +00004557 const TemplateArgumentLoc *ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004558 unsigned NumExplicitTemplateArgs,
Douglas Gregora60a6912008-11-26 06:01:48 +00004559 SourceLocation LParenLoc,
4560 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00004561 SourceLocation *CommaLocs,
Douglas Gregore254f902009-02-04 00:32:51 +00004562 SourceLocation RParenLoc,
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004563 bool &ArgumentDependentLookup) {
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004564 OverloadCandidateSet CandidateSet;
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004565
4566 // Add the functions denoted by Callee to the set of candidate
Douglas Gregorcabea402009-09-22 15:41:20 +00004567 // functions.
4568 AddOverloadedCallCandidates(Callee, UnqualifiedName, ArgumentDependentLookup,
4569 HasExplicitTemplateArgs, ExplicitTemplateArgs,
4570 NumExplicitTemplateArgs, Args, NumArgs,
4571 CandidateSet);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004572 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004573 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
Douglas Gregora60a6912008-11-26 06:01:48 +00004574 case OR_Success:
4575 return Best->Function;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004576
4577 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00004578 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004579 diag::err_ovl_no_viable_function_in_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00004580 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004581 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
4582 break;
4583
4584 case OR_Ambiguous:
4585 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
Douglas Gregorb8a9a412009-02-04 15:01:18 +00004586 << UnqualifiedName << Fn->getSourceRange();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004587 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4588 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00004589
4590 case OR_Deleted:
4591 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
4592 << Best->Function->isDeleted()
4593 << UnqualifiedName
4594 << Fn->getSourceRange();
4595 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4596 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00004597 }
4598
4599 // Overload resolution failed. Destroy all of the subexpressions and
4600 // return NULL.
4601 Fn->Destroy(Context);
4602 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
4603 Args[Arg]->Destroy(Context);
4604 return 0;
4605}
4606
Douglas Gregor084d8552009-03-13 23:49:33 +00004607/// \brief Create a unary operation that may resolve to an overloaded
4608/// operator.
4609///
4610/// \param OpLoc The location of the operator itself (e.g., '*').
4611///
4612/// \param OpcIn The UnaryOperator::Opcode that describes this
4613/// operator.
4614///
4615/// \param Functions The set of non-member functions that will be
4616/// considered by overload resolution. The caller needs to build this
4617/// set based on the context using, e.g.,
4618/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4619/// set should not contain any member functions; those will be added
4620/// by CreateOverloadedUnaryOp().
4621///
4622/// \param input The input argument.
4623Sema::OwningExprResult Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc,
4624 unsigned OpcIn,
4625 FunctionSet &Functions,
Mike Stump11289f42009-09-09 15:08:12 +00004626 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004627 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
4628 Expr *Input = (Expr *)input.get();
4629
4630 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
4631 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
4632 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4633
4634 Expr *Args[2] = { Input, 0 };
4635 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004636
Douglas Gregor084d8552009-03-13 23:49:33 +00004637 // For post-increment and post-decrement, add the implicit '0' as
4638 // the second argument, so that we know this is a post-increment or
4639 // post-decrement.
4640 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
4641 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00004642 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00004643 SourceLocation());
4644 NumArgs = 2;
4645 }
4646
4647 if (Input->isTypeDependent()) {
Mike Stump11289f42009-09-09 15:08:12 +00004648 OverloadedFunctionDecl *Overloads
Douglas Gregor084d8552009-03-13 23:49:33 +00004649 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump11289f42009-09-09 15:08:12 +00004650 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor084d8552009-03-13 23:49:33 +00004651 FuncEnd = Functions.end();
4652 Func != FuncEnd; ++Func)
4653 Overloads->addOverload(*Func);
4654
4655 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4656 OpLoc, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00004657
Douglas Gregor084d8552009-03-13 23:49:33 +00004658 input.release();
4659 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
4660 &Args[0], NumArgs,
4661 Context.DependentTy,
4662 OpLoc));
4663 }
4664
4665 // Build an empty overload set.
4666 OverloadCandidateSet CandidateSet;
4667
4668 // Add the candidates from the given function set.
4669 AddFunctionCandidates(Functions, &Args[0], NumArgs, CandidateSet, false);
4670
4671 // Add operator candidates that are member functions.
4672 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
4673
4674 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004675 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00004676
4677 // Perform overload resolution.
4678 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004679 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00004680 case OR_Success: {
4681 // We found a built-in operator or an overloaded operator.
4682 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00004683
Douglas Gregor084d8552009-03-13 23:49:33 +00004684 if (FnDecl) {
4685 // We matched an overloaded operator. Build a call to that
4686 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00004687
Douglas Gregor084d8552009-03-13 23:49:33 +00004688 // Convert the arguments.
4689 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
4690 if (PerformObjectArgumentInitialization(Input, Method))
4691 return ExprError();
4692 } else {
4693 // Convert the arguments.
4694 if (PerformCopyInitialization(Input,
4695 FnDecl->getParamDecl(0)->getType(),
4696 "passing"))
4697 return ExprError();
4698 }
4699
4700 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00004701 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00004702
Douglas Gregor084d8552009-03-13 23:49:33 +00004703 // Build the actual expression node.
4704 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
4705 SourceLocation());
4706 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00004707
Douglas Gregor084d8552009-03-13 23:49:33 +00004708 input.release();
Mike Stump11289f42009-09-09 15:08:12 +00004709
Anders Carlssonf64a3da2009-10-13 21:19:37 +00004710 ExprOwningPtr<CallExpr> TheCall(this,
4711 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4712 &Input, 1, ResultTy, OpLoc));
4713
4714 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4715 FnDecl))
4716 return ExprError();
4717
4718 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00004719 } else {
4720 // We matched a built-in operator. Convert the arguments, then
4721 // break out so that we will build the appropriate built-in
4722 // operator node.
4723 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
4724 Best->Conversions[0], "passing"))
4725 return ExprError();
4726
4727 break;
4728 }
4729 }
4730
4731 case OR_No_Viable_Function:
4732 // No viable function; fall through to handling this as a
4733 // built-in operator, which will produce an error message for us.
4734 break;
4735
4736 case OR_Ambiguous:
4737 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4738 << UnaryOperator::getOpcodeStr(Opc)
4739 << Input->getSourceRange();
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004740 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
4741 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00004742 return ExprError();
4743
4744 case OR_Deleted:
4745 Diag(OpLoc, diag::err_ovl_deleted_oper)
4746 << Best->Function->isDeleted()
4747 << UnaryOperator::getOpcodeStr(Opc)
4748 << Input->getSourceRange();
4749 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4750 return ExprError();
4751 }
4752
4753 // Either we found no viable overloaded operator or we matched a
4754 // built-in operator. In either case, fall through to trying to
4755 // build a built-in operation.
4756 input.release();
4757 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
4758}
4759
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004760/// \brief Create a binary operation that may resolve to an overloaded
4761/// operator.
4762///
4763/// \param OpLoc The location of the operator itself (e.g., '+').
4764///
4765/// \param OpcIn The BinaryOperator::Opcode that describes this
4766/// operator.
4767///
4768/// \param Functions The set of non-member functions that will be
4769/// considered by overload resolution. The caller needs to build this
4770/// set based on the context using, e.g.,
4771/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
4772/// set should not contain any member functions; those will be added
4773/// by CreateOverloadedBinOp().
4774///
4775/// \param LHS Left-hand argument.
4776/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00004777Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004778Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00004779 unsigned OpcIn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004780 FunctionSet &Functions,
4781 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004782 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00004783 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004784
4785 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
4786 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
4787 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4788
4789 // If either side is type-dependent, create an appropriate dependent
4790 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00004791 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00004792 if (Functions.empty()) {
4793 // If there are no functions to store, just build a dependent
4794 // BinaryOperator or CompoundAssignment.
4795 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
4796 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
4797 Context.DependentTy, OpLoc));
4798
4799 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
4800 Context.DependentTy,
4801 Context.DependentTy,
4802 Context.DependentTy,
4803 OpLoc));
4804 }
4805
Mike Stump11289f42009-09-09 15:08:12 +00004806 OverloadedFunctionDecl *Overloads
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004807 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
Mike Stump11289f42009-09-09 15:08:12 +00004808 for (FunctionSet::iterator Func = Functions.begin(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004809 FuncEnd = Functions.end();
4810 Func != FuncEnd; ++Func)
4811 Overloads->addOverload(*Func);
4812
4813 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4814 OpLoc, false, false);
Mike Stump11289f42009-09-09 15:08:12 +00004815
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004816 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00004817 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004818 Context.DependentTy,
4819 OpLoc));
4820 }
4821
4822 // If this is the .* operator, which is not overloadable, just
4823 // create a built-in binary operator.
4824 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00004825 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004826
4827 // If this is one of the assignment operators, we only perform
4828 // overload resolution if the left-hand side is a class or
4829 // enumeration type (C++ [expr.ass]p3).
4830 if (Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign &&
Douglas Gregore9899d92009-08-26 17:08:25 +00004831 !Args[0]->getType()->isOverloadableType())
4832 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004833
Douglas Gregor084d8552009-03-13 23:49:33 +00004834 // Build an empty overload set.
4835 OverloadCandidateSet CandidateSet;
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004836
4837 // Add the candidates from the given function set.
4838 AddFunctionCandidates(Functions, Args, 2, CandidateSet, false);
4839
4840 // Add operator candidates that are member functions.
4841 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
4842
4843 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004844 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004845
4846 // Perform overload resolution.
4847 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004848 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004849 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004850 // We found a built-in operator or an overloaded operator.
4851 FunctionDecl *FnDecl = Best->Function;
4852
4853 if (FnDecl) {
4854 // We matched an overloaded operator. Build a call to that
4855 // operator.
4856
4857 // Convert the arguments.
4858 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
Douglas Gregore9899d92009-08-26 17:08:25 +00004859 if (PerformObjectArgumentInitialization(Args[0], Method) ||
4860 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004861 "passing"))
4862 return ExprError();
4863 } else {
4864 // Convert the arguments.
Douglas Gregore9899d92009-08-26 17:08:25 +00004865 if (PerformCopyInitialization(Args[0], FnDecl->getParamDecl(0)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004866 "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004867 PerformCopyInitialization(Args[1], FnDecl->getParamDecl(1)->getType(),
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004868 "passing"))
4869 return ExprError();
4870 }
4871
4872 // Determine the result type
4873 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00004874 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004875 ResultTy = ResultTy.getNonReferenceType();
4876
4877 // Build the actual expression node.
4878 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00004879 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004880 UsualUnaryConversions(FnExpr);
4881
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00004882 ExprOwningPtr<CXXOperatorCallExpr>
4883 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
4884 Args, 2, ResultTy,
4885 OpLoc));
4886
4887 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
4888 FnDecl))
4889 return ExprError();
4890
4891 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004892 } else {
4893 // We matched a built-in operator. Convert the arguments, then
4894 // break out so that we will build the appropriate built-in
4895 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00004896 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004897 Best->Conversions[0], "passing") ||
Douglas Gregore9899d92009-08-26 17:08:25 +00004898 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004899 Best->Conversions[1], "passing"))
4900 return ExprError();
4901
4902 break;
4903 }
4904 }
4905
Douglas Gregor66950a32009-09-30 21:46:01 +00004906 case OR_No_Viable_Function: {
4907 // C++ [over.match.oper]p9:
4908 // If the operator is the operator , [...] and there are no
4909 // viable functions, then the operator is assumed to be the
4910 // built-in operator and interpreted according to clause 5.
4911 if (Opc == BinaryOperator::Comma)
4912 break;
4913
Sebastian Redl027de2a2009-05-21 11:50:50 +00004914 // For class as left operand for assignment or compound assigment operator
4915 // do not fall through to handling in built-in, but report that no overloaded
4916 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00004917 OwningExprResult Result = ExprError();
4918 if (Args[0]->getType()->isRecordType() &&
4919 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00004920 Diag(OpLoc, diag::err_ovl_no_viable_oper)
4921 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004922 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00004923 } else {
4924 // No viable function; try to create a built-in operation, which will
4925 // produce an error. Then, show the non-viable candidates.
4926 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00004927 }
Douglas Gregor66950a32009-09-30 21:46:01 +00004928 assert(Result.isInvalid() &&
4929 "C++ binary operator overloading is missing candidates!");
4930 if (Result.isInvalid())
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004931 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
4932 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00004933 return move(Result);
4934 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004935
4936 case OR_Ambiguous:
4937 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
4938 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004939 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Fariborz Jahaniane7196432009-10-12 20:11:40 +00004940 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
4941 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004942 return ExprError();
4943
4944 case OR_Deleted:
4945 Diag(OpLoc, diag::err_ovl_deleted_oper)
4946 << Best->Function->isDeleted()
4947 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00004948 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004949 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
4950 return ExprError();
4951 }
4952
Douglas Gregor66950a32009-09-30 21:46:01 +00004953 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00004954 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004955}
4956
Sebastian Redladba46e2009-10-29 20:17:01 +00004957Action::OwningExprResult
4958Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
4959 SourceLocation RLoc,
4960 ExprArg Base, ExprArg Idx) {
4961 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
4962 static_cast<Expr*>(Idx.get()) };
4963 DeclarationName OpName =
4964 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
4965
4966 // If either side is type-dependent, create an appropriate dependent
4967 // expression.
4968 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
4969
4970 OverloadedFunctionDecl *Overloads
4971 = OverloadedFunctionDecl::Create(Context, CurContext, OpName);
4972
4973 DeclRefExpr *Fn = new (Context) DeclRefExpr(Overloads, Context.OverloadTy,
4974 LLoc, false, false);
4975
4976 Base.release();
4977 Idx.release();
4978 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
4979 Args, 2,
4980 Context.DependentTy,
4981 RLoc));
4982 }
4983
4984 // Build an empty overload set.
4985 OverloadCandidateSet CandidateSet;
4986
4987 // Subscript can only be overloaded as a member function.
4988
4989 // Add operator candidates that are member functions.
4990 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
4991
4992 // Add builtin operator candidates.
4993 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
4994
4995 // Perform overload resolution.
4996 OverloadCandidateSet::iterator Best;
4997 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
4998 case OR_Success: {
4999 // We found a built-in operator or an overloaded operator.
5000 FunctionDecl *FnDecl = Best->Function;
5001
5002 if (FnDecl) {
5003 // We matched an overloaded operator. Build a call to that
5004 // operator.
5005
5006 // Convert the arguments.
5007 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
5008 if (PerformObjectArgumentInitialization(Args[0], Method) ||
5009 PerformCopyInitialization(Args[1],
5010 FnDecl->getParamDecl(0)->getType(),
5011 "passing"))
5012 return ExprError();
5013
5014 // Determine the result type
5015 QualType ResultTy
5016 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
5017 ResultTy = ResultTy.getNonReferenceType();
5018
5019 // Build the actual expression node.
5020 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
5021 LLoc);
5022 UsualUnaryConversions(FnExpr);
5023
5024 Base.release();
5025 Idx.release();
5026 ExprOwningPtr<CXXOperatorCallExpr>
5027 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
5028 FnExpr, Args, 2,
5029 ResultTy, RLoc));
5030
5031 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
5032 FnDecl))
5033 return ExprError();
5034
5035 return MaybeBindToTemporary(TheCall.release());
5036 } else {
5037 // We matched a built-in operator. Convert the arguments, then
5038 // break out so that we will build the appropriate built-in
5039 // operator node.
5040 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
5041 Best->Conversions[0], "passing") ||
5042 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
5043 Best->Conversions[1], "passing"))
5044 return ExprError();
5045
5046 break;
5047 }
5048 }
5049
5050 case OR_No_Viable_Function: {
5051 // No viable function; try to create a built-in operation, which will
5052 // produce an error. Then, show the non-viable candidates.
5053 OwningExprResult Result =
5054 CreateBuiltinArraySubscriptExpr(move(Base), LLoc, move(Idx), RLoc);
5055 assert(Result.isInvalid() &&
5056 "C++ subscript operator overloading is missing candidates!");
5057 if (Result.isInvalid())
5058 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false,
5059 "[]", LLoc);
5060 return move(Result);
5061 }
5062
5063 case OR_Ambiguous:
5064 Diag(LLoc, diag::err_ovl_ambiguous_oper)
5065 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5066 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true,
5067 "[]", LLoc);
5068 return ExprError();
5069
5070 case OR_Deleted:
5071 Diag(LLoc, diag::err_ovl_deleted_oper)
5072 << Best->Function->isDeleted() << "[]"
5073 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
5074 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5075 return ExprError();
5076 }
5077
5078 // We matched a built-in operator; build it.
5079 Base.release();
5080 Idx.release();
5081 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
5082 Owned(Args[1]), RLoc);
5083}
5084
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005085/// BuildCallToMemberFunction - Build a call to a member
5086/// function. MemExpr is the expression that refers to the member
5087/// function (and includes the object parameter), Args/NumArgs are the
5088/// arguments to the function call (not including the object
5089/// parameter). The caller needs to validate that the member
5090/// expression refers to a member function or an overloaded member
5091/// function.
5092Sema::ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00005093Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
5094 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005095 unsigned NumArgs, SourceLocation *CommaLocs,
5096 SourceLocation RParenLoc) {
5097 // Dig out the member expression. This holds both the object
5098 // argument and the member function we're referring to.
5099 MemberExpr *MemExpr = 0;
5100 if (ParenExpr *ParenE = dyn_cast<ParenExpr>(MemExprE))
5101 MemExpr = dyn_cast<MemberExpr>(ParenE->getSubExpr());
5102 else
5103 MemExpr = dyn_cast<MemberExpr>(MemExprE);
5104 assert(MemExpr && "Building member call without member expression");
5105
5106 // Extract the object argument.
5107 Expr *ObjectArg = MemExpr->getBase();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00005108
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005109 CXXMethodDecl *Method = 0;
Douglas Gregor97628d62009-08-21 00:16:32 +00005110 if (isa<OverloadedFunctionDecl>(MemExpr->getMemberDecl()) ||
5111 isa<FunctionTemplateDecl>(MemExpr->getMemberDecl())) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005112 // Add overload candidates
5113 OverloadCandidateSet CandidateSet;
Douglas Gregor97628d62009-08-21 00:16:32 +00005114 DeclarationName DeclName = MemExpr->getMemberDecl()->getDeclName();
Mike Stump11289f42009-09-09 15:08:12 +00005115
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005116 for (OverloadIterator Func(MemExpr->getMemberDecl()), FuncEnd;
5117 Func != FuncEnd; ++Func) {
Douglas Gregord3319842009-10-24 04:59:53 +00005118 if ((Method = dyn_cast<CXXMethodDecl>(*Func))) {
5119 // If explicit template arguments were provided, we can't call a
5120 // non-template member function.
5121 if (MemExpr->hasExplicitTemplateArgumentList())
5122 continue;
5123
Mike Stump11289f42009-09-09 15:08:12 +00005124 AddMethodCandidate(Method, ObjectArg, Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005125 /*SuppressUserConversions=*/false);
Douglas Gregord3319842009-10-24 04:59:53 +00005126 } else
Douglas Gregor84f14dd2009-09-01 00:37:14 +00005127 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(*Func),
5128 MemExpr->hasExplicitTemplateArgumentList(),
5129 MemExpr->getTemplateArgs(),
5130 MemExpr->getNumTemplateArgs(),
5131 ObjectArg, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00005132 CandidateSet,
5133 /*SuppressUsedConversions=*/false);
5134 }
Mike Stump11289f42009-09-09 15:08:12 +00005135
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005136 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005137 switch (BestViableFunction(CandidateSet, MemExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005138 case OR_Success:
5139 Method = cast<CXXMethodDecl>(Best->Function);
5140 break;
5141
5142 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00005143 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005144 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005145 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005146 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5147 // FIXME: Leaking incoming expressions!
5148 return true;
5149
5150 case OR_Ambiguous:
Mike Stump11289f42009-09-09 15:08:12 +00005151 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005152 diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00005153 << DeclName << MemExprE->getSourceRange();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005154 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5155 // FIXME: Leaking incoming expressions!
5156 return true;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005157
5158 case OR_Deleted:
Mike Stump11289f42009-09-09 15:08:12 +00005159 Diag(MemExpr->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +00005160 diag::err_ovl_deleted_member_call)
5161 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00005162 << DeclName << MemExprE->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005163 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
5164 // FIXME: Leaking incoming expressions!
5165 return true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005166 }
5167
5168 FixOverloadedFunctionReference(MemExpr, Method);
5169 } else {
5170 Method = dyn_cast<CXXMethodDecl>(MemExpr->getMemberDecl());
5171 }
5172
5173 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00005174 ExprOwningPtr<CXXMemberCallExpr>
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005175 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExpr, Args,
Mike Stump11289f42009-09-09 15:08:12 +00005176 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005177 Method->getResultType().getNonReferenceType(),
5178 RParenLoc));
5179
Anders Carlssonc4859ba2009-10-10 00:06:20 +00005180 // Check for a valid return type.
5181 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
5182 TheCall.get(), Method))
5183 return true;
5184
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005185 // Convert the object argument (for a non-static member function call).
Mike Stump11289f42009-09-09 15:08:12 +00005186 if (!Method->isStatic() &&
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005187 PerformObjectArgumentInitialization(ObjectArg, Method))
5188 return true;
5189 MemExpr->setBase(ObjectArg);
5190
5191 // Convert the rest of the arguments
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005192 const FunctionProtoType *Proto = cast<FunctionProtoType>(Method->getType());
Mike Stump11289f42009-09-09 15:08:12 +00005193 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005194 RParenLoc))
5195 return true;
5196
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005197 if (CheckFunctionCall(Method, TheCall.get()))
5198 return true;
Anders Carlsson8c84c202009-08-16 03:42:12 +00005199
5200 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005201}
5202
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005203/// BuildCallToObjectOfClassType - Build a call to an object of class
5204/// type (C++ [over.call.object]), which can end up invoking an
5205/// overloaded function call operator (@c operator()) or performing a
5206/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00005207Sema::ExprResult
5208Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00005209 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005210 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00005211 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005212 SourceLocation RParenLoc) {
5213 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005214 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00005215
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005216 // C++ [over.call.object]p1:
5217 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00005218 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005219 // candidate functions includes at least the function call
5220 // operators of T. The function call operators of T are obtained by
5221 // ordinary lookup of the name operator() in the context of
5222 // (E).operator().
5223 OverloadCandidateSet CandidateSet;
Douglas Gregor91f84212008-12-11 16:49:14 +00005224 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor55297ac2008-12-23 00:26:44 +00005225 DeclContext::lookup_const_iterator Oper, OperEnd;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00005226 for (llvm::tie(Oper, OperEnd) = Record->getDecl()->lookup(OpName);
Douglas Gregor55297ac2008-12-23 00:26:44 +00005227 Oper != OperEnd; ++Oper)
Mike Stump11289f42009-09-09 15:08:12 +00005228 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Object, Args, NumArgs,
Douglas Gregor55297ac2008-12-23 00:26:44 +00005229 CandidateSet, /*SuppressUserConversions=*/false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005230
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005231 if (RequireCompleteType(LParenLoc, Object->getType(),
5232 PartialDiagnostic(diag::err_incomplete_object_call)
5233 << Object->getSourceRange()))
5234 return true;
5235
Douglas Gregorab7897a2008-11-19 22:57:39 +00005236 // C++ [over.call.object]p2:
5237 // In addition, for each conversion function declared in T of the
5238 // form
5239 //
5240 // operator conversion-type-id () cv-qualifier;
5241 //
5242 // where cv-qualifier is the same cv-qualification as, or a
5243 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00005244 // denotes the type "pointer to function of (P1,...,Pn) returning
5245 // R", or the type "reference to pointer to function of
5246 // (P1,...,Pn) returning R", or the type "reference to function
5247 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00005248 // is also considered as a candidate function. Similarly,
5249 // surrogate call functions are added to the set of candidate
5250 // functions for each conversion function declared in an
5251 // accessible base class provided the function is not hidden
5252 // within T by another intervening declaration.
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005253 // FIXME: Look in base classes for more conversion operators!
5254 OverloadedFunctionDecl *Conversions
5255 = cast<CXXRecordDecl>(Record->getDecl())->getConversionFunctions();
5256 for (OverloadedFunctionDecl::function_iterator
5257 Func = Conversions->function_begin(),
5258 FuncEnd = Conversions->function_end();
5259 Func != FuncEnd; ++Func) {
5260 CXXConversionDecl *Conv;
5261 FunctionTemplateDecl *ConvTemplate;
5262 GetFunctionAndTemplate(*Func, Conv, ConvTemplate);
Mike Stump11289f42009-09-09 15:08:12 +00005263
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005264 // Skip over templated conversion functions; they aren't
5265 // surrogates.
5266 if (ConvTemplate)
5267 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005268
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005269 // Strip the reference type (if any) and then the pointer type (if
5270 // any) to get down to what might be a function type.
5271 QualType ConvType = Conv->getConversionType().getNonReferenceType();
5272 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5273 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005274
Douglas Gregor74ba25c2009-10-21 06:18:39 +00005275 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
5276 AddSurrogateCandidate(Conv, Proto, Object, Args, NumArgs, CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00005277 }
Mike Stump11289f42009-09-09 15:08:12 +00005278
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005279 // Perform overload resolution.
5280 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005281 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005282 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00005283 // Overload resolution succeeded; we'll build the appropriate call
5284 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005285 break;
5286
5287 case OR_No_Viable_Function:
Mike Stump11289f42009-09-09 15:08:12 +00005288 Diag(Object->getSourceRange().getBegin(),
Sebastian Redl15b02d22008-11-22 13:44:36 +00005289 diag::err_ovl_no_viable_object_call)
Chris Lattner45d9d602009-02-17 07:29:20 +00005290 << Object->getType() << Object->getSourceRange();
Sebastian Redl15b02d22008-11-22 13:44:36 +00005291 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005292 break;
5293
5294 case OR_Ambiguous:
5295 Diag(Object->getSourceRange().getBegin(),
5296 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00005297 << Object->getType() << Object->getSourceRange();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005298 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5299 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00005300
5301 case OR_Deleted:
5302 Diag(Object->getSourceRange().getBegin(),
5303 diag::err_ovl_deleted_object_call)
5304 << Best->Function->isDeleted()
5305 << Object->getType() << Object->getSourceRange();
5306 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
5307 break;
Mike Stump11289f42009-09-09 15:08:12 +00005308 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005309
Douglas Gregorab7897a2008-11-19 22:57:39 +00005310 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005311 // We had an error; delete all of the subexpressions and return
5312 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00005313 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005314 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00005315 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005316 return true;
5317 }
5318
Douglas Gregorab7897a2008-11-19 22:57:39 +00005319 if (Best->Function == 0) {
5320 // Since there is no function declaration, this is one of the
5321 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00005322 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00005323 = cast<CXXConversionDecl>(
5324 Best->Conversions[0].UserDefined.ConversionFunction);
5325
5326 // We selected one of the surrogate functions that converts the
5327 // object parameter to a function pointer. Perform the conversion
5328 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005329
5330 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005331 // and then call it.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005332 CXXMemberCallExpr *CE =
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00005333 BuildCXXMemberCallExpr(Object, Conv);
5334
Fariborz Jahanian774cf792009-09-28 18:35:46 +00005335 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00005336 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
5337 CommaLocs, RParenLoc).release();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005338 }
5339
5340 // We found an overloaded operator(). Build a CXXOperatorCallExpr
5341 // that calls this method, using Object for the implicit object
5342 // parameter and passing along the remaining arguments.
5343 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00005344 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005345
5346 unsigned NumArgsInProto = Proto->getNumArgs();
5347 unsigned NumArgsToCheck = NumArgs;
5348
5349 // Build the full argument list for the method call (the
5350 // implicit object parameter is placed at the beginning of the
5351 // list).
5352 Expr **MethodArgs;
5353 if (NumArgs < NumArgsInProto) {
5354 NumArgsToCheck = NumArgsInProto;
5355 MethodArgs = new Expr*[NumArgsInProto + 1];
5356 } else {
5357 MethodArgs = new Expr*[NumArgs + 1];
5358 }
5359 MethodArgs[0] = Object;
5360 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5361 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00005362
5363 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00005364 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005365 UsualUnaryConversions(NewFn);
5366
5367 // Once we've built TheCall, all of the expressions are properly
5368 // owned.
5369 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00005370 ExprOwningPtr<CXXOperatorCallExpr>
5371 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005372 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00005373 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005374 delete [] MethodArgs;
5375
Anders Carlsson3d5829c2009-10-13 21:49:31 +00005376 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
5377 Method))
5378 return true;
5379
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005380 // We may have default arguments. If so, we need to allocate more
5381 // slots in the call for them.
5382 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00005383 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005384 else if (NumArgs > NumArgsInProto)
5385 NumArgsToCheck = NumArgsInProto;
5386
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005387 bool IsError = false;
5388
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005389 // Initialize the implicit object parameter.
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005390 IsError |= PerformObjectArgumentInitialization(Object, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005391 TheCall->setArg(0, Object);
5392
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005393
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005394 // Check the argument types.
5395 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005396 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005397 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005398 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00005399
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005400 // Pass the argument.
5401 QualType ProtoArgType = Proto->getArgType(i);
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005402 IsError |= PerformCopyInitialization(Arg, ProtoArgType, "passing");
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005403 } else {
Anders Carlssone8271232009-08-14 18:30:22 +00005404 Arg = CXXDefaultArgExpr::Create(Context, Method->getParamDecl(i));
Douglas Gregor02a0acd2009-01-13 05:10:00 +00005405 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005406
5407 TheCall->setArg(i + 1, Arg);
5408 }
5409
5410 // If this is a variadic call, handle args passed through "...".
5411 if (Proto->isVariadic()) {
5412 // Promote the arguments (C99 6.5.2.2p7).
5413 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
5414 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005415 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005416 TheCall->setArg(i + 1, Arg);
5417 }
5418 }
5419
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00005420 if (IsError) return true;
5421
Anders Carlssonbc4c1072009-08-16 01:56:34 +00005422 if (CheckFunctionCall(Method, TheCall.get()))
5423 return true;
5424
Anders Carlsson1c83deb2009-08-16 03:53:54 +00005425 return MaybeBindToTemporary(TheCall.release()).release();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00005426}
5427
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005428/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00005429/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005430/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00005431Sema::OwningExprResult
5432Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
5433 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005434 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00005435
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005436 // C++ [over.ref]p1:
5437 //
5438 // [...] An expression x->m is interpreted as (x.operator->())->m
5439 // for a class object x of type T if T::operator->() exists and if
5440 // the operator is selected as the best match function by the
5441 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005442 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
5443 OverloadCandidateSet CandidateSet;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005444 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00005445
John McCall9f3059a2009-10-09 21:13:30 +00005446 LookupResult R;
5447 LookupQualifiedName(R, BaseRecord->getDecl(), OpName, LookupOrdinaryName);
Anders Carlsson78b54932009-09-10 23:18:36 +00005448
5449 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
5450 Oper != OperEnd; ++Oper)
Douglas Gregor55297ac2008-12-23 00:26:44 +00005451 AddMethodCandidate(cast<CXXMethodDecl>(*Oper), Base, 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005452 /*SuppressUserConversions=*/false);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005453
5454 // Perform overload resolution.
5455 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005456 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005457 case OR_Success:
5458 // Overload resolution succeeded; we'll build the call below.
5459 break;
5460
5461 case OR_No_Viable_Function:
5462 if (CandidateSet.empty())
5463 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00005464 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005465 else
5466 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00005467 << "operator->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005468 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/false);
Douglas Gregord8061562009-08-06 03:17:00 +00005469 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005470
5471 case OR_Ambiguous:
5472 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00005473 << "->" << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005474 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005475 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005476
5477 case OR_Deleted:
5478 Diag(OpLoc, diag::err_ovl_deleted_oper)
5479 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00005480 << "->" << Base->getSourceRange();
Douglas Gregor171c45a2009-02-18 21:56:37 +00005481 PrintOverloadCandidates(CandidateSet, /*OnlyViable=*/true);
Douglas Gregord8061562009-08-06 03:17:00 +00005482 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005483 }
5484
5485 // Convert the object parameter.
5486 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Douglas Gregor9ecea262008-11-21 03:04:22 +00005487 if (PerformObjectArgumentInitialization(Base, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00005488 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00005489
5490 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00005491 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005492
5493 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00005494 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
5495 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005496 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00005497
5498 QualType ResultTy = Method->getResultType().getNonReferenceType();
5499 ExprOwningPtr<CXXOperatorCallExpr>
5500 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
5501 &Base, 1, ResultTy, OpLoc));
5502
5503 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
5504 Method))
5505 return ExprError();
5506 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00005507}
5508
Douglas Gregorcd695e52008-11-10 20:40:00 +00005509/// FixOverloadedFunctionReference - E is an expression that refers to
5510/// a C++ overloaded function (possibly with some parentheses and
5511/// perhaps a '&' around it). We have resolved the overloaded function
5512/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005513/// refer (possibly indirectly) to Fn. Returns the new expr.
5514Expr *Sema::FixOverloadedFunctionReference(Expr *E, FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005515 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005516 Expr *NewExpr = FixOverloadedFunctionReference(PE->getSubExpr(), Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00005517 PE->setSubExpr(NewExpr);
5518 PE->setType(NewExpr->getType());
5519 } else if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
5520 Expr *NewExpr = FixOverloadedFunctionReference(ICE->getSubExpr(), Fn);
5521 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
5522 NewExpr->getType()) &&
5523 "Implicit cast type cannot be determined from overload");
5524 ICE->setSubExpr(NewExpr);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005525 } else if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00005526 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00005527 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005528 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
5529 if (Method->isStatic()) {
5530 // Do nothing: static member functions aren't any different
5531 // from non-member functions.
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005532 } else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(UnOp->getSubExpr())) {
5533 if (DRE->getQualifier()) {
5534 // We have taken the address of a pointer to member
5535 // function. Perform the computation here so that we get the
5536 // appropriate pointer to member type.
5537 DRE->setDecl(Fn);
5538 DRE->setType(Fn->getType());
5539 QualType ClassType
5540 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
5541 E->setType(Context.getMemberPointerType(Fn->getType(),
5542 ClassType.getTypePtr()));
5543 return E;
5544 }
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005545 }
Douglas Gregor6a573fe2009-10-22 18:02:20 +00005546 // FIXME: TemplateIdRefExpr referring to a member function template
5547 // specialization!
Douglas Gregor6f233ef2009-02-11 01:18:59 +00005548 }
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005549 Expr *NewExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(), Fn);
5550 UnOp->setSubExpr(NewExpr);
5551 UnOp->setType(Context.getPointerType(NewExpr->getType()));
5552
5553 return UnOp;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005554 } else if (DeclRefExpr *DR = dyn_cast<DeclRefExpr>(E)) {
Douglas Gregor9b146582009-07-08 20:55:45 +00005555 assert((isa<OverloadedFunctionDecl>(DR->getDecl()) ||
Douglas Gregor091f0422009-10-23 22:18:25 +00005556 isa<FunctionTemplateDecl>(DR->getDecl()) ||
5557 isa<FunctionDecl>(DR->getDecl())) &&
5558 "Expected function or function template");
Douglas Gregorcd695e52008-11-10 20:40:00 +00005559 DR->setDecl(Fn);
5560 E->setType(Fn->getType());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005561 } else if (MemberExpr *MemExpr = dyn_cast<MemberExpr>(E)) {
5562 MemExpr->setMemberDecl(Fn);
5563 E->setType(Fn->getType());
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005564 } else if (TemplateIdRefExpr *TID = dyn_cast<TemplateIdRefExpr>(E)) {
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005565 E = DeclRefExpr::Create(Context,
5566 TID->getQualifier(), TID->getQualifierRange(),
5567 Fn, TID->getTemplateNameLoc(),
5568 true,
5569 TID->getLAngleLoc(),
5570 TID->getTemplateArgs(),
5571 TID->getNumTemplateArgs(),
5572 TID->getRAngleLoc(),
5573 Fn->getType(),
5574 /*FIXME?*/false, /*FIXME?*/false);
Douglas Gregor6a573fe2009-10-22 18:02:20 +00005575
Douglas Gregor4bd90e52009-10-23 18:54:35 +00005576 // FIXME: Don't destroy TID here, since we need its template arguments
5577 // to survive.
5578 // TID->Destroy(Context);
Douglas Gregor091f0422009-10-23 22:18:25 +00005579 } else if (isa<UnresolvedFunctionNameExpr>(E)) {
5580 return DeclRefExpr::Create(Context,
5581 /*Qualifier=*/0,
5582 /*QualifierRange=*/SourceRange(),
5583 Fn, E->getLocStart(),
5584 Fn->getType(), false, false);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005585 } else {
5586 assert(false && "Invalid reference to overloaded function");
5587 }
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00005588
5589 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005590}
5591
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005592} // end namespace clang