blob: 04495e5ca4c7e2239b0f3fd82ec9d2721ee46e79 [file] [log] [blame]
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
John McCall7d384dd2009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor4c2458a2009-12-22 21:44:34 +000016#include "SemaInit.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000017#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000018#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000019#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000021#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000023#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000025#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000027#include <algorithm>
28
29namespace clang {
30
31/// GetConversionCategory - Retrieve the implicit conversion
32/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000033ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000034GetConversionCategory(ImplicitConversionKind Kind) {
35 static const ImplicitConversionCategory
36 Category[(int)ICK_Num_Conversion_Kinds] = {
37 ICC_Identity,
38 ICC_Lvalue_Transformation,
39 ICC_Lvalue_Transformation,
40 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +000041 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000042 ICC_Qualification_Adjustment,
43 ICC_Promotion,
44 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000045 ICC_Promotion,
46 ICC_Conversion,
47 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000048 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000053 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000054 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000055 ICC_Conversion
56 };
57 return Category[(int)Kind];
58}
59
60/// GetConversionRank - Retrieve the implicit conversion rank
61/// corresponding to the given implicit conversion kind.
62ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
63 static const ImplicitConversionRank
64 Rank[(int)ICK_Num_Conversion_Kinds] = {
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +000070 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000071 ICR_Promotion,
72 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000073 ICR_Promotion,
74 ICR_Conversion,
75 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000076 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
79 ICR_Conversion,
80 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000081 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000082 ICR_Conversion,
Chandler Carruth23a370f2010-02-25 07:20:54 +000083 ICR_Complex_Real_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000084 };
85 return Rank[(int)Kind];
86}
87
88/// GetImplicitConversionName - Return the name of this kind of
89/// implicit conversion.
90const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +000091 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000092 "No conversion",
93 "Lvalue-to-rvalue",
94 "Array-to-pointer",
95 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +000096 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000097 "Qualification",
98 "Integral promotion",
99 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000100 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000101 "Integral conversion",
102 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000103 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000104 "Floating-integral conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000105 "Complex-real conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000106 "Pointer conversion",
107 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000108 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000109 "Compatible-types conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000110 "Derived-to-base conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000111 };
112 return Name[Kind];
113}
114
Douglas Gregor60d62c22008-10-31 16:23:19 +0000115/// StandardConversionSequence - Set the standard conversion
116/// sequence to the identity conversion.
117void StandardConversionSequence::setAsIdentityConversion() {
118 First = ICK_Identity;
119 Second = ICK_Identity;
120 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000121 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000122 ReferenceBinding = false;
123 DirectBinding = false;
Sebastian Redl85002392009-03-29 22:46:24 +0000124 RRefBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000125 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000126}
127
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000128/// getRank - Retrieve the rank of this standard conversion sequence
129/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
130/// implicit conversions.
131ImplicitConversionRank StandardConversionSequence::getRank() const {
132 ImplicitConversionRank Rank = ICR_Exact_Match;
133 if (GetConversionRank(First) > Rank)
134 Rank = GetConversionRank(First);
135 if (GetConversionRank(Second) > Rank)
136 Rank = GetConversionRank(Second);
137 if (GetConversionRank(Third) > Rank)
138 Rank = GetConversionRank(Third);
139 return Rank;
140}
141
142/// isPointerConversionToBool - Determines whether this conversion is
143/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000144/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000145/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000146bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000147 // Note that FromType has not necessarily been transformed by the
148 // array-to-pointer or function-to-pointer implicit conversions, so
149 // check for their presence as well as checking whether FromType is
150 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000151 if (getToType(1)->isBooleanType() &&
John McCall1d318332010-01-12 00:44:57 +0000152 (getFromType()->isPointerType() || getFromType()->isBlockPointerType() ||
Douglas Gregor8e9bebd2008-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 Gregorbc0805a2008-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 Stump1eb44332009-09-09 15:08:12 +0000163bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000164StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000165isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000166 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000167 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000168
169 // Note that FromType has not necessarily been transformed by the
170 // array-to-pointer implicit conversion, so check for its presence
171 // and redo the conversion to get a pointer.
172 if (First == ICK_Array_To_Pointer)
173 FromType = Context.getArrayDecayedType(FromType);
174
Douglas Gregor01919692009-12-13 21:37:05 +0000175 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000176 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000182/// DebugPrint - Print this standard conversion sequence to standard
183/// error. Useful for debugging overloading issues.
184void StandardConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000185 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000186 bool PrintedSomething = false;
187 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000188 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000189 PrintedSomething = true;
190 }
191
192 if (Second != ICK_Identity) {
193 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000194 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000195 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000196 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000197
198 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000199 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000200 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000201 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000202 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000203 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000204 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000205 PrintedSomething = true;
206 }
207
208 if (Third != ICK_Identity) {
209 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000210 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000211 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000212 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000213 PrintedSomething = true;
214 }
215
216 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000217 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000218 }
219}
220
221/// DebugPrint - Print this user-defined conversion sequence to standard
222/// error. Useful for debugging overloading issues.
223void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000224 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000225 if (Before.First || Before.Second || Before.Third) {
226 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000227 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000228 }
Benjamin Kramer900fc632010-04-17 09:33:03 +0000229 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000230 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000231 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000232 After.DebugPrint();
233 }
234}
235
236/// DebugPrint - Print this implicit conversion sequence to standard
237/// error. Useful for debugging overloading issues.
238void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000239 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000240 switch (ConversionKind) {
241 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000242 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000243 Standard.DebugPrint();
244 break;
245 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000246 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000247 UserDefined.DebugPrint();
248 break;
249 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000250 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000251 break;
John McCall1d318332010-01-12 00:44:57 +0000252 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000253 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000254 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000255 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000256 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000257 break;
258 }
259
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000260 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000261}
262
John McCall1d318332010-01-12 00:44:57 +0000263void AmbiguousConversionSequence::construct() {
264 new (&conversions()) ConversionSet();
265}
266
267void AmbiguousConversionSequence::destruct() {
268 conversions().~ConversionSet();
269}
270
271void
272AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
273 FromTypePtr = O.FromTypePtr;
274 ToTypePtr = O.ToTypePtr;
275 new (&conversions()) ConversionSet(O.conversions());
276}
277
Douglas Gregora9333192010-05-08 17:41:32 +0000278namespace {
279 // Structure used by OverloadCandidate::DeductionFailureInfo to store
280 // template parameter and template argument information.
281 struct DFIParamWithArguments {
282 TemplateParameter Param;
283 TemplateArgument FirstArg;
284 TemplateArgument SecondArg;
285 };
286}
287
288/// \brief Convert from Sema's representation of template deduction information
289/// to the form used in overload-candidate information.
290OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000291static MakeDeductionFailureInfo(ASTContext &Context,
292 Sema::TemplateDeductionResult TDK,
Douglas Gregorec20f462010-05-08 20:07:26 +0000293 Sema::TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000294 OverloadCandidate::DeductionFailureInfo Result;
295 Result.Result = static_cast<unsigned>(TDK);
296 Result.Data = 0;
297 switch (TDK) {
298 case Sema::TDK_Success:
299 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000300 case Sema::TDK_TooManyArguments:
301 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000302 break;
303
304 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000305 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000306 Result.Data = Info.Param.getOpaqueValue();
307 break;
308
Douglas Gregora9333192010-05-08 17:41:32 +0000309 case Sema::TDK_Inconsistent:
310 case Sema::TDK_InconsistentQuals: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000311 // FIXME: Should allocate from normal heap so that we can free this later.
312 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000313 Saved->Param = Info.Param;
314 Saved->FirstArg = Info.FirstArg;
315 Saved->SecondArg = Info.SecondArg;
316 Result.Data = Saved;
317 break;
318 }
319
320 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000321 Result.Data = Info.take();
322 break;
323
Douglas Gregora9333192010-05-08 17:41:32 +0000324 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000325 case Sema::TDK_FailedOverloadResolution:
326 break;
327 }
328
329 return Result;
330}
John McCall1d318332010-01-12 00:44:57 +0000331
Douglas Gregora9333192010-05-08 17:41:32 +0000332void OverloadCandidate::DeductionFailureInfo::Destroy() {
333 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
334 case Sema::TDK_Success:
335 case Sema::TDK_InstantiationDepth:
336 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000337 case Sema::TDK_TooManyArguments:
338 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000339 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000340 break;
341
Douglas Gregora9333192010-05-08 17:41:32 +0000342 case Sema::TDK_Inconsistent:
343 case Sema::TDK_InconsistentQuals:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000344 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000345 Data = 0;
346 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000347
348 case Sema::TDK_SubstitutionFailure:
349 // FIXME: Destroy the template arugment list?
350 Data = 0;
351 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000352
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000353 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000354 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000355 case Sema::TDK_FailedOverloadResolution:
356 break;
357 }
358}
359
360TemplateParameter
361OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
362 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
363 case Sema::TDK_Success:
364 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000365 case Sema::TDK_TooManyArguments:
366 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000367 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000368 return TemplateParameter();
369
370 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000371 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000372 return TemplateParameter::getFromOpaqueValue(Data);
373
374 case Sema::TDK_Inconsistent:
375 case Sema::TDK_InconsistentQuals:
376 return static_cast<DFIParamWithArguments*>(Data)->Param;
377
378 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000379 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000380 case Sema::TDK_FailedOverloadResolution:
381 break;
382 }
383
384 return TemplateParameter();
385}
Douglas Gregorec20f462010-05-08 20:07:26 +0000386
387TemplateArgumentList *
388OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
389 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
390 case Sema::TDK_Success:
391 case Sema::TDK_InstantiationDepth:
392 case Sema::TDK_TooManyArguments:
393 case Sema::TDK_TooFewArguments:
394 case Sema::TDK_Incomplete:
395 case Sema::TDK_InvalidExplicitArguments:
396 case Sema::TDK_Inconsistent:
397 case Sema::TDK_InconsistentQuals:
398 return 0;
399
400 case Sema::TDK_SubstitutionFailure:
401 return static_cast<TemplateArgumentList*>(Data);
402
403 // Unhandled
404 case Sema::TDK_NonDeducedMismatch:
405 case Sema::TDK_FailedOverloadResolution:
406 break;
407 }
408
409 return 0;
410}
411
Douglas Gregora9333192010-05-08 17:41:32 +0000412const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
413 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
414 case Sema::TDK_Success:
415 case Sema::TDK_InstantiationDepth:
416 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000417 case Sema::TDK_TooManyArguments:
418 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000419 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000420 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000421 return 0;
422
Douglas Gregora9333192010-05-08 17:41:32 +0000423 case Sema::TDK_Inconsistent:
424 case Sema::TDK_InconsistentQuals:
425 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
426
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000427 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000428 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000429 case Sema::TDK_FailedOverloadResolution:
430 break;
431 }
432
433 return 0;
434}
435
436const TemplateArgument *
437OverloadCandidate::DeductionFailureInfo::getSecondArg() {
438 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
439 case Sema::TDK_Success:
440 case Sema::TDK_InstantiationDepth:
441 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000442 case Sema::TDK_TooManyArguments:
443 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000444 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000445 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000446 return 0;
447
Douglas Gregora9333192010-05-08 17:41:32 +0000448 case Sema::TDK_Inconsistent:
449 case Sema::TDK_InconsistentQuals:
450 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
451
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000452 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000453 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000454 case Sema::TDK_FailedOverloadResolution:
455 break;
456 }
457
458 return 0;
459}
460
461void OverloadCandidateSet::clear() {
Douglas Gregora9333192010-05-08 17:41:32 +0000462 inherited::clear();
463 Functions.clear();
464}
465
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000466// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000467// overload of the declarations in Old. This routine returns false if
468// New and Old cannot be overloaded, e.g., if New has the same
469// signature as some function in Old (C++ 1.3.10) or if the Old
470// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000471// it does return false, MatchedDecl will point to the decl that New
472// cannot be overloaded with. This decl may be a UsingShadowDecl on
473// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000474//
475// Example: Given the following input:
476//
477// void f(int, float); // #1
478// void f(int, int); // #2
479// int f(int, int); // #3
480//
481// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000482// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000483//
John McCall51fa86f2009-12-02 08:47:38 +0000484// When we process #2, Old contains only the FunctionDecl for #1. By
485// comparing the parameter types, we see that #1 and #2 are overloaded
486// (since they have different signatures), so this routine returns
487// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000488//
John McCall51fa86f2009-12-02 08:47:38 +0000489// When we process #3, Old is an overload set containing #1 and #2. We
490// compare the signatures of #3 to #1 (they're overloaded, so we do
491// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
492// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000493// signature), IsOverload returns false and MatchedDecl will be set to
494// point to the FunctionDecl for #2.
John McCall871b2e72009-12-09 03:35:25 +0000495Sema::OverloadKind
John McCall9f54ad42009-12-10 09:41:52 +0000496Sema::CheckOverload(FunctionDecl *New, const LookupResult &Old,
497 NamedDecl *&Match) {
John McCall51fa86f2009-12-02 08:47:38 +0000498 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000499 I != E; ++I) {
John McCall51fa86f2009-12-02 08:47:38 +0000500 NamedDecl *OldD = (*I)->getUnderlyingDecl();
501 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCall68263142009-11-18 22:49:29 +0000502 if (!IsOverload(New, OldT->getTemplatedDecl())) {
John McCall871b2e72009-12-09 03:35:25 +0000503 Match = *I;
504 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000505 }
John McCall51fa86f2009-12-02 08:47:38 +0000506 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCall68263142009-11-18 22:49:29 +0000507 if (!IsOverload(New, OldF)) {
John McCall871b2e72009-12-09 03:35:25 +0000508 Match = *I;
509 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000510 }
John McCall9f54ad42009-12-10 09:41:52 +0000511 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
512 // We can overload with these, which can show up when doing
513 // redeclaration checks for UsingDecls.
514 assert(Old.getLookupKind() == LookupUsingDeclName);
515 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
516 // Optimistically assume that an unresolved using decl will
517 // overload; if it doesn't, we'll have to diagnose during
518 // template instantiation.
519 } else {
John McCall68263142009-11-18 22:49:29 +0000520 // (C++ 13p1):
521 // Only function declarations can be overloaded; object and type
522 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000523 Match = *I;
524 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000525 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000526 }
John McCall68263142009-11-18 22:49:29 +0000527
John McCall871b2e72009-12-09 03:35:25 +0000528 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000529}
530
531bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
532 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
533 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
534
535 // C++ [temp.fct]p2:
536 // A function template can be overloaded with other function templates
537 // and with normal (non-template) functions.
538 if ((OldTemplate == 0) != (NewTemplate == 0))
539 return true;
540
541 // Is the function New an overload of the function Old?
542 QualType OldQType = Context.getCanonicalType(Old->getType());
543 QualType NewQType = Context.getCanonicalType(New->getType());
544
545 // Compare the signatures (C++ 1.3.10) of the two functions to
546 // determine whether they are overloads. If we find any mismatch
547 // in the signature, they are overloads.
548
549 // If either of these functions is a K&R-style function (no
550 // prototype), then we consider them to have matching signatures.
551 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
552 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
553 return false;
554
555 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
556 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
557
558 // The signature of a function includes the types of its
559 // parameters (C++ 1.3.10), which includes the presence or absence
560 // of the ellipsis; see C++ DR 357).
561 if (OldQType != NewQType &&
562 (OldType->getNumArgs() != NewType->getNumArgs() ||
563 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000564 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000565 return true;
566
567 // C++ [temp.over.link]p4:
568 // The signature of a function template consists of its function
569 // signature, its return type and its template parameter list. The names
570 // of the template parameters are significant only for establishing the
571 // relationship between the template parameters and the rest of the
572 // signature.
573 //
574 // We check the return type and template parameter lists for function
575 // templates first; the remaining checks follow.
576 if (NewTemplate &&
577 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
578 OldTemplate->getTemplateParameters(),
579 false, TPL_TemplateMatch) ||
580 OldType->getResultType() != NewType->getResultType()))
581 return true;
582
583 // If the function is a class member, its signature includes the
584 // cv-qualifiers (if any) on the function itself.
585 //
586 // As part of this, also check whether one of the member functions
587 // is static, in which case they are not overloads (C++
588 // 13.1p2). While not part of the definition of the signature,
589 // this check is important to determine whether these functions
590 // can be overloaded.
591 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
592 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
593 if (OldMethod && NewMethod &&
594 !OldMethod->isStatic() && !NewMethod->isStatic() &&
595 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
596 return true;
597
598 // The signatures match; this is not an overload.
599 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000600}
601
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000602/// TryImplicitConversion - Attempt to perform an implicit conversion
603/// from the given expression (Expr) to the given type (ToType). This
604/// function returns an implicit conversion sequence that can be used
605/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000606///
607/// void f(float f);
608/// void g(int i) { f(i); }
609///
610/// this routine would produce an implicit conversion sequence to
611/// describe the initialization of f from i, which will be a standard
612/// conversion sequence containing an lvalue-to-rvalue conversion (C++
613/// 4.1) followed by a floating-integral conversion (C++ 4.9).
614//
615/// Note that this routine only determines how the conversion can be
616/// performed; it does not actually perform the conversion. As such,
617/// it will not produce any diagnostics if no conversion is available,
618/// but will instead return an implicit conversion sequence of kind
619/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000620///
621/// If @p SuppressUserConversions, then user-defined conversions are
622/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000623/// If @p AllowExplicit, then explicit user-defined conversions are
624/// permitted.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000625ImplicitConversionSequence
Anders Carlsson2974b5c2009-08-27 17:14:02 +0000626Sema::TryImplicitConversion(Expr* From, QualType ToType,
627 bool SuppressUserConversions,
Douglas Gregor74e386e2010-04-16 18:00:29 +0000628 bool AllowExplicit,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000629 bool InOverloadResolution) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000630 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +0000631 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
John McCall1d318332010-01-12 00:44:57 +0000632 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +0000633 return ICS;
634 }
635
636 if (!getLangOptions().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +0000637 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +0000638 return ICS;
639 }
640
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000641 if (SuppressUserConversions) {
642 // C++ [over.ics.user]p4:
643 // A conversion of an expression of class type to the same class
644 // type is given Exact Match rank, and a conversion of an
645 // expression of class type to a base class of that type is
646 // given Conversion rank, in spite of the fact that a copy/move
647 // constructor (i.e., a user-defined conversion function) is
648 // called for those cases.
649 QualType FromType = From->getType();
650 if (!ToType->getAs<RecordType>() || !FromType->getAs<RecordType>() ||
651 !(Context.hasSameUnqualifiedType(FromType, ToType) ||
652 IsDerivedFrom(FromType, ToType))) {
653 // We're not in the case above, so there is no conversion that
654 // we can perform.
655 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
656 return ICS;
657 }
658
659 ICS.setStandard();
660 ICS.Standard.setAsIdentityConversion();
661 ICS.Standard.setFromType(FromType);
662 ICS.Standard.setAllToTypes(ToType);
663
664 // We don't actually check at this point whether there is a valid
665 // copy/move constructor, since overloading just assumes that it
666 // exists. When we actually perform initialization, we'll find the
667 // appropriate constructor to copy the returned object, if needed.
668 ICS.Standard.CopyConstructor = 0;
669
670 // Determine whether this is considered a derived-to-base conversion.
671 if (!Context.hasSameUnqualifiedType(FromType, ToType))
672 ICS.Standard.Second = ICK_Derived_To_Base;
673
674 return ICS;
675 }
676
677 // Attempt user-defined conversion.
John McCall5769d612010-02-08 23:07:23 +0000678 OverloadCandidateSet Conversions(From->getExprLoc());
679 OverloadingResult UserDefResult
680 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000681 AllowExplicit);
John McCall5769d612010-02-08 23:07:23 +0000682
683 if (UserDefResult == OR_Success) {
John McCall1d318332010-01-12 00:44:57 +0000684 ICS.setUserDefined();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000685 // C++ [over.ics.user]p4:
686 // A conversion of an expression of class type to the same class
687 // type is given Exact Match rank, and a conversion of an
688 // expression of class type to a base class of that type is
689 // given Conversion rank, in spite of the fact that a copy
690 // constructor (i.e., a user-defined conversion function) is
691 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000692 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000693 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000694 QualType FromCanon
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000695 = Context.getCanonicalType(From->getType().getUnqualifiedType());
696 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor9e9199d2009-12-22 00:34:07 +0000697 if (Constructor->isCopyConstructor() &&
Douglas Gregor0d6d12b2009-12-22 00:21:20 +0000698 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000699 // Turn this into a "standard" conversion sequence, so that it
700 // gets ranked with standard conversion sequences.
John McCall1d318332010-01-12 00:44:57 +0000701 ICS.setStandard();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000702 ICS.Standard.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +0000703 ICS.Standard.setFromType(From->getType());
Douglas Gregorad323a82010-01-27 03:51:04 +0000704 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000705 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000706 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000707 ICS.Standard.Second = ICK_Derived_To_Base;
708 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000709 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000710
711 // C++ [over.best.ics]p4:
712 // However, when considering the argument of a user-defined
713 // conversion function that is a candidate by 13.3.1.3 when
714 // invoked for the copying of the temporary in the second step
715 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
716 // 13.3.1.6 in all cases, only standard conversion sequences and
717 // ellipsis conversion sequences are allowed.
John McCalladbb8f82010-01-13 09:16:55 +0000718 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCallb1bdc622010-02-25 01:37:24 +0000719 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCalladbb8f82010-01-13 09:16:55 +0000720 }
John McCallcefd3ad2010-01-13 22:30:33 +0000721 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall1d318332010-01-12 00:44:57 +0000722 ICS.setAmbiguous();
723 ICS.Ambiguous.setFromType(From->getType());
724 ICS.Ambiguous.setToType(ToType);
725 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
726 Cand != Conversions.end(); ++Cand)
727 if (Cand->Viable)
728 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000729 } else {
John McCallb1bdc622010-02-25 01:37:24 +0000730 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000731 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000732
733 return ICS;
734}
735
Douglas Gregor575c63a2010-04-16 22:27:05 +0000736/// PerformImplicitConversion - Perform an implicit conversion of the
737/// expression From to the type ToType. Returns true if there was an
738/// error, false otherwise. The expression From is replaced with the
739/// converted expression. Flavor is the kind of conversion we're
740/// performing, used in the error message. If @p AllowExplicit,
741/// explicit user-defined conversions are permitted.
742bool
743Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
744 AssignmentAction Action, bool AllowExplicit) {
745 ImplicitConversionSequence ICS;
746 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
747}
748
749bool
750Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
751 AssignmentAction Action, bool AllowExplicit,
752 ImplicitConversionSequence& ICS) {
753 ICS = TryImplicitConversion(From, ToType,
754 /*SuppressUserConversions=*/false,
755 AllowExplicit,
756 /*InOverloadResolution=*/false);
757 return PerformImplicitConversion(From, ToType, ICS, Action);
758}
759
Douglas Gregor43c79c22009-12-09 00:47:37 +0000760/// \brief Determine whether the conversion from FromType to ToType is a valid
761/// conversion that strips "noreturn" off the nested function type.
762static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
763 QualType ToType, QualType &ResultTy) {
764 if (Context.hasSameUnqualifiedType(FromType, ToType))
765 return false;
766
767 // Strip the noreturn off the type we're converting from; noreturn can
768 // safely be removed.
769 FromType = Context.getNoReturnType(FromType, false);
770 if (!Context.hasSameUnqualifiedType(FromType, ToType))
771 return false;
772
773 ResultTy = FromType;
774 return true;
775}
776
Douglas Gregor60d62c22008-10-31 16:23:19 +0000777/// IsStandardConversion - Determines whether there is a standard
778/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
779/// expression From to the type ToType. Standard conversion sequences
780/// only consider non-class types; for conversions that involve class
781/// types, use TryImplicitConversion. If a conversion exists, SCS will
782/// contain the standard conversion sequence required to perform this
783/// conversion and this routine will return true. Otherwise, this
784/// routine will return false and the value of SCS is unspecified.
Mike Stump1eb44332009-09-09 15:08:12 +0000785bool
786Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000787 bool InOverloadResolution,
Mike Stump1eb44332009-09-09 15:08:12 +0000788 StandardConversionSequence &SCS) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000789 QualType FromType = From->getType();
790
Douglas Gregor60d62c22008-10-31 16:23:19 +0000791 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000792 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +0000793 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000794 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +0000795 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000796 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000797
Douglas Gregorf9201e02009-02-11 23:02:49 +0000798 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +0000799 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +0000800 if (FromType->isRecordType() || ToType->isRecordType()) {
801 if (getLangOptions().CPlusPlus)
802 return false;
803
Mike Stump1eb44332009-09-09 15:08:12 +0000804 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000805 }
806
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000807 // The first conversion can be an lvalue-to-rvalue conversion,
808 // array-to-pointer conversion, or function-to-pointer conversion
809 // (C++ 4p1).
810
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000811 if (FromType == Context.OverloadTy) {
812 DeclAccessPair AccessPair;
813 if (FunctionDecl *Fn
814 = ResolveAddressOfOverloadedFunction(From, ToType, false,
815 AccessPair)) {
816 // We were able to resolve the address of the overloaded function,
817 // so we can convert to the type of that function.
818 FromType = Fn->getType();
819 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
820 if (!Method->isStatic()) {
821 Type *ClassType
822 = Context.getTypeDeclType(Method->getParent()).getTypePtr();
823 FromType = Context.getMemberPointerType(FromType, ClassType);
824 }
825 }
826
827 // If the "from" expression takes the address of the overloaded
828 // function, update the type of the resulting expression accordingly.
829 if (FromType->getAs<FunctionType>())
830 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
831 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
832 FromType = Context.getPointerType(FromType);
833
834 // Check that we've computed the proper type after overload resolution.
835 assert(Context.hasSameType(FromType,
836 FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
837 } else {
838 return false;
839 }
840 }
Mike Stump1eb44332009-09-09 15:08:12 +0000841 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000842 // An lvalue (3.10) of a non-function, non-array type T can be
843 // converted to an rvalue.
844 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000845 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000846 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor063daf62009-03-13 18:40:31 +0000847 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000848 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000849
850 // If T is a non-class type, the type of the rvalue is the
851 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +0000852 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
853 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000854 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000855 } else if (FromType->isArrayType()) {
856 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000857 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000858
859 // An lvalue or rvalue of type "array of N T" or "array of unknown
860 // bound of T" can be converted to an rvalue of type "pointer to
861 // T" (C++ 4.2p1).
862 FromType = Context.getArrayDecayedType(FromType);
863
864 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
865 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +0000866 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000867
868 // For the purpose of ranking in overload resolution
869 // (13.3.3.1.1), this conversion is considered an
870 // array-to-pointer conversion followed by a qualification
871 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000872 SCS.Second = ICK_Identity;
873 SCS.Third = ICK_Qualification;
Douglas Gregorad323a82010-01-27 03:51:04 +0000874 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000875 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000876 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000877 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
878 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000879 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000880
881 // An lvalue of function type T can be converted to an rvalue of
882 // type "pointer to T." The result is a pointer to the
883 // function. (C++ 4.3p1).
884 FromType = Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000885 } else {
886 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000887 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000888 }
Douglas Gregorad323a82010-01-27 03:51:04 +0000889 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000890
891 // The second conversion can be an integral promotion, floating
892 // point promotion, integral conversion, floating point conversion,
893 // floating-integral conversion, pointer conversion,
894 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +0000895 // For overloading in C, this can also be a "compatible-type"
896 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +0000897 bool IncompatibleObjC = false;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000898 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000899 // The unqualified versions of the types are the same: there's no
900 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000901 SCS.Second = ICK_Identity;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000902 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000903 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000904 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000905 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000906 } else if (IsFloatingPointPromotion(FromType, ToType)) {
907 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000908 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000909 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000910 } else if (IsComplexPromotion(FromType, ToType)) {
911 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000912 SCS.Second = ICK_Complex_Promotion;
913 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000914 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000915 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000916 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000917 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000918 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000919 } else if (FromType->isComplexType() && ToType->isComplexType()) {
920 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000921 SCS.Second = ICK_Complex_Conversion;
922 FromType = ToType.getUnqualifiedType();
Chandler Carruth23a370f2010-02-25 07:20:54 +0000923 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
924 (ToType->isComplexType() && FromType->isArithmeticType())) {
925 // Complex-real conversions (C99 6.3.1.7)
926 SCS.Second = ICK_Complex_Real;
927 FromType = ToType.getUnqualifiedType();
928 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
929 // Floating point conversions (C++ 4.8).
930 SCS.Second = ICK_Floating_Conversion;
931 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000932 } else if ((FromType->isFloatingType() &&
933 ToType->isIntegralType() && (!ToType->isBooleanType() &&
934 !ToType->isEnumeralType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000935 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000936 ToType->isFloatingType())) {
937 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000938 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000939 FromType = ToType.getUnqualifiedType();
Anders Carlsson08972922009-08-28 15:33:32 +0000940 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
941 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000942 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000943 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +0000944 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregorce940492009-09-25 04:25:58 +0000945 } else if (IsMemberPointerConversion(From, FromType, ToType,
946 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000947 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000948 SCS.Second = ICK_Pointer_Member;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000949 } else if (ToType->isBooleanType() &&
950 (FromType->isArithmeticType() ||
951 FromType->isEnumeralType() ||
Fariborz Jahanian1f7711d2009-12-11 21:23:13 +0000952 FromType->isAnyPointerType() ||
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000953 FromType->isBlockPointerType() ||
954 FromType->isMemberPointerType() ||
955 FromType->isNullPtrType())) {
956 // Boolean conversions (C++ 4.12).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000957 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000958 FromType = Context.BoolTy;
Mike Stump1eb44332009-09-09 15:08:12 +0000959 } else if (!getLangOptions().CPlusPlus &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000960 Context.typesAreCompatible(ToType, FromType)) {
961 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000962 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor43c79c22009-12-09 00:47:37 +0000963 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
964 // Treat a conversion that strips "noreturn" as an identity conversion.
965 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000966 } else {
967 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000968 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000969 }
Douglas Gregorad323a82010-01-27 03:51:04 +0000970 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000971
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000972 QualType CanonFrom;
973 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000974 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +0000975 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000976 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000977 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000978 CanonFrom = Context.getCanonicalType(FromType);
979 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000980 } else {
981 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +0000982 SCS.Third = ICK_Identity;
983
Mike Stump1eb44332009-09-09 15:08:12 +0000984 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +0000985 // [...] Any difference in top-level cv-qualification is
986 // subsumed by the initialization itself and does not constitute
987 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000988 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +0000989 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregora4923eb2009-11-16 21:35:15 +0000990 if (CanonFrom.getLocalUnqualifiedType()
991 == CanonTo.getLocalUnqualifiedType() &&
992 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000993 FromType = ToType;
994 CanonFrom = CanonTo;
995 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000996 }
Douglas Gregorad323a82010-01-27 03:51:04 +0000997 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000998
999 // If we have not converted the argument type to the parameter type,
1000 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001001 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001002 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001003
Douglas Gregor60d62c22008-10-31 16:23:19 +00001004 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001005}
1006
1007/// IsIntegralPromotion - Determines whether the conversion from the
1008/// expression From (whose potentially-adjusted type is FromType) to
1009/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1010/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001011bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001012 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001013 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001014 if (!To) {
1015 return false;
1016 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001017
1018 // An rvalue of type char, signed char, unsigned char, short int, or
1019 // unsigned short int can be converted to an rvalue of type int if
1020 // int can represent all the values of the source type; otherwise,
1021 // the source rvalue can be converted to an rvalue of type unsigned
1022 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001023 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1024 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001025 if (// We can promote any signed, promotable integer type to an int
1026 (FromType->isSignedIntegerType() ||
1027 // We can promote any unsigned integer type whose size is
1028 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001029 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001030 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001031 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001032 }
1033
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001034 return To->getKind() == BuiltinType::UInt;
1035 }
1036
1037 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
1038 // can be converted to an rvalue of the first of the following types
1039 // that can represent all the values of its underlying type: int,
1040 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall842aef82009-12-09 09:09:27 +00001041
1042 // We pre-calculate the promotion type for enum types.
1043 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
1044 if (ToType->isIntegerType())
1045 return Context.hasSameUnqualifiedType(ToType,
1046 FromEnumType->getDecl()->getPromotionType());
1047
1048 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001049 // Determine whether the type we're converting from is signed or
1050 // unsigned.
1051 bool FromIsSigned;
1052 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall842aef82009-12-09 09:09:27 +00001053
1054 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1055 FromIsSigned = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001056
1057 // The types we'll try to promote to, in the appropriate
1058 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001059 QualType PromoteTypes[6] = {
1060 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001061 Context.LongTy, Context.UnsignedLongTy ,
1062 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001063 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001064 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001065 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1066 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001067 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001068 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1069 // We found the type that we can promote to. If this is the
1070 // type we wanted, we have a promotion. Otherwise, no
1071 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001072 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001073 }
1074 }
1075 }
1076
1077 // An rvalue for an integral bit-field (9.6) can be converted to an
1078 // rvalue of type int if int can represent all the values of the
1079 // bit-field; otherwise, it can be converted to unsigned int if
1080 // unsigned int can represent all the values of the bit-field. If
1081 // the bit-field is larger yet, no integral promotion applies to
1082 // it. If the bit-field has an enumerated type, it is treated as any
1083 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001084 // FIXME: We should delay checking of bit-fields until we actually perform the
1085 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001086 using llvm::APSInt;
1087 if (From)
1088 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001089 APSInt BitWidth;
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001090 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
1091 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1092 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1093 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001094
Douglas Gregor86f19402008-12-20 23:49:58 +00001095 // Are we promoting to an int from a bitfield that fits in an int?
1096 if (BitWidth < ToSize ||
1097 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1098 return To->getKind() == BuiltinType::Int;
1099 }
Mike Stump1eb44332009-09-09 15:08:12 +00001100
Douglas Gregor86f19402008-12-20 23:49:58 +00001101 // Are we promoting to an unsigned int from an unsigned bitfield
1102 // that fits into an unsigned int?
1103 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1104 return To->getKind() == BuiltinType::UInt;
1105 }
Mike Stump1eb44332009-09-09 15:08:12 +00001106
Douglas Gregor86f19402008-12-20 23:49:58 +00001107 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001108 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001109 }
Mike Stump1eb44332009-09-09 15:08:12 +00001110
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001111 // An rvalue of type bool can be converted to an rvalue of type int,
1112 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001113 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001114 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001115 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001116
1117 return false;
1118}
1119
1120/// IsFloatingPointPromotion - Determines whether the conversion from
1121/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1122/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001123bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001124 /// An rvalue of type float can be converted to an rvalue of type
1125 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +00001126 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1127 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001128 if (FromBuiltin->getKind() == BuiltinType::Float &&
1129 ToBuiltin->getKind() == BuiltinType::Double)
1130 return true;
1131
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001132 // C99 6.3.1.5p1:
1133 // When a float is promoted to double or long double, or a
1134 // double is promoted to long double [...].
1135 if (!getLangOptions().CPlusPlus &&
1136 (FromBuiltin->getKind() == BuiltinType::Float ||
1137 FromBuiltin->getKind() == BuiltinType::Double) &&
1138 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1139 return true;
1140 }
1141
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001142 return false;
1143}
1144
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001145/// \brief Determine if a conversion is a complex promotion.
1146///
1147/// A complex promotion is defined as a complex -> complex conversion
1148/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001149/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001150bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001151 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001152 if (!FromComplex)
1153 return false;
1154
John McCall183700f2009-09-21 23:43:11 +00001155 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001156 if (!ToComplex)
1157 return false;
1158
1159 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001160 ToComplex->getElementType()) ||
1161 IsIntegralPromotion(0, FromComplex->getElementType(),
1162 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001163}
1164
Douglas Gregorcb7de522008-11-26 23:31:11 +00001165/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1166/// the pointer type FromPtr to a pointer to type ToPointee, with the
1167/// same type qualifiers as FromPtr has on its pointee type. ToType,
1168/// if non-empty, will be a pointer to ToType that may or may not have
1169/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +00001170static QualType
1171BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001172 QualType ToPointee, QualType ToType,
1173 ASTContext &Context) {
1174 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1175 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001176 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001177
1178 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001179 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001180 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001181 if (!ToType.isNull())
Douglas Gregorcb7de522008-11-26 23:31:11 +00001182 return ToType;
1183
1184 // Build a pointer to ToPointee. It has the right qualifiers
1185 // already.
1186 return Context.getPointerType(ToPointee);
1187 }
1188
1189 // Just build a canonical type that has the right qualifiers.
John McCall0953e762009-09-24 19:53:00 +00001190 return Context.getPointerType(
Douglas Gregora4923eb2009-11-16 21:35:15 +00001191 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1192 Quals));
Douglas Gregorcb7de522008-11-26 23:31:11 +00001193}
1194
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001195/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1196/// the FromType, which is an objective-c pointer, to ToType, which may or may
1197/// not have the right set of qualifiers.
1198static QualType
1199BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1200 QualType ToType,
1201 ASTContext &Context) {
1202 QualType CanonFromType = Context.getCanonicalType(FromType);
1203 QualType CanonToType = Context.getCanonicalType(ToType);
1204 Qualifiers Quals = CanonFromType.getQualifiers();
1205
1206 // Exact qualifier match -> return the pointer type we're converting to.
1207 if (CanonToType.getLocalQualifiers() == Quals)
1208 return ToType;
1209
1210 // Just build a canonical type that has the right qualifiers.
1211 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1212}
1213
Mike Stump1eb44332009-09-09 15:08:12 +00001214static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001215 bool InOverloadResolution,
1216 ASTContext &Context) {
1217 // Handle value-dependent integral null pointer constants correctly.
1218 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1219 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1220 Expr->getType()->isIntegralType())
1221 return !InOverloadResolution;
1222
Douglas Gregorce940492009-09-25 04:25:58 +00001223 return Expr->isNullPointerConstant(Context,
1224 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1225 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001226}
Mike Stump1eb44332009-09-09 15:08:12 +00001227
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001228/// IsPointerConversion - Determines whether the conversion of the
1229/// expression From, which has the (possibly adjusted) type FromType,
1230/// can be converted to the type ToType via a pointer conversion (C++
1231/// 4.10). If so, returns true and places the converted type (that
1232/// might differ from ToType in its cv-qualifiers at some level) into
1233/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001234///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001235/// This routine also supports conversions to and from block pointers
1236/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1237/// pointers to interfaces. FIXME: Once we've determined the
1238/// appropriate overloading rules for Objective-C, we may want to
1239/// split the Objective-C checks into a different routine; however,
1240/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001241/// conversions, so for now they live here. IncompatibleObjC will be
1242/// set if the conversion is an allowed Objective-C conversion that
1243/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001244bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001245 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001246 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001247 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001248 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +00001249 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1250 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001251
Mike Stump1eb44332009-09-09 15:08:12 +00001252 // Conversion from a null pointer constant to any Objective-C pointer type.
1253 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001254 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001255 ConvertedType = ToType;
1256 return true;
1257 }
1258
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001259 // Blocks: Block pointers can be converted to void*.
1260 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001261 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001262 ConvertedType = ToType;
1263 return true;
1264 }
1265 // Blocks: A null pointer constant can be converted to a block
1266 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001267 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001268 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001269 ConvertedType = ToType;
1270 return true;
1271 }
1272
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001273 // If the left-hand-side is nullptr_t, the right side can be a null
1274 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001275 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001276 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001277 ConvertedType = ToType;
1278 return true;
1279 }
1280
Ted Kremenek6217b802009-07-29 21:53:49 +00001281 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001282 if (!ToTypePtr)
1283 return false;
1284
1285 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001286 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001287 ConvertedType = ToType;
1288 return true;
1289 }
Sebastian Redl07779722008-10-31 14:43:28 +00001290
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001291 // Beyond this point, both types need to be pointers
1292 // , including objective-c pointers.
1293 QualType ToPointeeType = ToTypePtr->getPointeeType();
1294 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1295 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1296 ToType, Context);
1297 return true;
1298
1299 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001300 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001301 if (!FromTypePtr)
1302 return false;
1303
1304 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001305
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001306 // An rvalue of type "pointer to cv T," where T is an object type,
1307 // can be converted to an rvalue of type "pointer to cv void" (C++
1308 // 4.10p2).
Douglas Gregorbad0e652009-03-24 20:32:41 +00001309 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001310 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001311 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001312 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001313 return true;
1314 }
1315
Douglas Gregorf9201e02009-02-11 23:02:49 +00001316 // When we're overloading in C, we allow a special kind of pointer
1317 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001318 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001319 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001320 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001321 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001322 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001323 return true;
1324 }
1325
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001326 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001327 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001328 // An rvalue of type "pointer to cv D," where D is a class type,
1329 // can be converted to an rvalue of type "pointer to cv B," where
1330 // B is a base class (clause 10) of D. If B is an inaccessible
1331 // (clause 11) or ambiguous (10.2) base class of D, a program that
1332 // necessitates this conversion is ill-formed. The result of the
1333 // conversion is a pointer to the base class sub-object of the
1334 // derived class object. The null pointer value is converted to
1335 // the null pointer value of the destination type.
1336 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001337 // Note that we do not check for ambiguity or inaccessibility
1338 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001339 if (getLangOptions().CPlusPlus &&
1340 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001341 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001342 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001343 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001344 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001345 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001346 ToType, Context);
1347 return true;
1348 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001349
Douglas Gregorc7887512008-12-19 19:13:09 +00001350 return false;
1351}
1352
1353/// isObjCPointerConversion - Determines whether this is an
1354/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1355/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001356bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001357 QualType& ConvertedType,
1358 bool &IncompatibleObjC) {
1359 if (!getLangOptions().ObjC1)
1360 return false;
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001361
Steve Naroff14108da2009-07-10 23:34:53 +00001362 // First, we handle all conversions on ObjC object pointer types.
John McCall183700f2009-09-21 23:43:11 +00001363 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001364 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001365 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001366
Steve Naroff14108da2009-07-10 23:34:53 +00001367 if (ToObjCPtr && FromObjCPtr) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00001368 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001369 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001370 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001371 ConvertedType = ToType;
1372 return true;
1373 }
1374 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001375 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001376 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001377 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001378 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001379 ConvertedType = ToType;
1380 return true;
1381 }
1382 // Objective C++: We're able to convert from a pointer to an
1383 // interface to a pointer to a different interface.
1384 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00001385 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1386 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1387 if (getLangOptions().CPlusPlus && LHS && RHS &&
1388 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1389 FromObjCPtr->getPointeeType()))
1390 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00001391 ConvertedType = ToType;
1392 return true;
1393 }
1394
1395 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1396 // Okay: this is some kind of implicit downcast of Objective-C
1397 // interfaces, which is permitted. However, we're going to
1398 // complain about it.
1399 IncompatibleObjC = true;
1400 ConvertedType = FromType;
1401 return true;
1402 }
Mike Stump1eb44332009-09-09 15:08:12 +00001403 }
Steve Naroff14108da2009-07-10 23:34:53 +00001404 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001405 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001406 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001407 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001408 else if (const BlockPointerType *ToBlockPtr =
1409 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00001410 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001411 // to a block pointer type.
1412 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1413 ConvertedType = ToType;
1414 return true;
1415 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001416 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001417 }
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001418 else if (FromType->getAs<BlockPointerType>() &&
1419 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1420 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00001421 // pointer to any object.
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001422 ConvertedType = ToType;
1423 return true;
1424 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001425 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001426 return false;
1427
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001428 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001429 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001430 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001431 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001432 FromPointeeType = FromBlockPtr->getPointeeType();
1433 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001434 return false;
1435
Douglas Gregorc7887512008-12-19 19:13:09 +00001436 // If we have pointers to pointers, recursively check whether this
1437 // is an Objective-C conversion.
1438 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1439 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1440 IncompatibleObjC)) {
1441 // We always complain about this conversion.
1442 IncompatibleObjC = true;
1443 ConvertedType = ToType;
1444 return true;
1445 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001446 // Allow conversion of pointee being objective-c pointer to another one;
1447 // as in I* to id.
1448 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1449 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1450 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1451 IncompatibleObjC)) {
1452 ConvertedType = ToType;
1453 return true;
1454 }
1455
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001456 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001457 // differences in the argument and result types are in Objective-C
1458 // pointer conversions. If so, we permit the conversion (but
1459 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001460 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001461 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001462 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001463 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001464 if (FromFunctionType && ToFunctionType) {
1465 // If the function types are exactly the same, this isn't an
1466 // Objective-C pointer conversion.
1467 if (Context.getCanonicalType(FromPointeeType)
1468 == Context.getCanonicalType(ToPointeeType))
1469 return false;
1470
1471 // Perform the quick checks that will tell us whether these
1472 // function types are obviously different.
1473 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1474 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1475 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1476 return false;
1477
1478 bool HasObjCConversion = false;
1479 if (Context.getCanonicalType(FromFunctionType->getResultType())
1480 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1481 // Okay, the types match exactly. Nothing to do.
1482 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1483 ToFunctionType->getResultType(),
1484 ConvertedType, IncompatibleObjC)) {
1485 // Okay, we have an Objective-C pointer conversion.
1486 HasObjCConversion = true;
1487 } else {
1488 // Function types are too different. Abort.
1489 return false;
1490 }
Mike Stump1eb44332009-09-09 15:08:12 +00001491
Douglas Gregorc7887512008-12-19 19:13:09 +00001492 // Check argument types.
1493 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1494 ArgIdx != NumArgs; ++ArgIdx) {
1495 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1496 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1497 if (Context.getCanonicalType(FromArgType)
1498 == Context.getCanonicalType(ToArgType)) {
1499 // Okay, the types match exactly. Nothing to do.
1500 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1501 ConvertedType, IncompatibleObjC)) {
1502 // Okay, we have an Objective-C pointer conversion.
1503 HasObjCConversion = true;
1504 } else {
1505 // Argument types are too different. Abort.
1506 return false;
1507 }
1508 }
1509
1510 if (HasObjCConversion) {
1511 // We had an Objective-C conversion. Allow this pointer
1512 // conversion, but complain about it.
1513 ConvertedType = ToType;
1514 IncompatibleObjC = true;
1515 return true;
1516 }
1517 }
1518
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001519 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001520}
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001521
1522/// FunctionArgTypesAreEqual - This routine checks two function proto types
1523/// for equlity of their argument types. Caller has already checked that
1524/// they have same number of arguments. This routine assumes that Objective-C
1525/// pointer types which only differ in their protocol qualifiers are equal.
1526bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1527 FunctionProtoType* NewType){
1528 if (!getLangOptions().ObjC1)
1529 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1530 NewType->arg_type_begin());
1531
1532 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1533 N = NewType->arg_type_begin(),
1534 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1535 QualType ToType = (*O);
1536 QualType FromType = (*N);
1537 if (ToType != FromType) {
1538 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1539 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00001540 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1541 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1542 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1543 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001544 continue;
1545 }
1546 else if (ToType->isObjCObjectPointerType() &&
1547 FromType->isObjCObjectPointerType()) {
1548 QualType ToInterfaceTy = ToType->getPointeeType();
1549 QualType FromInterfaceTy = FromType->getPointeeType();
1550 if (const ObjCInterfaceType *OITTo =
1551 ToInterfaceTy->getAs<ObjCInterfaceType>())
1552 if (const ObjCInterfaceType *OITFr =
1553 FromInterfaceTy->getAs<ObjCInterfaceType>())
1554 if (OITTo->getDecl() == OITFr->getDecl())
1555 continue;
1556 }
1557 return false;
1558 }
1559 }
1560 return true;
1561}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001562
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001563/// CheckPointerConversion - Check the pointer conversion from the
1564/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001565/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001566/// conversions for which IsPointerConversion has already returned
1567/// true. It returns true and produces a diagnostic if there was an
1568/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001569bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001570 CastExpr::CastKind &Kind,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001571 CXXBaseSpecifierArray& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001572 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001573 QualType FromType = From->getType();
1574
Ted Kremenek6217b802009-07-29 21:53:49 +00001575 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1576 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001577 QualType FromPointeeType = FromPtrType->getPointeeType(),
1578 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001579
Douglas Gregor5fccd362010-03-03 23:55:11 +00001580 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1581 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001582 // We must have a derived-to-base conversion. Check an
1583 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001584 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1585 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001586 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001587 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001588 return true;
1589
1590 // The conversion was successful.
1591 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001592 }
1593 }
Mike Stump1eb44332009-09-09 15:08:12 +00001594 if (const ObjCObjectPointerType *FromPtrType =
John McCall183700f2009-09-21 23:43:11 +00001595 FromType->getAs<ObjCObjectPointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001596 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00001597 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001598 // Objective-C++ conversions are always okay.
1599 // FIXME: We should have a different class of conversions for the
1600 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001601 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001602 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001603
Steve Naroff14108da2009-07-10 23:34:53 +00001604 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001605 return false;
1606}
1607
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001608/// IsMemberPointerConversion - Determines whether the conversion of the
1609/// expression From, which has the (possibly adjusted) type FromType, can be
1610/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1611/// If so, returns true and places the converted type (that might differ from
1612/// ToType in its cv-qualifiers at some level) into ConvertedType.
1613bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregorce940492009-09-25 04:25:58 +00001614 QualType ToType,
1615 bool InOverloadResolution,
1616 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001617 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001618 if (!ToTypePtr)
1619 return false;
1620
1621 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00001622 if (From->isNullPointerConstant(Context,
1623 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1624 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001625 ConvertedType = ToType;
1626 return true;
1627 }
1628
1629 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001630 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001631 if (!FromTypePtr)
1632 return false;
1633
1634 // A pointer to member of B can be converted to a pointer to member of D,
1635 // where D is derived from B (C++ 4.11p2).
1636 QualType FromClass(FromTypePtr->getClass(), 0);
1637 QualType ToClass(ToTypePtr->getClass(), 0);
1638 // FIXME: What happens when these are dependent? Is this function even called?
1639
1640 if (IsDerivedFrom(ToClass, FromClass)) {
1641 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1642 ToClass.getTypePtr());
1643 return true;
1644 }
1645
1646 return false;
1647}
Douglas Gregor43c79c22009-12-09 00:47:37 +00001648
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001649/// CheckMemberPointerConversion - Check the member pointer conversion from the
1650/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00001651/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001652/// for which IsMemberPointerConversion has already returned true. It returns
1653/// true and produces a diagnostic if there was an error, or returns false
1654/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001655bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001656 CastExpr::CastKind &Kind,
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001657 CXXBaseSpecifierArray &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001658 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001659 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001660 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001661 if (!FromPtrType) {
1662 // This must be a null pointer to member pointer conversion
Douglas Gregorce940492009-09-25 04:25:58 +00001663 assert(From->isNullPointerConstant(Context,
1664 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001665 "Expr must be null pointer constant!");
1666 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001667 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001668 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001669
Ted Kremenek6217b802009-07-29 21:53:49 +00001670 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001671 assert(ToPtrType && "No member pointer cast has a target type "
1672 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001673
Sebastian Redl21593ac2009-01-28 18:33:18 +00001674 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1675 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001676
Sebastian Redl21593ac2009-01-28 18:33:18 +00001677 // FIXME: What about dependent types?
1678 assert(FromClass->isRecordType() && "Pointer into non-class.");
1679 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001680
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001681 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001682 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00001683 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1684 assert(DerivationOkay &&
1685 "Should not have been called if derivation isn't OK.");
1686 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001687
Sebastian Redl21593ac2009-01-28 18:33:18 +00001688 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1689 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001690 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1691 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1692 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1693 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001694 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001695
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001696 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001697 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1698 << FromClass << ToClass << QualType(VBase, 0)
1699 << From->getSourceRange();
1700 return true;
1701 }
1702
John McCall6b2accb2010-02-10 09:31:12 +00001703 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00001704 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1705 Paths.front(),
1706 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00001707
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001708 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001709 BuildBasePathArray(Paths, BasePath);
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001710 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001711 return false;
1712}
1713
Douglas Gregor98cd5992008-10-21 23:43:52 +00001714/// IsQualificationConversion - Determines whether the conversion from
1715/// an rvalue of type FromType to ToType is a qualification conversion
1716/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001717bool
1718Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001719 FromType = Context.getCanonicalType(FromType);
1720 ToType = Context.getCanonicalType(ToType);
1721
1722 // If FromType and ToType are the same type, this is not a
1723 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00001724 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00001725 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001726
Douglas Gregor98cd5992008-10-21 23:43:52 +00001727 // (C++ 4.4p4):
1728 // A conversion can add cv-qualifiers at levels other than the first
1729 // in multi-level pointers, subject to the following rules: [...]
1730 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001731 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +00001732 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001733 // Within each iteration of the loop, we check the qualifiers to
1734 // determine if this still looks like a qualification
1735 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001736 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001737 // until there are no more pointers or pointers-to-members left to
1738 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001739 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001740
1741 // -- for every j > 0, if const is in cv 1,j then const is in cv
1742 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001743 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001744 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001745
Douglas Gregor98cd5992008-10-21 23:43:52 +00001746 // -- if the cv 1,j and cv 2,j are different, then const is in
1747 // every cv for 0 < k < j.
1748 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001749 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001750 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001751
Douglas Gregor98cd5992008-10-21 23:43:52 +00001752 // Keep track of whether all prior cv-qualifiers in the "to" type
1753 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00001754 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00001755 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001756 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001757
1758 // We are left with FromType and ToType being the pointee types
1759 // after unwrapping the original FromType and ToType the same number
1760 // of types. If we unwrapped any pointers, and if FromType and
1761 // ToType have the same unqualified type (since we checked
1762 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001763 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00001764}
1765
Douglas Gregor734d9862009-01-30 23:27:23 +00001766/// Determines whether there is a user-defined conversion sequence
1767/// (C++ [over.ics.user]) that converts expression From to the type
1768/// ToType. If such a conversion exists, User will contain the
1769/// user-defined conversion sequence that performs such a conversion
1770/// and this routine will return true. Otherwise, this routine returns
1771/// false and User is unspecified.
1772///
Douglas Gregor734d9862009-01-30 23:27:23 +00001773/// \param AllowExplicit true if the conversion should consider C++0x
1774/// "explicit" conversion functions as well as non-explicit conversion
1775/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor20093b42009-12-09 23:02:17 +00001776OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1777 UserDefinedConversionSequence& User,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001778 OverloadCandidateSet& CandidateSet,
1779 bool AllowExplicit) {
1780 // Whether we will only visit constructors.
1781 bool ConstructorsOnly = false;
1782
1783 // If the type we are conversion to is a class type, enumerate its
1784 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00001785 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001786 // C++ [over.match.ctor]p1:
1787 // When objects of class type are direct-initialized (8.5), or
1788 // copy-initialized from an expression of the same or a
1789 // derived class type (8.5), overload resolution selects the
1790 // constructor. [...] For copy-initialization, the candidate
1791 // functions are all the converting constructors (12.3.1) of
1792 // that class. The argument list is the expression-list within
1793 // the parentheses of the initializer.
1794 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1795 (From->getType()->getAs<RecordType>() &&
1796 IsDerivedFrom(From->getType(), ToType)))
1797 ConstructorsOnly = true;
1798
Douglas Gregor393896f2009-11-05 13:06:35 +00001799 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1800 // We're not going to find any constructors.
1801 } else if (CXXRecordDecl *ToRecordDecl
1802 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001803 DeclarationName ConstructorName
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001804 = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001805 Context.getCanonicalType(ToType).getUnqualifiedType());
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001806 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump1eb44332009-09-09 15:08:12 +00001807 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001808 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001809 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00001810 NamedDecl *D = *Con;
1811 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1812
Douglas Gregordec06662009-08-21 18:42:58 +00001813 // Find the constructor (which may be a template).
1814 CXXConstructorDecl *Constructor = 0;
1815 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00001816 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00001817 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00001818 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00001819 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1820 else
John McCall9aa472c2010-03-19 07:35:19 +00001821 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001822
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00001823 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00001824 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001825 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00001826 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001827 /*ExplicitArgs*/ 0,
John McCalld5532b62009-11-23 01:53:49 +00001828 &From, 1, CandidateSet,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001829 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00001830 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001831 // Allow one user-defined conversion when user specifies a
1832 // From->ToType conversion via an static cast (c-style, etc).
John McCall9aa472c2010-03-19 07:35:19 +00001833 AddOverloadCandidate(Constructor, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001834 &From, 1, CandidateSet,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001835 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00001836 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001837 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001838 }
1839 }
1840
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001841 // Enumerate conversion functions, if we're allowed to.
1842 if (ConstructorsOnly) {
Mike Stump1eb44332009-09-09 15:08:12 +00001843 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001844 PDiag(0) << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00001845 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00001846 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001847 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001848 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001849 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1850 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00001851 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00001852 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001853 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001854 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00001855 DeclAccessPair FoundDecl = I.getPair();
1856 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00001857 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1858 if (isa<UsingShadowDecl>(D))
1859 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1860
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001861 CXXConversionDecl *Conv;
1862 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00001863 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1864 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001865 else
John McCall32daa422010-03-31 01:36:47 +00001866 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001867
1868 if (AllowExplicit || !Conv->isExplicit()) {
1869 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00001870 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001871 ActingContext, From, ToType,
1872 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001873 else
John McCall9aa472c2010-03-19 07:35:19 +00001874 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCall86820f52010-01-26 01:37:31 +00001875 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001876 }
1877 }
1878 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001879 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001880
1881 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001882 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001883 case OR_Success:
1884 // Record the standard conversion we used and the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00001885 if (CXXConstructorDecl *Constructor
Douglas Gregor60d62c22008-10-31 16:23:19 +00001886 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1887 // C++ [over.ics.user]p1:
1888 // If the user-defined conversion is specified by a
1889 // constructor (12.3.1), the initial standard conversion
1890 // sequence converts the source type to the type required by
1891 // the argument of the constructor.
1892 //
Douglas Gregor60d62c22008-10-31 16:23:19 +00001893 QualType ThisType = Constructor->getThisType(Context);
John McCall1d318332010-01-12 00:44:57 +00001894 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001895 User.EllipsisConversion = true;
1896 else {
1897 User.Before = Best->Conversions[0].Standard;
1898 User.EllipsisConversion = false;
1899 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001900 User.ConversionFunction = Constructor;
1901 User.After.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +00001902 User.After.setFromType(
1903 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregorad323a82010-01-27 03:51:04 +00001904 User.After.setAllToTypes(ToType);
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001905 return OR_Success;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001906 } else if (CXXConversionDecl *Conversion
1907 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1908 // C++ [over.ics.user]p1:
1909 //
1910 // [...] If the user-defined conversion is specified by a
1911 // conversion function (12.3.2), the initial standard
1912 // conversion sequence converts the source type to the
1913 // implicit object parameter of the conversion function.
1914 User.Before = Best->Conversions[0].Standard;
1915 User.ConversionFunction = Conversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001916 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001917
1918 // C++ [over.ics.user]p2:
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001919 // The second standard conversion sequence converts the
1920 // result of the user-defined conversion to the target type
1921 // for the sequence. Since an implicit conversion sequence
1922 // is an initialization, the special rules for
1923 // initialization by user-defined conversion apply when
1924 // selecting the best user-defined conversion for a
1925 // user-defined conversion sequence (see 13.3.3 and
1926 // 13.3.3.1).
1927 User.After = Best->FinalConversion;
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001928 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001929 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001930 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001931 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001932 }
Mike Stump1eb44332009-09-09 15:08:12 +00001933
Douglas Gregor60d62c22008-10-31 16:23:19 +00001934 case OR_No_Viable_Function:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001935 return OR_No_Viable_Function;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001936 case OR_Deleted:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001937 // No conversion here! We're done.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001938 return OR_Deleted;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001939
1940 case OR_Ambiguous:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001941 return OR_Ambiguous;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001942 }
1943
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001944 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001945}
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001946
1947bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00001948Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001949 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00001950 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001951 OverloadingResult OvResult =
1952 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001953 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00001954 if (OvResult == OR_Ambiguous)
1955 Diag(From->getSourceRange().getBegin(),
1956 diag::err_typecheck_ambiguous_condition)
1957 << From->getType() << ToType << From->getSourceRange();
1958 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1959 Diag(From->getSourceRange().getBegin(),
1960 diag::err_typecheck_nonviable_condition)
1961 << From->getType() << ToType << From->getSourceRange();
1962 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001963 return false;
John McCallcbce6062010-01-12 07:18:19 +00001964 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001965 return true;
1966}
Douglas Gregor60d62c22008-10-31 16:23:19 +00001967
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001968/// CompareImplicitConversionSequences - Compare two implicit
1969/// conversion sequences to determine whether one is better than the
1970/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump1eb44332009-09-09 15:08:12 +00001971ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001972Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1973 const ImplicitConversionSequence& ICS2)
1974{
1975 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1976 // conversion sequences (as defined in 13.3.3.1)
1977 // -- a standard conversion sequence (13.3.3.1.1) is a better
1978 // conversion sequence than a user-defined conversion sequence or
1979 // an ellipsis conversion sequence, and
1980 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1981 // conversion sequence than an ellipsis conversion sequence
1982 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00001983 //
John McCall1d318332010-01-12 00:44:57 +00001984 // C++0x [over.best.ics]p10:
1985 // For the purpose of ranking implicit conversion sequences as
1986 // described in 13.3.3.2, the ambiguous conversion sequence is
1987 // treated as a user-defined sequence that is indistinguishable
1988 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001989 if (ICS1.getKindRank() < ICS2.getKindRank())
1990 return ImplicitConversionSequence::Better;
1991 else if (ICS2.getKindRank() < ICS1.getKindRank())
1992 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001993
Benjamin Kramerb6eee072010-04-18 12:05:54 +00001994 // The following checks require both conversion sequences to be of
1995 // the same kind.
1996 if (ICS1.getKind() != ICS2.getKind())
1997 return ImplicitConversionSequence::Indistinguishable;
1998
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001999 // Two implicit conversion sequences of the same form are
2000 // indistinguishable conversion sequences unless one of the
2001 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00002002 if (ICS1.isStandard())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002003 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00002004 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002005 // User-defined conversion sequence U1 is a better conversion
2006 // sequence than another user-defined conversion sequence U2 if
2007 // they contain the same user-defined conversion function or
2008 // constructor and if the second standard conversion sequence of
2009 // U1 is better than the second standard conversion sequence of
2010 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002011 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002012 ICS2.UserDefined.ConversionFunction)
2013 return CompareStandardConversionSequences(ICS1.UserDefined.After,
2014 ICS2.UserDefined.After);
2015 }
2016
2017 return ImplicitConversionSequence::Indistinguishable;
2018}
2019
Douglas Gregorad323a82010-01-27 03:51:04 +00002020// Per 13.3.3.2p3, compare the given standard conversion sequences to
2021// determine if one is a proper subset of the other.
2022static ImplicitConversionSequence::CompareKind
2023compareStandardConversionSubsets(ASTContext &Context,
2024 const StandardConversionSequence& SCS1,
2025 const StandardConversionSequence& SCS2) {
2026 ImplicitConversionSequence::CompareKind Result
2027 = ImplicitConversionSequence::Indistinguishable;
2028
2029 if (SCS1.Second != SCS2.Second) {
2030 if (SCS1.Second == ICK_Identity)
2031 Result = ImplicitConversionSequence::Better;
2032 else if (SCS2.Second == ICK_Identity)
2033 Result = ImplicitConversionSequence::Worse;
2034 else
2035 return ImplicitConversionSequence::Indistinguishable;
2036 } else if (!Context.hasSameType(SCS1.getToType(1), SCS2.getToType(1)))
2037 return ImplicitConversionSequence::Indistinguishable;
2038
2039 if (SCS1.Third == SCS2.Third) {
2040 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2041 : ImplicitConversionSequence::Indistinguishable;
2042 }
2043
2044 if (SCS1.Third == ICK_Identity)
2045 return Result == ImplicitConversionSequence::Worse
2046 ? ImplicitConversionSequence::Indistinguishable
2047 : ImplicitConversionSequence::Better;
2048
2049 if (SCS2.Third == ICK_Identity)
2050 return Result == ImplicitConversionSequence::Better
2051 ? ImplicitConversionSequence::Indistinguishable
2052 : ImplicitConversionSequence::Worse;
2053
2054 return ImplicitConversionSequence::Indistinguishable;
2055}
2056
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002057/// CompareStandardConversionSequences - Compare two standard
2058/// conversion sequences to determine whether one is better than the
2059/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002060ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002061Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
2062 const StandardConversionSequence& SCS2)
2063{
2064 // Standard conversion sequence S1 is a better conversion sequence
2065 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2066
2067 // -- S1 is a proper subsequence of S2 (comparing the conversion
2068 // sequences in the canonical form defined by 13.3.3.1.1,
2069 // excluding any Lvalue Transformation; the identity conversion
2070 // sequence is considered to be a subsequence of any
2071 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00002072 if (ImplicitConversionSequence::CompareKind CK
2073 = compareStandardConversionSubsets(Context, SCS1, SCS2))
2074 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002075
2076 // -- the rank of S1 is better than the rank of S2 (by the rules
2077 // defined below), or, if not that,
2078 ImplicitConversionRank Rank1 = SCS1.getRank();
2079 ImplicitConversionRank Rank2 = SCS2.getRank();
2080 if (Rank1 < Rank2)
2081 return ImplicitConversionSequence::Better;
2082 else if (Rank2 < Rank1)
2083 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002084
Douglas Gregor57373262008-10-22 14:17:15 +00002085 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2086 // are indistinguishable unless one of the following rules
2087 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00002088
Douglas Gregor57373262008-10-22 14:17:15 +00002089 // A conversion that is not a conversion of a pointer, or
2090 // pointer to member, to bool is better than another conversion
2091 // that is such a conversion.
2092 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2093 return SCS2.isPointerConversionToBool()
2094 ? ImplicitConversionSequence::Better
2095 : ImplicitConversionSequence::Worse;
2096
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002097 // C++ [over.ics.rank]p4b2:
2098 //
2099 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002100 // conversion of B* to A* is better than conversion of B* to
2101 // void*, and conversion of A* to void* is better than conversion
2102 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00002103 bool SCS1ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002104 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002105 bool SCS2ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002106 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002107 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2108 // Exactly one of the conversion sequences is a conversion to
2109 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002110 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2111 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002112 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2113 // Neither conversion sequence converts to a void pointer; compare
2114 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002115 if (ImplicitConversionSequence::CompareKind DerivedCK
2116 = CompareDerivedToBaseConversions(SCS1, SCS2))
2117 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002118 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2119 // Both conversion sequences are conversions to void
2120 // pointers. Compare the source types to determine if there's an
2121 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00002122 QualType FromType1 = SCS1.getFromType();
2123 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002124
2125 // Adjust the types we're converting from via the array-to-pointer
2126 // conversion, if we need to.
2127 if (SCS1.First == ICK_Array_To_Pointer)
2128 FromType1 = Context.getArrayDecayedType(FromType1);
2129 if (SCS2.First == ICK_Array_To_Pointer)
2130 FromType2 = Context.getArrayDecayedType(FromType2);
2131
Douglas Gregor01919692009-12-13 21:37:05 +00002132 QualType FromPointee1
2133 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2134 QualType FromPointee2
2135 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002136
Douglas Gregor01919692009-12-13 21:37:05 +00002137 if (IsDerivedFrom(FromPointee2, FromPointee1))
2138 return ImplicitConversionSequence::Better;
2139 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2140 return ImplicitConversionSequence::Worse;
2141
2142 // Objective-C++: If one interface is more specific than the
2143 // other, it is the better one.
2144 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2145 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2146 if (FromIface1 && FromIface1) {
2147 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2148 return ImplicitConversionSequence::Better;
2149 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2150 return ImplicitConversionSequence::Worse;
2151 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002152 }
Douglas Gregor57373262008-10-22 14:17:15 +00002153
2154 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2155 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00002156 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00002157 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002158 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00002159
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002160 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002161 // C++0x [over.ics.rank]p3b4:
2162 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2163 // implicit object parameter of a non-static member function declared
2164 // without a ref-qualifier, and S1 binds an rvalue reference to an
2165 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00002166 // FIXME: We don't know if we're dealing with the implicit object parameter,
2167 // or if the member function in this case has a ref qualifier.
2168 // (Of course, we don't have ref qualifiers yet.)
2169 if (SCS1.RRefBinding != SCS2.RRefBinding)
2170 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2171 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002172
2173 // C++ [over.ics.rank]p3b4:
2174 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2175 // which the references refer are the same type except for
2176 // top-level cv-qualifiers, and the type to which the reference
2177 // initialized by S2 refers is more cv-qualified than the type
2178 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00002179 QualType T1 = SCS1.getToType(2);
2180 QualType T2 = SCS2.getToType(2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002181 T1 = Context.getCanonicalType(T1);
2182 T2 = Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002183 Qualifiers T1Quals, T2Quals;
2184 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2185 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2186 if (UnqualT1 == UnqualT2) {
2187 // If the type is an array type, promote the element qualifiers to the type
2188 // for comparison.
2189 if (isa<ArrayType>(T1) && T1Quals)
2190 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2191 if (isa<ArrayType>(T2) && T2Quals)
2192 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002193 if (T2.isMoreQualifiedThan(T1))
2194 return ImplicitConversionSequence::Better;
2195 else if (T1.isMoreQualifiedThan(T2))
2196 return ImplicitConversionSequence::Worse;
2197 }
2198 }
Douglas Gregor57373262008-10-22 14:17:15 +00002199
2200 return ImplicitConversionSequence::Indistinguishable;
2201}
2202
2203/// CompareQualificationConversions - Compares two standard conversion
2204/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00002205/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2206ImplicitConversionSequence::CompareKind
Douglas Gregor57373262008-10-22 14:17:15 +00002207Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump1eb44332009-09-09 15:08:12 +00002208 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00002209 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00002210 // -- S1 and S2 differ only in their qualification conversion and
2211 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2212 // cv-qualification signature of type T1 is a proper subset of
2213 // the cv-qualification signature of type T2, and S1 is not the
2214 // deprecated string literal array-to-pointer conversion (4.2).
2215 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2216 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2217 return ImplicitConversionSequence::Indistinguishable;
2218
2219 // FIXME: the example in the standard doesn't use a qualification
2220 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00002221 QualType T1 = SCS1.getToType(2);
2222 QualType T2 = SCS2.getToType(2);
Douglas Gregor57373262008-10-22 14:17:15 +00002223 T1 = Context.getCanonicalType(T1);
2224 T2 = Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002225 Qualifiers T1Quals, T2Quals;
2226 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2227 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00002228
2229 // If the types are the same, we won't learn anything by unwrapped
2230 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00002231 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00002232 return ImplicitConversionSequence::Indistinguishable;
2233
Chandler Carruth28e318c2009-12-29 07:16:59 +00002234 // If the type is an array type, promote the element qualifiers to the type
2235 // for comparison.
2236 if (isa<ArrayType>(T1) && T1Quals)
2237 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2238 if (isa<ArrayType>(T2) && T2Quals)
2239 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2240
Mike Stump1eb44332009-09-09 15:08:12 +00002241 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00002242 = ImplicitConversionSequence::Indistinguishable;
2243 while (UnwrapSimilarPointerTypes(T1, T2)) {
2244 // Within each iteration of the loop, we check the qualifiers to
2245 // determine if this still looks like a qualification
2246 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002247 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00002248 // until there are no more pointers or pointers-to-members left
2249 // to unwrap. This essentially mimics what
2250 // IsQualificationConversion does, but here we're checking for a
2251 // strict subset of qualifiers.
2252 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2253 // The qualifiers are the same, so this doesn't tell us anything
2254 // about how the sequences rank.
2255 ;
2256 else if (T2.isMoreQualifiedThan(T1)) {
2257 // T1 has fewer qualifiers, so it could be the better sequence.
2258 if (Result == ImplicitConversionSequence::Worse)
2259 // Neither has qualifiers that are a subset of the other's
2260 // qualifiers.
2261 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002262
Douglas Gregor57373262008-10-22 14:17:15 +00002263 Result = ImplicitConversionSequence::Better;
2264 } else if (T1.isMoreQualifiedThan(T2)) {
2265 // T2 has fewer qualifiers, so it could be the better sequence.
2266 if (Result == ImplicitConversionSequence::Better)
2267 // Neither has qualifiers that are a subset of the other's
2268 // qualifiers.
2269 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002270
Douglas Gregor57373262008-10-22 14:17:15 +00002271 Result = ImplicitConversionSequence::Worse;
2272 } else {
2273 // Qualifiers are disjoint.
2274 return ImplicitConversionSequence::Indistinguishable;
2275 }
2276
2277 // If the types after this point are equivalent, we're done.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002278 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00002279 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002280 }
2281
Douglas Gregor57373262008-10-22 14:17:15 +00002282 // Check that the winning standard conversion sequence isn't using
2283 // the deprecated string literal array to pointer conversion.
2284 switch (Result) {
2285 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00002286 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002287 Result = ImplicitConversionSequence::Indistinguishable;
2288 break;
2289
2290 case ImplicitConversionSequence::Indistinguishable:
2291 break;
2292
2293 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00002294 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002295 Result = ImplicitConversionSequence::Indistinguishable;
2296 break;
2297 }
2298
2299 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002300}
2301
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002302/// CompareDerivedToBaseConversions - Compares two standard conversion
2303/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00002304/// various kinds of derived-to-base conversions (C++
2305/// [over.ics.rank]p4b3). As part of these checks, we also look at
2306/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002307ImplicitConversionSequence::CompareKind
2308Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2309 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00002310 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002311 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00002312 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002313 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002314
2315 // Adjust the types we're converting from via the array-to-pointer
2316 // conversion, if we need to.
2317 if (SCS1.First == ICK_Array_To_Pointer)
2318 FromType1 = Context.getArrayDecayedType(FromType1);
2319 if (SCS2.First == ICK_Array_To_Pointer)
2320 FromType2 = Context.getArrayDecayedType(FromType2);
2321
2322 // Canonicalize all of the types.
2323 FromType1 = Context.getCanonicalType(FromType1);
2324 ToType1 = Context.getCanonicalType(ToType1);
2325 FromType2 = Context.getCanonicalType(FromType2);
2326 ToType2 = Context.getCanonicalType(ToType2);
2327
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002328 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002329 //
2330 // If class B is derived directly or indirectly from class A and
2331 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002332 //
2333 // For Objective-C, we let A, B, and C also be Objective-C
2334 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002335
2336 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00002337 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00002338 SCS2.Second == ICK_Pointer_Conversion &&
2339 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2340 FromType1->isPointerType() && FromType2->isPointerType() &&
2341 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002342 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002343 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002344 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002345 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002346 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002347 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002348 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002349 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002350
John McCall183700f2009-09-21 23:43:11 +00002351 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2352 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2353 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
2354 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002355
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002356 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002357 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2358 if (IsDerivedFrom(ToPointee1, ToPointee2))
2359 return ImplicitConversionSequence::Better;
2360 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2361 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00002362
2363 if (ToIface1 && ToIface2) {
2364 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2365 return ImplicitConversionSequence::Better;
2366 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2367 return ImplicitConversionSequence::Worse;
2368 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002369 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002370
2371 // -- conversion of B* to A* is better than conversion of C* to A*,
2372 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2373 if (IsDerivedFrom(FromPointee2, FromPointee1))
2374 return ImplicitConversionSequence::Better;
2375 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2376 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00002377
Douglas Gregorcb7de522008-11-26 23:31:11 +00002378 if (FromIface1 && FromIface2) {
2379 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2380 return ImplicitConversionSequence::Better;
2381 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2382 return ImplicitConversionSequence::Worse;
2383 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002384 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002385 }
2386
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002387 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002388 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2389 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2390 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2391 const MemberPointerType * FromMemPointer1 =
2392 FromType1->getAs<MemberPointerType>();
2393 const MemberPointerType * ToMemPointer1 =
2394 ToType1->getAs<MemberPointerType>();
2395 const MemberPointerType * FromMemPointer2 =
2396 FromType2->getAs<MemberPointerType>();
2397 const MemberPointerType * ToMemPointer2 =
2398 ToType2->getAs<MemberPointerType>();
2399 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2400 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2401 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2402 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2403 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2404 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2405 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2406 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002407 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002408 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2409 if (IsDerivedFrom(ToPointee1, ToPointee2))
2410 return ImplicitConversionSequence::Worse;
2411 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2412 return ImplicitConversionSequence::Better;
2413 }
2414 // conversion of B::* to C::* is better than conversion of A::* to C::*
2415 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2416 if (IsDerivedFrom(FromPointee1, FromPointee2))
2417 return ImplicitConversionSequence::Better;
2418 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2419 return ImplicitConversionSequence::Worse;
2420 }
2421 }
2422
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002423 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002424 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00002425 // -- binding of an expression of type C to a reference of type
2426 // B& is better than binding an expression of type C to a
2427 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002428 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2429 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002430 if (IsDerivedFrom(ToType1, ToType2))
2431 return ImplicitConversionSequence::Better;
2432 else if (IsDerivedFrom(ToType2, ToType1))
2433 return ImplicitConversionSequence::Worse;
2434 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002435
Douglas Gregor225c41e2008-11-03 19:09:14 +00002436 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00002437 // -- binding of an expression of type B to a reference of type
2438 // A& is better than binding an expression of type C to a
2439 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002440 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2441 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002442 if (IsDerivedFrom(FromType2, FromType1))
2443 return ImplicitConversionSequence::Better;
2444 else if (IsDerivedFrom(FromType1, FromType2))
2445 return ImplicitConversionSequence::Worse;
2446 }
2447 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002448
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002449 return ImplicitConversionSequence::Indistinguishable;
2450}
2451
Douglas Gregorabe183d2010-04-13 16:31:36 +00002452/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2453/// determine whether they are reference-related,
2454/// reference-compatible, reference-compatible with added
2455/// qualification, or incompatible, for use in C++ initialization by
2456/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2457/// type, and the first type (T1) is the pointee type of the reference
2458/// type being initialized.
2459Sema::ReferenceCompareResult
2460Sema::CompareReferenceRelationship(SourceLocation Loc,
2461 QualType OrigT1, QualType OrigT2,
2462 bool& DerivedToBase) {
2463 assert(!OrigT1->isReferenceType() &&
2464 "T1 must be the pointee type of the reference type");
2465 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2466
2467 QualType T1 = Context.getCanonicalType(OrigT1);
2468 QualType T2 = Context.getCanonicalType(OrigT2);
2469 Qualifiers T1Quals, T2Quals;
2470 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2471 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2472
2473 // C++ [dcl.init.ref]p4:
2474 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2475 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2476 // T1 is a base class of T2.
2477 if (UnqualT1 == UnqualT2)
2478 DerivedToBase = false;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002479 else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00002480 IsDerivedFrom(UnqualT2, UnqualT1))
2481 DerivedToBase = true;
2482 else
2483 return Ref_Incompatible;
2484
2485 // At this point, we know that T1 and T2 are reference-related (at
2486 // least).
2487
2488 // If the type is an array type, promote the element qualifiers to the type
2489 // for comparison.
2490 if (isa<ArrayType>(T1) && T1Quals)
2491 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2492 if (isa<ArrayType>(T2) && T2Quals)
2493 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2494
2495 // C++ [dcl.init.ref]p4:
2496 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2497 // reference-related to T2 and cv1 is the same cv-qualification
2498 // as, or greater cv-qualification than, cv2. For purposes of
2499 // overload resolution, cases for which cv1 is greater
2500 // cv-qualification than cv2 are identified as
2501 // reference-compatible with added qualification (see 13.3.3.2).
2502 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2503 return Ref_Compatible;
2504 else if (T1.isMoreQualifiedThan(T2))
2505 return Ref_Compatible_With_Added_Qualification;
2506 else
2507 return Ref_Related;
2508}
2509
2510/// \brief Compute an implicit conversion sequence for reference
2511/// initialization.
2512static ImplicitConversionSequence
2513TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2514 SourceLocation DeclLoc,
2515 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00002516 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002517 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2518
2519 // Most paths end in a failed conversion.
2520 ImplicitConversionSequence ICS;
2521 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2522
2523 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2524 QualType T2 = Init->getType();
2525
2526 // If the initializer is the address of an overloaded function, try
2527 // to resolve the overloaded function. If all goes well, T2 is the
2528 // type of the resulting function.
2529 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2530 DeclAccessPair Found;
2531 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2532 false, Found))
2533 T2 = Fn->getType();
2534 }
2535
2536 // Compute some basic properties of the types and the initializer.
2537 bool isRValRef = DeclType->isRValueReferenceType();
2538 bool DerivedToBase = false;
Douglas Gregor23ef6c02010-04-16 17:45:54 +00002539 Expr::isLvalueResult InitLvalue = Init->isLvalue(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002540 Sema::ReferenceCompareResult RefRelationship
2541 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
2542
Douglas Gregorabe183d2010-04-13 16:31:36 +00002543
2544 // C++ [over.ics.ref]p3:
2545 // Except for an implicit object parameter, for which see 13.3.1,
2546 // a standard conversion sequence cannot be formed if it requires
2547 // binding an lvalue reference to non-const to an rvalue or
2548 // binding an rvalue reference to an lvalue.
Douglas Gregor66821b52010-04-18 09:22:00 +00002549 //
2550 // FIXME: DPG doesn't trust this code. It seems far too early to
2551 // abort because of a binding of an rvalue reference to an lvalue.
Douglas Gregorabe183d2010-04-13 16:31:36 +00002552 if (isRValRef && InitLvalue == Expr::LV_Valid)
2553 return ICS;
2554
Douglas Gregor66821b52010-04-18 09:22:00 +00002555 // C++0x [dcl.init.ref]p16:
2556 // A reference to type "cv1 T1" is initialized by an expression
2557 // of type "cv2 T2" as follows:
2558
2559 // -- If the initializer expression
Douglas Gregorabe183d2010-04-13 16:31:36 +00002560 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2561 // reference-compatible with "cv2 T2," or
2562 //
2563 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2564 if (InitLvalue == Expr::LV_Valid &&
2565 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2566 // C++ [over.ics.ref]p1:
2567 // When a parameter of reference type binds directly (8.5.3)
2568 // to an argument expression, the implicit conversion sequence
2569 // is the identity conversion, unless the argument expression
2570 // has a type that is a derived class of the parameter type,
2571 // in which case the implicit conversion sequence is a
2572 // derived-to-base Conversion (13.3.3.1).
2573 ICS.setStandard();
2574 ICS.Standard.First = ICK_Identity;
2575 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2576 ICS.Standard.Third = ICK_Identity;
2577 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2578 ICS.Standard.setToType(0, T2);
2579 ICS.Standard.setToType(1, T1);
2580 ICS.Standard.setToType(2, T1);
2581 ICS.Standard.ReferenceBinding = true;
2582 ICS.Standard.DirectBinding = true;
2583 ICS.Standard.RRefBinding = false;
2584 ICS.Standard.CopyConstructor = 0;
2585
2586 // Nothing more to do: the inaccessibility/ambiguity check for
2587 // derived-to-base conversions is suppressed when we're
2588 // computing the implicit conversion sequence (C++
2589 // [over.best.ics]p2).
2590 return ICS;
2591 }
2592
2593 // -- has a class type (i.e., T2 is a class type), where T1 is
2594 // not reference-related to T2, and can be implicitly
2595 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2596 // is reference-compatible with "cv3 T3" 92) (this
2597 // conversion is selected by enumerating the applicable
2598 // conversion functions (13.3.1.6) and choosing the best
2599 // one through overload resolution (13.3)),
2600 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
2601 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2602 RefRelationship == Sema::Ref_Incompatible) {
2603 CXXRecordDecl *T2RecordDecl
2604 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2605
2606 OverloadCandidateSet CandidateSet(DeclLoc);
2607 const UnresolvedSetImpl *Conversions
2608 = T2RecordDecl->getVisibleConversionFunctions();
2609 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2610 E = Conversions->end(); I != E; ++I) {
2611 NamedDecl *D = *I;
2612 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2613 if (isa<UsingShadowDecl>(D))
2614 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2615
2616 FunctionTemplateDecl *ConvTemplate
2617 = dyn_cast<FunctionTemplateDecl>(D);
2618 CXXConversionDecl *Conv;
2619 if (ConvTemplate)
2620 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2621 else
2622 Conv = cast<CXXConversionDecl>(D);
2623
2624 // If the conversion function doesn't return a reference type,
2625 // it can't be considered for this conversion.
2626 if (Conv->getConversionType()->isLValueReferenceType() &&
2627 (AllowExplicit || !Conv->isExplicit())) {
2628 if (ConvTemplate)
2629 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2630 Init, DeclType, CandidateSet);
2631 else
2632 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2633 DeclType, CandidateSet);
2634 }
2635 }
2636
2637 OverloadCandidateSet::iterator Best;
2638 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2639 case OR_Success:
2640 // C++ [over.ics.ref]p1:
2641 //
2642 // [...] If the parameter binds directly to the result of
2643 // applying a conversion function to the argument
2644 // expression, the implicit conversion sequence is a
2645 // user-defined conversion sequence (13.3.3.1.2), with the
2646 // second standard conversion sequence either an identity
2647 // conversion or, if the conversion function returns an
2648 // entity of a type that is a derived class of the parameter
2649 // type, a derived-to-base Conversion.
2650 if (!Best->FinalConversion.DirectBinding)
2651 break;
2652
2653 ICS.setUserDefined();
2654 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2655 ICS.UserDefined.After = Best->FinalConversion;
2656 ICS.UserDefined.ConversionFunction = Best->Function;
2657 ICS.UserDefined.EllipsisConversion = false;
2658 assert(ICS.UserDefined.After.ReferenceBinding &&
2659 ICS.UserDefined.After.DirectBinding &&
2660 "Expected a direct reference binding!");
2661 return ICS;
2662
2663 case OR_Ambiguous:
2664 ICS.setAmbiguous();
2665 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2666 Cand != CandidateSet.end(); ++Cand)
2667 if (Cand->Viable)
2668 ICS.Ambiguous.addConversion(Cand->Function);
2669 return ICS;
2670
2671 case OR_No_Viable_Function:
2672 case OR_Deleted:
2673 // There was no suitable conversion, or we found a deleted
2674 // conversion; continue with other checks.
2675 break;
2676 }
2677 }
2678
2679 // -- Otherwise, the reference shall be to a non-volatile const
2680 // type (i.e., cv1 shall be const), or the reference shall be an
2681 // rvalue reference and the initializer expression shall be an rvalue.
Douglas Gregor66821b52010-04-18 09:22:00 +00002682 //
2683 // We actually handle one oddity of C++ [over.ics.ref] at this
2684 // point, which is that, due to p2 (which short-circuits reference
2685 // binding by only attempting a simple conversion for non-direct
2686 // bindings) and p3's strange wording, we allow a const volatile
2687 // reference to bind to an rvalue. Hence the check for the presence
2688 // of "const" rather than checking for "const" being the only
2689 // qualifier.
2690 if (!isRValRef && !T1.isConstQualified())
Douglas Gregorabe183d2010-04-13 16:31:36 +00002691 return ICS;
2692
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002693 // -- if T2 is a class type and
2694 // -- the initializer expression is an rvalue and "cv1 T1"
2695 // is reference-compatible with "cv2 T2," or
Douglas Gregorabe183d2010-04-13 16:31:36 +00002696 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002697 // -- T1 is not reference-related to T2 and the initializer
2698 // expression can be implicitly converted to an rvalue
2699 // of type "cv3 T3" (this conversion is selected by
2700 // enumerating the applicable conversion functions
2701 // (13.3.1.6) and choosing the best one through overload
2702 // resolution (13.3)),
Douglas Gregorabe183d2010-04-13 16:31:36 +00002703 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002704 // then the reference is bound to the initializer
2705 // expression rvalue in the first case and to the object
2706 // that is the result of the conversion in the second case
2707 // (or, in either case, to the appropriate base class
2708 // subobject of the object).
Douglas Gregorabe183d2010-04-13 16:31:36 +00002709 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002710 // We're only checking the first case here, which is a direct
2711 // binding in C++0x but not in C++03.
Douglas Gregorabe183d2010-04-13 16:31:36 +00002712 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
2713 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2714 ICS.setStandard();
2715 ICS.Standard.First = ICK_Identity;
2716 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2717 ICS.Standard.Third = ICK_Identity;
2718 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2719 ICS.Standard.setToType(0, T2);
2720 ICS.Standard.setToType(1, T1);
2721 ICS.Standard.setToType(2, T1);
2722 ICS.Standard.ReferenceBinding = true;
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002723 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002724 ICS.Standard.RRefBinding = isRValRef;
2725 ICS.Standard.CopyConstructor = 0;
2726 return ICS;
2727 }
2728
2729 // -- Otherwise, a temporary of type "cv1 T1" is created and
2730 // initialized from the initializer expression using the
2731 // rules for a non-reference copy initialization (8.5). The
2732 // reference is then bound to the temporary. If T1 is
2733 // reference-related to T2, cv1 must be the same
2734 // cv-qualification as, or greater cv-qualification than,
2735 // cv2; otherwise, the program is ill-formed.
2736 if (RefRelationship == Sema::Ref_Related) {
2737 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2738 // we would be reference-compatible or reference-compatible with
2739 // added qualification. But that wasn't the case, so the reference
2740 // initialization fails.
2741 return ICS;
2742 }
2743
2744 // If at least one of the types is a class type, the types are not
2745 // related, and we aren't allowed any user conversions, the
2746 // reference binding fails. This case is important for breaking
2747 // recursion, since TryImplicitConversion below will attempt to
2748 // create a temporary through the use of a copy constructor.
2749 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2750 (T1->isRecordType() || T2->isRecordType()))
2751 return ICS;
2752
2753 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00002754 // When a parameter of reference type is not bound directly to
2755 // an argument expression, the conversion sequence is the one
2756 // required to convert the argument expression to the
2757 // underlying type of the reference according to
2758 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2759 // to copy-initializing a temporary of the underlying type with
2760 // the argument expression. Any difference in top-level
2761 // cv-qualification is subsumed by the initialization itself
2762 // and does not constitute a conversion.
2763 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2764 /*AllowExplicit=*/false,
Douglas Gregorabe183d2010-04-13 16:31:36 +00002765 /*InOverloadResolution=*/false);
2766
2767 // Of course, that's still a reference binding.
2768 if (ICS.isStandard()) {
2769 ICS.Standard.ReferenceBinding = true;
2770 ICS.Standard.RRefBinding = isRValRef;
2771 } else if (ICS.isUserDefined()) {
2772 ICS.UserDefined.After.ReferenceBinding = true;
2773 ICS.UserDefined.After.RRefBinding = isRValRef;
2774 }
2775 return ICS;
2776}
2777
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002778/// TryCopyInitialization - Try to copy-initialize a value of type
2779/// ToType from the expression From. Return the implicit conversion
2780/// sequence required to pass this argument, which may be a bad
2781/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00002782/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00002783/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00002784static ImplicitConversionSequence
2785TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregorb7f9e6a2010-04-16 17:53:55 +00002786 bool SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00002787 bool InOverloadResolution) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002788 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00002789 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00002790 /*FIXME:*/From->getLocStart(),
2791 SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00002792 /*AllowExplicit=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002793
Douglas Gregor74eb6582010-04-16 17:51:22 +00002794 return S.TryImplicitConversion(From, ToType,
2795 SuppressUserConversions,
2796 /*AllowExplicit=*/false,
Douglas Gregor74eb6582010-04-16 17:51:22 +00002797 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002798}
2799
Douglas Gregor96176b32008-11-18 23:14:02 +00002800/// TryObjectArgumentInitialization - Try to initialize the object
2801/// parameter of the given member function (@c Method) from the
2802/// expression @p From.
2803ImplicitConversionSequence
John McCall651f3ee2010-01-14 03:28:57 +00002804Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall701c89e2009-12-03 04:06:58 +00002805 CXXMethodDecl *Method,
2806 CXXRecordDecl *ActingContext) {
2807 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002808 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2809 // const volatile object.
2810 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2811 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2812 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00002813
2814 // Set up the conversion sequence as a "bad" conversion, to allow us
2815 // to exit early.
2816 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00002817
2818 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00002819 QualType FromType = OrigFromType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002820 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00002821 FromType = PT->getPointeeType();
2822
2823 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002824
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002825 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor96176b32008-11-18 23:14:02 +00002826 // where X is the class of which the function is a member
2827 // (C++ [over.match.funcs]p4). However, when finding an implicit
2828 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00002829 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00002830 // (C++ [over.match.funcs]p5). We perform a simplified version of
2831 // reference binding here, that allows class rvalues to bind to
2832 // non-constant references.
2833
2834 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2835 // with the implicit object parameter (C++ [over.match.funcs]p5).
2836 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00002837 if (ImplicitParamType.getCVRQualifiers()
2838 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00002839 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00002840 ICS.setBad(BadConversionSequence::bad_qualifiers,
2841 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002842 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00002843 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002844
2845 // Check that we have either the same type or a derived type. It
2846 // affects the conversion rank.
2847 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00002848 ImplicitConversionKind SecondKind;
2849 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2850 SecondKind = ICK_Identity;
2851 } else if (IsDerivedFrom(FromType, ClassType))
2852 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00002853 else {
John McCallb1bdc622010-02-25 01:37:24 +00002854 ICS.setBad(BadConversionSequence::unrelated_class,
2855 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002856 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00002857 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002858
2859 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00002860 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00002861 ICS.Standard.setAsIdentityConversion();
2862 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00002863 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00002864 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002865 ICS.Standard.ReferenceBinding = true;
2866 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00002867 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002868 return ICS;
2869}
2870
2871/// PerformObjectArgumentInitialization - Perform initialization of
2872/// the implicit object parameter for the given Method with the given
2873/// expression.
2874bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00002875Sema::PerformObjectArgumentInitialization(Expr *&From,
2876 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00002877 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002878 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002879 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00002880 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00002881 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002882
Ted Kremenek6217b802009-07-29 21:53:49 +00002883 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002884 FromRecordType = PT->getPointeeType();
2885 DestType = Method->getThisType(Context);
2886 } else {
2887 FromRecordType = From->getType();
2888 DestType = ImplicitParamRecordType;
2889 }
2890
John McCall701c89e2009-12-03 04:06:58 +00002891 // Note that we always use the true parent context when performing
2892 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002893 ImplicitConversionSequence ICS
John McCall701c89e2009-12-03 04:06:58 +00002894 = TryObjectArgumentInitialization(From->getType(), Method,
2895 Method->getParent());
John McCall1d318332010-01-12 00:44:57 +00002896 if (ICS.isBad())
Douglas Gregor96176b32008-11-18 23:14:02 +00002897 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002898 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00002899 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002900
Douglas Gregor5fccd362010-03-03 23:55:11 +00002901 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall6bb80172010-03-30 21:47:33 +00002902 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor96176b32008-11-18 23:14:02 +00002903
Douglas Gregor5fccd362010-03-03 23:55:11 +00002904 if (!Context.hasSameType(From->getType(), DestType))
Anders Carlssonf1b48b72010-04-24 16:57:13 +00002905 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
2906 /*isLvalue=*/!From->getType()->isPointerType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002907 return false;
2908}
2909
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002910/// TryContextuallyConvertToBool - Attempt to contextually convert the
2911/// expression From to bool (C++0x [conv]p3).
2912ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00002913 // FIXME: This is pretty broken.
Mike Stump1eb44332009-09-09 15:08:12 +00002914 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002915 // FIXME: Are these flags correct?
2916 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00002917 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00002918 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002919}
2920
2921/// PerformContextuallyConvertToBool - Perform a contextual conversion
2922/// of the expression From to bool (C++0x [conv]p3).
2923bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2924 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall1d318332010-01-12 00:44:57 +00002925 if (!ICS.isBad())
2926 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002927
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002928 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002929 return Diag(From->getSourceRange().getBegin(),
2930 diag::err_typecheck_bool_condition)
2931 << From->getType() << From->getSourceRange();
2932 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002933}
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00002934
2935/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
2936/// expression From to 'id'.
2937ImplicitConversionSequence Sema::TryContextuallyConvertToObjCId(Expr *From) {
2938 QualType Ty = Context.getObjCObjectPointerType(Context.ObjCBuiltinIdTy);
2939 return TryImplicitConversion(From, Ty,
2940 // FIXME: Are these flags correct?
2941 /*SuppressUserConversions=*/false,
2942 /*AllowExplicit=*/true,
2943 /*InOverloadResolution=*/false);
2944}
2945
2946/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
2947/// of the expression From to 'id'.
2948bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
2949 QualType Ty = Context.getObjCObjectPointerType(Context.ObjCBuiltinIdTy);
2950 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(From);
2951 if (!ICS.isBad())
2952 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
2953 return true;
2954}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002955
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002956/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00002957/// candidate functions, using the given function call arguments. If
2958/// @p SuppressUserConversions, then don't allow user-defined
2959/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002960///
2961/// \para PartialOverloading true if we are performing "partial" overloading
2962/// based on an incomplete set of function arguments. This feature is used by
2963/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00002964void
2965Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00002966 DeclAccessPair FoundDecl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002967 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00002968 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00002969 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00002970 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00002971 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00002972 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002973 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00002974 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00002975 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00002976
Douglas Gregor88a35142008-12-22 05:46:06 +00002977 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002978 if (!isa<CXXConstructorDecl>(Method)) {
2979 // If we get here, it's because we're calling a member function
2980 // that is named without a member access expression (e.g.,
2981 // "this->f") that was either written explicitly or created
2982 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00002983 // function, e.g., X::f(). We use an empty type for the implied
2984 // object argument (C++ [over.call.func]p3), and the acting context
2985 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00002986 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall701c89e2009-12-03 04:06:58 +00002987 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00002988 SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00002989 return;
2990 }
2991 // We treat a constructor like a non-member function, since its object
2992 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00002993 }
2994
Douglas Gregorfd476482009-11-13 23:59:09 +00002995 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00002996 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00002997
Douglas Gregor7edfb692009-11-23 12:27:39 +00002998 // Overload resolution is always an unevaluated context.
2999 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3000
Douglas Gregor66724ea2009-11-14 01:20:54 +00003001 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3002 // C++ [class.copy]p3:
3003 // A member function template is never instantiated to perform the copy
3004 // of a class object to an object of its class type.
3005 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3006 if (NumArgs == 1 &&
3007 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor12116062010-02-21 18:30:38 +00003008 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3009 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00003010 return;
3011 }
3012
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003013 // Add this candidate
3014 CandidateSet.push_back(OverloadCandidate());
3015 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003016 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003017 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00003018 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003019 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003020 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003021
3022 unsigned NumArgsInProto = Proto->getNumArgs();
3023
3024 // (C++ 13.3.2p2): A candidate function having fewer than m
3025 // parameters is viable only if it has an ellipsis in its parameter
3026 // list (8.3.5).
Douglas Gregor5bd1a112009-09-23 14:56:09 +00003027 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3028 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003029 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003030 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003031 return;
3032 }
3033
3034 // (C++ 13.3.2p2): A candidate function having more than m parameters
3035 // is viable only if the (m+1)st parameter has a default argument
3036 // (8.3.6). For the purposes of overload resolution, the
3037 // parameter list is truncated on the right, so that there are
3038 // exactly m parameters.
3039 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003040 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003041 // Not enough arguments.
3042 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003043 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003044 return;
3045 }
3046
3047 // Determine the implicit conversion sequences for each of the
3048 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003049 Candidate.Conversions.resize(NumArgs);
3050 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3051 if (ArgIdx < NumArgsInProto) {
3052 // (C++ 13.3.2p3): for F to be a viable function, there shall
3053 // exist for each argument an implicit conversion sequence
3054 // (13.3.3.1) that converts that argument to the corresponding
3055 // parameter of F.
3056 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003057 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003058 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003059 SuppressUserConversions,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003060 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003061 if (Candidate.Conversions[ArgIdx].isBad()) {
3062 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003063 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00003064 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00003065 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003066 } else {
3067 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3068 // argument for which there is no corresponding parameter is
3069 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003070 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003071 }
3072 }
3073}
3074
Douglas Gregor063daf62009-03-13 18:40:31 +00003075/// \brief Add all of the function declarations in the given function set to
3076/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00003077void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00003078 Expr **Args, unsigned NumArgs,
3079 OverloadCandidateSet& CandidateSet,
3080 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00003081 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00003082 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3083 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003084 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003085 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003086 cast<CXXMethodDecl>(FD)->getParent(),
3087 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003088 CandidateSet, SuppressUserConversions);
3089 else
John McCall9aa472c2010-03-19 07:35:19 +00003090 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00003091 SuppressUserConversions);
3092 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003093 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00003094 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3095 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003096 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003097 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00003098 /*FIXME: explicit args */ 0,
John McCall701c89e2009-12-03 04:06:58 +00003099 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003100 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00003101 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00003102 else
John McCall9aa472c2010-03-19 07:35:19 +00003103 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCalld5532b62009-11-23 01:53:49 +00003104 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00003105 Args, NumArgs, CandidateSet,
3106 SuppressUserConversions);
3107 }
Douglas Gregor364e0212009-06-27 21:05:07 +00003108 }
Douglas Gregor063daf62009-03-13 18:40:31 +00003109}
3110
John McCall314be4e2009-11-17 07:50:12 +00003111/// AddMethodCandidate - Adds a named decl (which is some kind of
3112/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00003113void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003114 QualType ObjectType,
John McCall314be4e2009-11-17 07:50:12 +00003115 Expr **Args, unsigned NumArgs,
3116 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003117 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00003118 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003119 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00003120
3121 if (isa<UsingShadowDecl>(Decl))
3122 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3123
3124 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3125 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3126 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00003127 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3128 /*ExplicitArgs*/ 0,
John McCall701c89e2009-12-03 04:06:58 +00003129 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00003130 CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003131 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003132 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003133 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall701c89e2009-12-03 04:06:58 +00003134 ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003135 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003136 }
3137}
3138
Douglas Gregor96176b32008-11-18 23:14:02 +00003139/// AddMethodCandidate - Adds the given C++ member function to the set
3140/// of candidate functions, using the given function call arguments
3141/// and the object argument (@c Object). For example, in a call
3142/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3143/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3144/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00003145/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00003146void
John McCall9aa472c2010-03-19 07:35:19 +00003147Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003148 CXXRecordDecl *ActingContext, QualType ObjectType,
3149 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00003150 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003151 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00003152 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003153 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00003154 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003155 assert(!isa<CXXConstructorDecl>(Method) &&
3156 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00003157
Douglas Gregor3f396022009-09-28 04:47:19 +00003158 if (!CandidateSet.isNewCandidate(Method))
3159 return;
3160
Douglas Gregor7edfb692009-11-23 12:27:39 +00003161 // Overload resolution is always an unevaluated context.
3162 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3163
Douglas Gregor96176b32008-11-18 23:14:02 +00003164 // Add this candidate
3165 CandidateSet.push_back(OverloadCandidate());
3166 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003167 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00003168 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003169 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003170 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003171
3172 unsigned NumArgsInProto = Proto->getNumArgs();
3173
3174 // (C++ 13.3.2p2): A candidate function having fewer than m
3175 // parameters is viable only if it has an ellipsis in its parameter
3176 // list (8.3.5).
3177 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3178 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003179 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003180 return;
3181 }
3182
3183 // (C++ 13.3.2p2): A candidate function having more than m parameters
3184 // is viable only if the (m+1)st parameter has a default argument
3185 // (8.3.6). For the purposes of overload resolution, the
3186 // parameter list is truncated on the right, so that there are
3187 // exactly m parameters.
3188 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3189 if (NumArgs < MinRequiredArgs) {
3190 // Not enough arguments.
3191 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003192 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003193 return;
3194 }
3195
3196 Candidate.Viable = true;
3197 Candidate.Conversions.resize(NumArgs + 1);
3198
John McCall701c89e2009-12-03 04:06:58 +00003199 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00003200 // The implicit object argument is ignored.
3201 Candidate.IgnoreObjectArgument = true;
3202 else {
3203 // Determine the implicit conversion sequence for the object
3204 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00003205 Candidate.Conversions[0]
3206 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00003207 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003208 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003209 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00003210 return;
3211 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003212 }
3213
3214 // Determine the implicit conversion sequences for each of the
3215 // arguments.
3216 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3217 if (ArgIdx < NumArgsInProto) {
3218 // (C++ 13.3.2p3): for F to be a viable function, there shall
3219 // exist for each argument an implicit conversion sequence
3220 // (13.3.3.1) that converts that argument to the corresponding
3221 // parameter of F.
3222 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003223 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003224 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003225 SuppressUserConversions,
Anders Carlsson08972922009-08-28 15:33:32 +00003226 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003227 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00003228 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003229 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00003230 break;
3231 }
3232 } else {
3233 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3234 // argument for which there is no corresponding parameter is
3235 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003236 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00003237 }
3238 }
3239}
Douglas Gregora9333192010-05-08 17:41:32 +00003240
Douglas Gregor6b906862009-08-21 00:16:32 +00003241/// \brief Add a C++ member function template as a candidate to the candidate
3242/// set, using template argument deduction to produce an appropriate member
3243/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003244void
Douglas Gregor6b906862009-08-21 00:16:32 +00003245Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00003246 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003247 CXXRecordDecl *ActingContext,
John McCalld5532b62009-11-23 01:53:49 +00003248 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00003249 QualType ObjectType,
3250 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003251 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003252 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003253 if (!CandidateSet.isNewCandidate(MethodTmpl))
3254 return;
3255
Douglas Gregor6b906862009-08-21 00:16:32 +00003256 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003257 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00003258 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003259 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00003260 // candidate functions in the usual way.113) A given name can refer to one
3261 // or more function templates and also to a set of overloaded non-template
3262 // functions. In such a case, the candidate functions generated from each
3263 // function template are combined with the set of non-template candidate
3264 // functions.
John McCall5769d612010-02-08 23:07:23 +00003265 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00003266 FunctionDecl *Specialization = 0;
3267 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003268 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003269 Args, NumArgs, Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003270 CandidateSet.push_back(OverloadCandidate());
3271 OverloadCandidate &Candidate = CandidateSet.back();
3272 Candidate.FoundDecl = FoundDecl;
3273 Candidate.Function = MethodTmpl->getTemplatedDecl();
3274 Candidate.Viable = false;
3275 Candidate.FailureKind = ovl_fail_bad_deduction;
3276 Candidate.IsSurrogate = false;
3277 Candidate.IgnoreObjectArgument = false;
3278 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3279 Info);
3280 return;
3281 }
Mike Stump1eb44332009-09-09 15:08:12 +00003282
Douglas Gregor6b906862009-08-21 00:16:32 +00003283 // Add the function template specialization produced by template argument
3284 // deduction as a candidate.
3285 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00003286 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00003287 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00003288 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003289 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003290 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00003291}
3292
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003293/// \brief Add a C++ function template specialization as a candidate
3294/// in the candidate set, using template argument deduction to produce
3295/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003296void
Douglas Gregore53060f2009-06-25 22:08:12 +00003297Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003298 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00003299 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00003300 Expr **Args, unsigned NumArgs,
3301 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003302 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003303 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3304 return;
3305
Douglas Gregore53060f2009-06-25 22:08:12 +00003306 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003307 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00003308 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003309 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00003310 // candidate functions in the usual way.113) A given name can refer to one
3311 // or more function templates and also to a set of overloaded non-template
3312 // functions. In such a case, the candidate functions generated from each
3313 // function template are combined with the set of non-template candidate
3314 // functions.
John McCall5769d612010-02-08 23:07:23 +00003315 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00003316 FunctionDecl *Specialization = 0;
3317 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003318 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003319 Args, NumArgs, Specialization, Info)) {
John McCall578b69b2009-12-16 08:11:27 +00003320 CandidateSet.push_back(OverloadCandidate());
3321 OverloadCandidate &Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003322 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00003323 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3324 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003325 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00003326 Candidate.IsSurrogate = false;
3327 Candidate.IgnoreObjectArgument = false;
Douglas Gregorff5adac2010-05-08 20:18:54 +00003328 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3329 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00003330 return;
3331 }
Mike Stump1eb44332009-09-09 15:08:12 +00003332
Douglas Gregore53060f2009-06-25 22:08:12 +00003333 // Add the function template specialization produced by template argument
3334 // deduction as a candidate.
3335 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003336 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003337 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00003338}
Mike Stump1eb44332009-09-09 15:08:12 +00003339
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003340/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00003341/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003342/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00003343/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003344/// (which may or may not be the same type as the type that the
3345/// conversion function produces).
3346void
3347Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003348 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003349 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003350 Expr *From, QualType ToType,
3351 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003352 assert(!Conversion->getDescribedFunctionTemplate() &&
3353 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003354 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00003355 if (!CandidateSet.isNewCandidate(Conversion))
3356 return;
3357
Douglas Gregor7edfb692009-11-23 12:27:39 +00003358 // Overload resolution is always an unevaluated context.
3359 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3360
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003361 // Add this candidate
3362 CandidateSet.push_back(OverloadCandidate());
3363 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003364 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003365 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003366 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003367 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003368 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003369 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003370 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003371
Douglas Gregor96176b32008-11-18 23:14:02 +00003372 // Determine the implicit conversion sequence for the implicit
3373 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003374 Candidate.Viable = true;
3375 Candidate.Conversions.resize(1);
John McCall701c89e2009-12-03 04:06:58 +00003376 Candidate.Conversions[0]
3377 = TryObjectArgumentInitialization(From->getType(), Conversion,
3378 ActingContext);
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00003379 // Conversion functions to a different type in the base class is visible in
3380 // the derived class. So, a derived to base conversion should not participate
3381 // in overload resolution.
3382 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
3383 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall1d318332010-01-12 00:44:57 +00003384 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003385 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003386 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003387 return;
3388 }
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003389
3390 // We won't go through a user-define type conversion function to convert a
3391 // derived to base as such conversions are given Conversion Rank. They only
3392 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3393 QualType FromCanon
3394 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3395 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3396 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3397 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003398 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003399 return;
3400 }
3401
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003402 // To determine what the conversion from the result of calling the
3403 // conversion function to the type we're eventually trying to
3404 // convert to (ToType), we need to synthesize a call to the
3405 // conversion function and attempt copy initialization from it. This
3406 // makes sure that we get the right semantics with respect to
3407 // lvalues/rvalues and the type. Fortunately, we can allocate this
3408 // call on the stack and we don't need its arguments to be
3409 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00003410 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003411 From->getLocStart());
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003412 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman73c39ab2009-10-20 08:27:19 +00003413 CastExpr::CK_FunctionToPointerDecay,
Anders Carlssonf1b48b72010-04-24 16:57:13 +00003414 &ConversionRef, CXXBaseSpecifierArray(), false);
Mike Stump1eb44332009-09-09 15:08:12 +00003415
3416 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00003417 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3418 // allocator).
Mike Stump1eb44332009-09-09 15:08:12 +00003419 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003420 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003421 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00003422 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00003423 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00003424 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003425 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00003426
John McCall1d318332010-01-12 00:44:57 +00003427 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003428 case ImplicitConversionSequence::StandardConversion:
3429 Candidate.FinalConversion = ICS.Standard;
Douglas Gregorc520c842010-04-12 23:42:09 +00003430
3431 // C++ [over.ics.user]p3:
3432 // If the user-defined conversion is specified by a specialization of a
3433 // conversion function template, the second standard conversion sequence
3434 // shall have exact match rank.
3435 if (Conversion->getPrimaryTemplate() &&
3436 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3437 Candidate.Viable = false;
3438 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3439 }
3440
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003441 break;
3442
3443 case ImplicitConversionSequence::BadConversion:
3444 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003445 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003446 break;
3447
3448 default:
Mike Stump1eb44332009-09-09 15:08:12 +00003449 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003450 "Can only end up with a standard conversion sequence or failure");
3451 }
3452}
3453
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003454/// \brief Adds a conversion function template specialization
3455/// candidate to the overload set, using template argument deduction
3456/// to deduce the template arguments of the conversion function
3457/// template from the type that we are converting to (C++
3458/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00003459void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003460Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003461 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003462 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003463 Expr *From, QualType ToType,
3464 OverloadCandidateSet &CandidateSet) {
3465 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3466 "Only conversion function templates permitted here");
3467
Douglas Gregor3f396022009-09-28 04:47:19 +00003468 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3469 return;
3470
John McCall5769d612010-02-08 23:07:23 +00003471 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003472 CXXConversionDecl *Specialization = 0;
3473 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00003474 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003475 Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003476 CandidateSet.push_back(OverloadCandidate());
3477 OverloadCandidate &Candidate = CandidateSet.back();
3478 Candidate.FoundDecl = FoundDecl;
3479 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3480 Candidate.Viable = false;
3481 Candidate.FailureKind = ovl_fail_bad_deduction;
3482 Candidate.IsSurrogate = false;
3483 Candidate.IgnoreObjectArgument = false;
3484 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3485 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003486 return;
3487 }
Mike Stump1eb44332009-09-09 15:08:12 +00003488
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003489 // Add the conversion function template specialization produced by
3490 // template argument deduction as a candidate.
3491 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003492 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00003493 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003494}
3495
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003496/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3497/// converts the given @c Object to a function pointer via the
3498/// conversion function @c Conversion, and then attempts to call it
3499/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3500/// the type of function that we'll eventually be calling.
3501void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003502 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003503 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00003504 const FunctionProtoType *Proto,
John McCall701c89e2009-12-03 04:06:58 +00003505 QualType ObjectType,
3506 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003507 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003508 if (!CandidateSet.isNewCandidate(Conversion))
3509 return;
3510
Douglas Gregor7edfb692009-11-23 12:27:39 +00003511 // Overload resolution is always an unevaluated context.
3512 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3513
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003514 CandidateSet.push_back(OverloadCandidate());
3515 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003516 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003517 Candidate.Function = 0;
3518 Candidate.Surrogate = Conversion;
3519 Candidate.Viable = true;
3520 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003521 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003522 Candidate.Conversions.resize(NumArgs + 1);
3523
3524 // Determine the implicit conversion sequence for the implicit
3525 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00003526 ImplicitConversionSequence ObjectInit
John McCall701c89e2009-12-03 04:06:58 +00003527 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00003528 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003529 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003530 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00003531 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003532 return;
3533 }
3534
3535 // The first conversion is actually a user-defined conversion whose
3536 // first conversion is ObjectInit's standard conversion (which is
3537 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00003538 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003539 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00003540 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003541 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00003542 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003543 = Candidate.Conversions[0].UserDefined.Before;
3544 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3545
Mike Stump1eb44332009-09-09 15:08:12 +00003546 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003547 unsigned NumArgsInProto = Proto->getNumArgs();
3548
3549 // (C++ 13.3.2p2): A candidate function having fewer than m
3550 // parameters is viable only if it has an ellipsis in its parameter
3551 // list (8.3.5).
3552 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3553 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003554 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003555 return;
3556 }
3557
3558 // Function types don't have any default arguments, so just check if
3559 // we have enough arguments.
3560 if (NumArgs < NumArgsInProto) {
3561 // Not enough arguments.
3562 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003563 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003564 return;
3565 }
3566
3567 // Determine the implicit conversion sequences for each of the
3568 // arguments.
3569 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3570 if (ArgIdx < NumArgsInProto) {
3571 // (C++ 13.3.2p3): for F to be a viable function, there shall
3572 // exist for each argument an implicit conversion sequence
3573 // (13.3.3.1) that converts that argument to the corresponding
3574 // parameter of F.
3575 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003576 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003577 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00003578 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003579 /*InOverloadResolution=*/false);
John McCall1d318332010-01-12 00:44:57 +00003580 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003581 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003582 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003583 break;
3584 }
3585 } else {
3586 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3587 // argument for which there is no corresponding parameter is
3588 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003589 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003590 }
3591 }
3592}
3593
Douglas Gregor063daf62009-03-13 18:40:31 +00003594/// \brief Add overload candidates for overloaded operators that are
3595/// member functions.
3596///
3597/// Add the overloaded operator candidates that are member functions
3598/// for the operator Op that was used in an operator expression such
3599/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3600/// CandidateSet will store the added overload candidates. (C++
3601/// [over.match.oper]).
3602void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3603 SourceLocation OpLoc,
3604 Expr **Args, unsigned NumArgs,
3605 OverloadCandidateSet& CandidateSet,
3606 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00003607 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3608
3609 // C++ [over.match.oper]p3:
3610 // For a unary operator @ with an operand of a type whose
3611 // cv-unqualified version is T1, and for a binary operator @ with
3612 // a left operand of a type whose cv-unqualified version is T1 and
3613 // a right operand of a type whose cv-unqualified version is T2,
3614 // three sets of candidate functions, designated member
3615 // candidates, non-member candidates and built-in candidates, are
3616 // constructed as follows:
3617 QualType T1 = Args[0]->getType();
3618 QualType T2;
3619 if (NumArgs > 1)
3620 T2 = Args[1]->getType();
3621
3622 // -- If T1 is a class type, the set of member candidates is the
3623 // result of the qualified lookup of T1::operator@
3624 // (13.3.1.1.1); otherwise, the set of member candidates is
3625 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00003626 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003627 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003628 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003629 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003630
John McCalla24dc2e2009-11-17 02:14:36 +00003631 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3632 LookupQualifiedName(Operators, T1Rec->getDecl());
3633 Operators.suppressDiagnostics();
3634
Mike Stump1eb44332009-09-09 15:08:12 +00003635 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003636 OperEnd = Operators.end();
3637 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00003638 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00003639 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall701c89e2009-12-03 04:06:58 +00003640 Args + 1, NumArgs - 1, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00003641 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00003642 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003643}
3644
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003645/// AddBuiltinCandidate - Add a candidate for a built-in
3646/// operator. ResultTy and ParamTys are the result and parameter types
3647/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003648/// arguments being passed to the candidate. IsAssignmentOperator
3649/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003650/// operator. NumContextualBoolArguments is the number of arguments
3651/// (at the beginning of the argument list) that will be contextually
3652/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00003653void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003654 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003655 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003656 bool IsAssignmentOperator,
3657 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00003658 // Overload resolution is always an unevaluated context.
3659 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3660
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003661 // Add this candidate
3662 CandidateSet.push_back(OverloadCandidate());
3663 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003664 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003665 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003666 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003667 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003668 Candidate.BuiltinTypes.ResultTy = ResultTy;
3669 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3670 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3671
3672 // Determine the implicit conversion sequences for each of the
3673 // arguments.
3674 Candidate.Viable = true;
3675 Candidate.Conversions.resize(NumArgs);
3676 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003677 // C++ [over.match.oper]p4:
3678 // For the built-in assignment operators, conversions of the
3679 // left operand are restricted as follows:
3680 // -- no temporaries are introduced to hold the left operand, and
3681 // -- no user-defined conversions are applied to the left
3682 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00003683 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003684 //
3685 // We block these conversions by turning off user-defined
3686 // conversions, since that is the only way that initialization of
3687 // a reference to a non-class type can occur from something that
3688 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003689 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00003690 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003691 "Contextual conversion to bool requires bool type");
3692 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3693 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003694 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003695 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00003696 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003697 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003698 }
John McCall1d318332010-01-12 00:44:57 +00003699 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003700 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003701 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00003702 break;
3703 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003704 }
3705}
3706
3707/// BuiltinCandidateTypeSet - A set of types that will be used for the
3708/// candidate operator functions for built-in operators (C++
3709/// [over.built]). The types are separated into pointer types and
3710/// enumeration types.
3711class BuiltinCandidateTypeSet {
3712 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003713 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003714
3715 /// PointerTypes - The set of pointer types that will be used in the
3716 /// built-in candidates.
3717 TypeSet PointerTypes;
3718
Sebastian Redl78eb8742009-04-19 21:53:20 +00003719 /// MemberPointerTypes - The set of member pointer types that will be
3720 /// used in the built-in candidates.
3721 TypeSet MemberPointerTypes;
3722
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003723 /// EnumerationTypes - The set of enumeration types that will be
3724 /// used in the built-in candidates.
3725 TypeSet EnumerationTypes;
3726
Douglas Gregor5842ba92009-08-24 15:23:48 +00003727 /// Sema - The semantic analysis instance where we are building the
3728 /// candidate type set.
3729 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00003730
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003731 /// Context - The AST context in which we will build the type sets.
3732 ASTContext &Context;
3733
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003734 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3735 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00003736 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003737
3738public:
3739 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003740 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003741
Mike Stump1eb44332009-09-09 15:08:12 +00003742 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor5842ba92009-08-24 15:23:48 +00003743 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003744
Douglas Gregor573d9c32009-10-21 23:19:44 +00003745 void AddTypesConvertedFrom(QualType Ty,
3746 SourceLocation Loc,
3747 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003748 bool AllowExplicitConversions,
3749 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003750
3751 /// pointer_begin - First pointer type found;
3752 iterator pointer_begin() { return PointerTypes.begin(); }
3753
Sebastian Redl78eb8742009-04-19 21:53:20 +00003754 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003755 iterator pointer_end() { return PointerTypes.end(); }
3756
Sebastian Redl78eb8742009-04-19 21:53:20 +00003757 /// member_pointer_begin - First member pointer type found;
3758 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3759
3760 /// member_pointer_end - Past the last member pointer type found;
3761 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3762
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003763 /// enumeration_begin - First enumeration type found;
3764 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3765
Sebastian Redl78eb8742009-04-19 21:53:20 +00003766 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003767 iterator enumeration_end() { return EnumerationTypes.end(); }
3768};
3769
Sebastian Redl78eb8742009-04-19 21:53:20 +00003770/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003771/// the set of pointer types along with any more-qualified variants of
3772/// that type. For example, if @p Ty is "int const *", this routine
3773/// will add "int const *", "int const volatile *", "int const
3774/// restrict *", and "int const volatile restrict *" to the set of
3775/// pointer types. Returns true if the add of @p Ty itself succeeded,
3776/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003777///
3778/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003779bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00003780BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3781 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00003782
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003783 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003784 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003785 return false;
3786
John McCall0953e762009-09-24 19:53:00 +00003787 const PointerType *PointerTy = Ty->getAs<PointerType>();
3788 assert(PointerTy && "type was not a pointer type!");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003789
John McCall0953e762009-09-24 19:53:00 +00003790 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003791 // Don't add qualified variants of arrays. For one, they're not allowed
3792 // (the qualifier would sink to the element type), and for another, the
3793 // only overload situation where it matters is subscript or pointer +- int,
3794 // and those shouldn't have qualifier variants anyway.
3795 if (PointeeTy->isArrayType())
3796 return true;
John McCall0953e762009-09-24 19:53:00 +00003797 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00003798 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00003799 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003800 bool hasVolatile = VisibleQuals.hasVolatile();
3801 bool hasRestrict = VisibleQuals.hasRestrict();
3802
John McCall0953e762009-09-24 19:53:00 +00003803 // Iterate through all strict supersets of BaseCVR.
3804 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3805 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003806 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3807 // in the types.
3808 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3809 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00003810 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3811 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003812 }
3813
3814 return true;
3815}
3816
Sebastian Redl78eb8742009-04-19 21:53:20 +00003817/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3818/// to the set of pointer types along with any more-qualified variants of
3819/// that type. For example, if @p Ty is "int const *", this routine
3820/// will add "int const *", "int const volatile *", "int const
3821/// restrict *", and "int const volatile restrict *" to the set of
3822/// pointer types. Returns true if the add of @p Ty itself succeeded,
3823/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003824///
3825/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003826bool
3827BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3828 QualType Ty) {
3829 // Insert this type.
3830 if (!MemberPointerTypes.insert(Ty))
3831 return false;
3832
John McCall0953e762009-09-24 19:53:00 +00003833 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3834 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00003835
John McCall0953e762009-09-24 19:53:00 +00003836 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003837 // Don't add qualified variants of arrays. For one, they're not allowed
3838 // (the qualifier would sink to the element type), and for another, the
3839 // only overload situation where it matters is subscript or pointer +- int,
3840 // and those shouldn't have qualifier variants anyway.
3841 if (PointeeTy->isArrayType())
3842 return true;
John McCall0953e762009-09-24 19:53:00 +00003843 const Type *ClassTy = PointerTy->getClass();
3844
3845 // Iterate through all strict supersets of the pointee type's CVR
3846 // qualifiers.
3847 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3848 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3849 if ((CVR | BaseCVR) != CVR) continue;
3850
3851 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3852 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00003853 }
3854
3855 return true;
3856}
3857
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003858/// AddTypesConvertedFrom - Add each of the types to which the type @p
3859/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00003860/// primarily interested in pointer types and enumeration types. We also
3861/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003862/// AllowUserConversions is true if we should look at the conversion
3863/// functions of a class type, and AllowExplicitConversions if we
3864/// should also include the explicit conversion functions of a class
3865/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003866void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003867BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00003868 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003869 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003870 bool AllowExplicitConversions,
3871 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003872 // Only deal with canonical types.
3873 Ty = Context.getCanonicalType(Ty);
3874
3875 // Look through reference types; they aren't part of the type of an
3876 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00003877 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003878 Ty = RefTy->getPointeeType();
3879
3880 // We don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003881 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003882
Sebastian Redla65b5512009-11-05 16:36:20 +00003883 // If we're dealing with an array type, decay to the pointer.
3884 if (Ty->isArrayType())
3885 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3886
Ted Kremenek6217b802009-07-29 21:53:49 +00003887 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003888 QualType PointeeTy = PointerTy->getPointeeType();
3889
3890 // Insert our type, and its more-qualified variants, into the set
3891 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003892 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003893 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00003894 } else if (Ty->isMemberPointerType()) {
3895 // Member pointers are far easier, since the pointee can't be converted.
3896 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3897 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003898 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00003899 EnumerationTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003900 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003901 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003902 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003903 // No conversion functions in incomplete types.
3904 return;
3905 }
Mike Stump1eb44332009-09-09 15:08:12 +00003906
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003907 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00003908 const UnresolvedSetImpl *Conversions
Fariborz Jahanianca4fb042009-10-07 17:26:09 +00003909 = ClassDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003910 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00003911 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00003912 NamedDecl *D = I.getDecl();
3913 if (isa<UsingShadowDecl>(D))
3914 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003915
Mike Stump1eb44332009-09-09 15:08:12 +00003916 // Skip conversion function templates; they don't tell us anything
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003917 // about which builtin types we can convert to.
John McCall32daa422010-03-31 01:36:47 +00003918 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003919 continue;
3920
John McCall32daa422010-03-31 01:36:47 +00003921 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003922 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003923 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003924 VisibleQuals);
3925 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003926 }
3927 }
3928 }
3929}
3930
Douglas Gregor19b7b152009-08-24 13:43:27 +00003931/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3932/// the volatile- and non-volatile-qualified assignment operators for the
3933/// given type to the candidate set.
3934static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3935 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00003936 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003937 unsigned NumArgs,
3938 OverloadCandidateSet &CandidateSet) {
3939 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00003940
Douglas Gregor19b7b152009-08-24 13:43:27 +00003941 // T& operator=(T&, T)
3942 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3943 ParamTypes[1] = T;
3944 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3945 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00003946
Douglas Gregor19b7b152009-08-24 13:43:27 +00003947 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3948 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00003949 ParamTypes[0]
3950 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00003951 ParamTypes[1] = T;
3952 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00003953 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00003954 }
3955}
Mike Stump1eb44332009-09-09 15:08:12 +00003956
Sebastian Redl9994a342009-10-25 17:03:50 +00003957/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3958/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003959static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3960 Qualifiers VRQuals;
3961 const RecordType *TyRec;
3962 if (const MemberPointerType *RHSMPType =
3963 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00003964 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003965 else
3966 TyRec = ArgExpr->getType()->getAs<RecordType>();
3967 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003968 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003969 VRQuals.addVolatile();
3970 VRQuals.addRestrict();
3971 return VRQuals;
3972 }
3973
3974 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00003975 if (!ClassDecl->hasDefinition())
3976 return VRQuals;
3977
John McCalleec51cf2010-01-20 00:46:10 +00003978 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00003979 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003980
John McCalleec51cf2010-01-20 00:46:10 +00003981 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00003982 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00003983 NamedDecl *D = I.getDecl();
3984 if (isa<UsingShadowDecl>(D))
3985 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3986 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003987 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3988 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3989 CanTy = ResTypeRef->getPointeeType();
3990 // Need to go down the pointer/mempointer chain and add qualifiers
3991 // as see them.
3992 bool done = false;
3993 while (!done) {
3994 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3995 CanTy = ResTypePtr->getPointeeType();
3996 else if (const MemberPointerType *ResTypeMPtr =
3997 CanTy->getAs<MemberPointerType>())
3998 CanTy = ResTypeMPtr->getPointeeType();
3999 else
4000 done = true;
4001 if (CanTy.isVolatileQualified())
4002 VRQuals.addVolatile();
4003 if (CanTy.isRestrictQualified())
4004 VRQuals.addRestrict();
4005 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4006 return VRQuals;
4007 }
4008 }
4009 }
4010 return VRQuals;
4011}
4012
Douglas Gregor74253732008-11-19 15:42:04 +00004013/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4014/// operator overloads to the candidate set (C++ [over.built]), based
4015/// on the operator @p Op and the arguments given. For example, if the
4016/// operator is a binary '+', this routine might add "int
4017/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004018void
Mike Stump1eb44332009-09-09 15:08:12 +00004019Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004020 SourceLocation OpLoc,
Douglas Gregor74253732008-11-19 15:42:04 +00004021 Expr **Args, unsigned NumArgs,
4022 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004023 // The set of "promoted arithmetic types", which are the arithmetic
4024 // types are that preserved by promotion (C++ [over.built]p2). Note
4025 // that the first few of these types are the promoted integral
4026 // types; these types need to be first.
4027 // FIXME: What about complex?
4028 const unsigned FirstIntegralType = 0;
4029 const unsigned LastIntegralType = 13;
Mike Stump1eb44332009-09-09 15:08:12 +00004030 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004031 LastPromotedIntegralType = 13;
4032 const unsigned FirstPromotedArithmeticType = 7,
4033 LastPromotedArithmeticType = 16;
4034 const unsigned NumArithmeticTypes = 16;
4035 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump1eb44332009-09-09 15:08:12 +00004036 Context.BoolTy, Context.CharTy, Context.WCharTy,
4037// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004038 Context.SignedCharTy, Context.ShortTy,
4039 Context.UnsignedCharTy, Context.UnsignedShortTy,
4040 Context.IntTy, Context.LongTy, Context.LongLongTy,
4041 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
4042 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
4043 };
Douglas Gregor652371a2009-10-21 22:01:30 +00004044 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
4045 "Invalid first promoted integral type");
4046 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4047 == Context.UnsignedLongLongTy &&
4048 "Invalid last promoted integral type");
4049 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
4050 "Invalid first promoted arithmetic type");
4051 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4052 == Context.LongDoubleTy &&
4053 "Invalid last promoted arithmetic type");
4054
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004055 // Find all of the types that the arguments can convert to, but only
4056 // if the operator we're looking at has built-in operator candidates
4057 // that make use of these types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004058 Qualifiers VisibleTypeConversionsQuals;
4059 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004060 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4061 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4062
Douglas Gregor5842ba92009-08-24 15:23:48 +00004063 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004064 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
4065 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregor74253732008-11-19 15:42:04 +00004066 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004067 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregor74253732008-11-19 15:42:04 +00004068 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004069 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregor74253732008-11-19 15:42:04 +00004070 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004071 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregor573d9c32009-10-21 23:19:44 +00004072 OpLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004073 true,
4074 (Op == OO_Exclaim ||
4075 Op == OO_AmpAmp ||
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004076 Op == OO_PipePipe),
4077 VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004078 }
4079
4080 bool isComparison = false;
4081 switch (Op) {
4082 case OO_None:
4083 case NUM_OVERLOADED_OPERATORS:
4084 assert(false && "Expected an overloaded operator");
4085 break;
4086
Douglas Gregor74253732008-11-19 15:42:04 +00004087 case OO_Star: // '*' is either unary or binary
Mike Stump1eb44332009-09-09 15:08:12 +00004088 if (NumArgs == 1)
Douglas Gregor74253732008-11-19 15:42:04 +00004089 goto UnaryStar;
4090 else
4091 goto BinaryStar;
4092 break;
4093
4094 case OO_Plus: // '+' is either unary or binary
4095 if (NumArgs == 1)
4096 goto UnaryPlus;
4097 else
4098 goto BinaryPlus;
4099 break;
4100
4101 case OO_Minus: // '-' is either unary or binary
4102 if (NumArgs == 1)
4103 goto UnaryMinus;
4104 else
4105 goto BinaryMinus;
4106 break;
4107
4108 case OO_Amp: // '&' is either unary or binary
4109 if (NumArgs == 1)
4110 goto UnaryAmp;
4111 else
4112 goto BinaryAmp;
4113
4114 case OO_PlusPlus:
4115 case OO_MinusMinus:
4116 // C++ [over.built]p3:
4117 //
4118 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4119 // is either volatile or empty, there exist candidate operator
4120 // functions of the form
4121 //
4122 // VQ T& operator++(VQ T&);
4123 // T operator++(VQ T&, int);
4124 //
4125 // C++ [over.built]p4:
4126 //
4127 // For every pair (T, VQ), where T is an arithmetic type other
4128 // than bool, and VQ is either volatile or empty, there exist
4129 // candidate operator functions of the form
4130 //
4131 // VQ T& operator--(VQ T&);
4132 // T operator--(VQ T&, int);
Mike Stump1eb44332009-09-09 15:08:12 +00004133 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor74253732008-11-19 15:42:04 +00004134 Arith < NumArithmeticTypes; ++Arith) {
4135 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump1eb44332009-09-09 15:08:12 +00004136 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004137 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00004138
4139 // Non-volatile version.
4140 if (NumArgs == 1)
4141 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4142 else
4143 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004144 // heuristic to reduce number of builtin candidates in the set.
4145 // Add volatile version only if there are conversions to a volatile type.
4146 if (VisibleTypeConversionsQuals.hasVolatile()) {
4147 // Volatile version
4148 ParamTypes[0]
4149 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4150 if (NumArgs == 1)
4151 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4152 else
4153 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4154 }
Douglas Gregor74253732008-11-19 15:42:04 +00004155 }
4156
4157 // C++ [over.built]p5:
4158 //
4159 // For every pair (T, VQ), where T is a cv-qualified or
4160 // cv-unqualified object type, and VQ is either volatile or
4161 // empty, there exist candidate operator functions of the form
4162 //
4163 // T*VQ& operator++(T*VQ&);
4164 // T*VQ& operator--(T*VQ&);
4165 // T* operator++(T*VQ&, int);
4166 // T* operator--(T*VQ&, int);
4167 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4168 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4169 // Skip pointer types that aren't pointers to object types.
Ted Kremenek6217b802009-07-29 21:53:49 +00004170 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00004171 continue;
4172
Mike Stump1eb44332009-09-09 15:08:12 +00004173 QualType ParamTypes[2] = {
4174 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00004175 };
Mike Stump1eb44332009-09-09 15:08:12 +00004176
Douglas Gregor74253732008-11-19 15:42:04 +00004177 // Without volatile
4178 if (NumArgs == 1)
4179 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4180 else
4181 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4182
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004183 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4184 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00004185 // With volatile
John McCall0953e762009-09-24 19:53:00 +00004186 ParamTypes[0]
4187 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor74253732008-11-19 15:42:04 +00004188 if (NumArgs == 1)
4189 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4190 else
4191 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4192 }
4193 }
4194 break;
4195
4196 UnaryStar:
4197 // C++ [over.built]p6:
4198 // For every cv-qualified or cv-unqualified object type T, there
4199 // exist candidate operator functions of the form
4200 //
4201 // T& operator*(T*);
4202 //
4203 // C++ [over.built]p7:
4204 // For every function type T, there exist candidate operator
4205 // functions of the form
4206 // T& operator*(T*);
4207 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4208 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4209 QualType ParamTy = *Ptr;
Ted Kremenek6217b802009-07-29 21:53:49 +00004210 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004211 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00004212 &ParamTy, Args, 1, CandidateSet);
4213 }
4214 break;
4215
4216 UnaryPlus:
4217 // C++ [over.built]p8:
4218 // For every type T, there exist candidate operator functions of
4219 // the form
4220 //
4221 // T* operator+(T*);
4222 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4223 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4224 QualType ParamTy = *Ptr;
4225 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4226 }
Mike Stump1eb44332009-09-09 15:08:12 +00004227
Douglas Gregor74253732008-11-19 15:42:04 +00004228 // Fall through
4229
4230 UnaryMinus:
4231 // C++ [over.built]p9:
4232 // For every promoted arithmetic type T, there exist candidate
4233 // operator functions of the form
4234 //
4235 // T operator+(T);
4236 // T operator-(T);
Mike Stump1eb44332009-09-09 15:08:12 +00004237 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor74253732008-11-19 15:42:04 +00004238 Arith < LastPromotedArithmeticType; ++Arith) {
4239 QualType ArithTy = ArithmeticTypes[Arith];
4240 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4241 }
4242 break;
4243
4244 case OO_Tilde:
4245 // C++ [over.built]p10:
4246 // For every promoted integral type T, there exist candidate
4247 // operator functions of the form
4248 //
4249 // T operator~(T);
Mike Stump1eb44332009-09-09 15:08:12 +00004250 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor74253732008-11-19 15:42:04 +00004251 Int < LastPromotedIntegralType; ++Int) {
4252 QualType IntTy = ArithmeticTypes[Int];
4253 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4254 }
4255 break;
4256
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004257 case OO_New:
4258 case OO_Delete:
4259 case OO_Array_New:
4260 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004261 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00004262 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004263 break;
4264
4265 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00004266 UnaryAmp:
4267 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004268 // C++ [over.match.oper]p3:
4269 // -- For the operator ',', the unary operator '&', or the
4270 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004271 break;
4272
Douglas Gregor19b7b152009-08-24 13:43:27 +00004273 case OO_EqualEqual:
4274 case OO_ExclaimEqual:
4275 // C++ [over.match.oper]p16:
Mike Stump1eb44332009-09-09 15:08:12 +00004276 // For every pointer to member type T, there exist candidate operator
4277 // functions of the form
Douglas Gregor19b7b152009-08-24 13:43:27 +00004278 //
4279 // bool operator==(T,T);
4280 // bool operator!=(T,T);
Mike Stump1eb44332009-09-09 15:08:12 +00004281 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor19b7b152009-08-24 13:43:27 +00004282 MemPtr = CandidateTypes.member_pointer_begin(),
4283 MemPtrEnd = CandidateTypes.member_pointer_end();
4284 MemPtr != MemPtrEnd;
4285 ++MemPtr) {
4286 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4287 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4288 }
Mike Stump1eb44332009-09-09 15:08:12 +00004289
Douglas Gregor19b7b152009-08-24 13:43:27 +00004290 // Fall through
Mike Stump1eb44332009-09-09 15:08:12 +00004291
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004292 case OO_Less:
4293 case OO_Greater:
4294 case OO_LessEqual:
4295 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004296 // C++ [over.built]p15:
4297 //
4298 // For every pointer or enumeration type T, there exist
4299 // candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004300 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004301 // bool operator<(T, T);
4302 // bool operator>(T, T);
4303 // bool operator<=(T, T);
4304 // bool operator>=(T, T);
4305 // bool operator==(T, T);
4306 // bool operator!=(T, T);
4307 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4308 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4309 QualType ParamTypes[2] = { *Ptr, *Ptr };
4310 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4311 }
Mike Stump1eb44332009-09-09 15:08:12 +00004312 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004313 = CandidateTypes.enumeration_begin();
4314 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4315 QualType ParamTypes[2] = { *Enum, *Enum };
4316 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4317 }
4318
4319 // Fall through.
4320 isComparison = true;
4321
Douglas Gregor74253732008-11-19 15:42:04 +00004322 BinaryPlus:
4323 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004324 if (!isComparison) {
4325 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4326
4327 // C++ [over.built]p13:
4328 //
4329 // For every cv-qualified or cv-unqualified object type T
4330 // there exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004331 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004332 // T* operator+(T*, ptrdiff_t);
4333 // T& operator[](T*, ptrdiff_t); [BELOW]
4334 // T* operator-(T*, ptrdiff_t);
4335 // T* operator+(ptrdiff_t, T*);
4336 // T& operator[](ptrdiff_t, T*); [BELOW]
4337 //
4338 // C++ [over.built]p14:
4339 //
4340 // For every T, where T is a pointer to object type, there
4341 // exist candidate operator functions of the form
4342 //
4343 // ptrdiff_t operator-(T, T);
Mike Stump1eb44332009-09-09 15:08:12 +00004344 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004345 = CandidateTypes.pointer_begin();
4346 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4347 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4348
4349 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4350 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4351
4352 if (Op == OO_Plus) {
4353 // T* operator+(ptrdiff_t, T*);
4354 ParamTypes[0] = ParamTypes[1];
4355 ParamTypes[1] = *Ptr;
4356 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4357 } else {
4358 // ptrdiff_t operator-(T, T);
4359 ParamTypes[1] = *Ptr;
4360 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4361 Args, 2, CandidateSet);
4362 }
4363 }
4364 }
4365 // Fall through
4366
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004367 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00004368 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004369 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004370 // C++ [over.built]p12:
4371 //
4372 // For every pair of promoted arithmetic types L and R, there
4373 // exist candidate operator functions of the form
4374 //
4375 // LR operator*(L, R);
4376 // LR operator/(L, R);
4377 // LR operator+(L, R);
4378 // LR operator-(L, R);
4379 // bool operator<(L, R);
4380 // bool operator>(L, R);
4381 // bool operator<=(L, R);
4382 // bool operator>=(L, R);
4383 // bool operator==(L, R);
4384 // bool operator!=(L, R);
4385 //
4386 // where LR is the result of the usual arithmetic conversions
4387 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004388 //
4389 // C++ [over.built]p24:
4390 //
4391 // For every pair of promoted arithmetic types L and R, there exist
4392 // candidate operator functions of the form
4393 //
4394 // LR operator?(bool, L, R);
4395 //
4396 // where LR is the result of the usual arithmetic conversions
4397 // between types L and R.
4398 // Our candidates ignore the first parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00004399 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004400 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004401 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004402 Right < LastPromotedArithmeticType; ++Right) {
4403 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00004404 QualType Result
4405 = isComparison
4406 ? Context.BoolTy
4407 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004408 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4409 }
4410 }
4411 break;
4412
4413 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00004414 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004415 case OO_Caret:
4416 case OO_Pipe:
4417 case OO_LessLess:
4418 case OO_GreaterGreater:
4419 // C++ [over.built]p17:
4420 //
4421 // For every pair of promoted integral types L and R, there
4422 // exist candidate operator functions of the form
4423 //
4424 // LR operator%(L, R);
4425 // LR operator&(L, R);
4426 // LR operator^(L, R);
4427 // LR operator|(L, R);
4428 // L operator<<(L, R);
4429 // L operator>>(L, R);
4430 //
4431 // where LR is the result of the usual arithmetic conversions
4432 // between types L and R.
Mike Stump1eb44332009-09-09 15:08:12 +00004433 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004434 Left < LastPromotedIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004435 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004436 Right < LastPromotedIntegralType; ++Right) {
4437 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4438 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4439 ? LandR[0]
Eli Friedmana95d7572009-08-19 07:44:53 +00004440 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004441 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4442 }
4443 }
4444 break;
4445
4446 case OO_Equal:
4447 // C++ [over.built]p20:
4448 //
4449 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00004450 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004451 // empty, there exist candidate operator functions of the form
4452 //
4453 // VQ T& operator=(VQ T&, T);
Douglas Gregor19b7b152009-08-24 13:43:27 +00004454 for (BuiltinCandidateTypeSet::iterator
4455 Enum = CandidateTypes.enumeration_begin(),
4456 EnumEnd = CandidateTypes.enumeration_end();
4457 Enum != EnumEnd; ++Enum)
Mike Stump1eb44332009-09-09 15:08:12 +00004458 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004459 CandidateSet);
4460 for (BuiltinCandidateTypeSet::iterator
4461 MemPtr = CandidateTypes.member_pointer_begin(),
4462 MemPtrEnd = CandidateTypes.member_pointer_end();
4463 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump1eb44332009-09-09 15:08:12 +00004464 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004465 CandidateSet);
4466 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004467
4468 case OO_PlusEqual:
4469 case OO_MinusEqual:
4470 // C++ [over.built]p19:
4471 //
4472 // For every pair (T, VQ), where T is any type and VQ is either
4473 // volatile or empty, there exist candidate operator functions
4474 // of the form
4475 //
4476 // T*VQ& operator=(T*VQ&, T*);
4477 //
4478 // C++ [over.built]p21:
4479 //
4480 // For every pair (T, VQ), where T is a cv-qualified or
4481 // cv-unqualified object type and VQ is either volatile or
4482 // empty, there exist candidate operator functions of the form
4483 //
4484 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4485 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4486 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4487 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4488 QualType ParamTypes[2];
4489 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4490
4491 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004492 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004493 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4494 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004495
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004496 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4497 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00004498 // volatile version
John McCall0953e762009-09-24 19:53:00 +00004499 ParamTypes[0]
4500 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004501 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4502 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00004503 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004504 }
4505 // Fall through.
4506
4507 case OO_StarEqual:
4508 case OO_SlashEqual:
4509 // C++ [over.built]p18:
4510 //
4511 // For every triple (L, VQ, R), where L is an arithmetic type,
4512 // VQ is either volatile or empty, and R is a promoted
4513 // arithmetic type, there exist candidate operator functions of
4514 // the form
4515 //
4516 // VQ L& operator=(VQ L&, R);
4517 // VQ L& operator*=(VQ L&, R);
4518 // VQ L& operator/=(VQ L&, R);
4519 // VQ L& operator+=(VQ L&, R);
4520 // VQ L& operator-=(VQ L&, R);
4521 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004522 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004523 Right < LastPromotedArithmeticType; ++Right) {
4524 QualType ParamTypes[2];
4525 ParamTypes[1] = ArithmeticTypes[Right];
4526
4527 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004528 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004529 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4530 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004531
4532 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004533 if (VisibleTypeConversionsQuals.hasVolatile()) {
4534 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4535 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4536 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4537 /*IsAssigmentOperator=*/Op == OO_Equal);
4538 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004539 }
4540 }
4541 break;
4542
4543 case OO_PercentEqual:
4544 case OO_LessLessEqual:
4545 case OO_GreaterGreaterEqual:
4546 case OO_AmpEqual:
4547 case OO_CaretEqual:
4548 case OO_PipeEqual:
4549 // C++ [over.built]p22:
4550 //
4551 // For every triple (L, VQ, R), where L is an integral type, VQ
4552 // is either volatile or empty, and R is a promoted integral
4553 // type, there exist candidate operator functions of the form
4554 //
4555 // VQ L& operator%=(VQ L&, R);
4556 // VQ L& operator<<=(VQ L&, R);
4557 // VQ L& operator>>=(VQ L&, R);
4558 // VQ L& operator&=(VQ L&, R);
4559 // VQ L& operator^=(VQ L&, R);
4560 // VQ L& operator|=(VQ L&, R);
4561 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004562 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004563 Right < LastPromotedIntegralType; ++Right) {
4564 QualType ParamTypes[2];
4565 ParamTypes[1] = ArithmeticTypes[Right];
4566
4567 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004568 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004569 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian035c46f2009-10-20 00:04:40 +00004570 if (VisibleTypeConversionsQuals.hasVolatile()) {
4571 // Add this built-in operator as a candidate (VQ is 'volatile').
4572 ParamTypes[0] = ArithmeticTypes[Left];
4573 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4574 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4575 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4576 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004577 }
4578 }
4579 break;
4580
Douglas Gregor74253732008-11-19 15:42:04 +00004581 case OO_Exclaim: {
4582 // C++ [over.operator]p23:
4583 //
4584 // There also exist candidate operator functions of the form
4585 //
Mike Stump1eb44332009-09-09 15:08:12 +00004586 // bool operator!(bool);
Douglas Gregor74253732008-11-19 15:42:04 +00004587 // bool operator&&(bool, bool); [BELOW]
4588 // bool operator||(bool, bool); [BELOW]
4589 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004590 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4591 /*IsAssignmentOperator=*/false,
4592 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00004593 break;
4594 }
4595
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004596 case OO_AmpAmp:
4597 case OO_PipePipe: {
4598 // C++ [over.operator]p23:
4599 //
4600 // There also exist candidate operator functions of the form
4601 //
Douglas Gregor74253732008-11-19 15:42:04 +00004602 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004603 // bool operator&&(bool, bool);
4604 // bool operator||(bool, bool);
4605 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004606 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4607 /*IsAssignmentOperator=*/false,
4608 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004609 break;
4610 }
4611
4612 case OO_Subscript:
4613 // C++ [over.built]p13:
4614 //
4615 // For every cv-qualified or cv-unqualified object type T there
4616 // exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004617 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004618 // T* operator+(T*, ptrdiff_t); [ABOVE]
4619 // T& operator[](T*, ptrdiff_t);
4620 // T* operator-(T*, ptrdiff_t); [ABOVE]
4621 // T* operator+(ptrdiff_t, T*); [ABOVE]
4622 // T& operator[](ptrdiff_t, T*);
4623 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4624 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4625 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenek6217b802009-07-29 21:53:49 +00004626 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004627 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004628
4629 // T& operator[](T*, ptrdiff_t)
4630 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4631
4632 // T& operator[](ptrdiff_t, T*);
4633 ParamTypes[0] = ParamTypes[1];
4634 ParamTypes[1] = *Ptr;
4635 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4636 }
4637 break;
4638
4639 case OO_ArrowStar:
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004640 // C++ [over.built]p11:
4641 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4642 // C1 is the same type as C2 or is a derived class of C2, T is an object
4643 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4644 // there exist candidate operator functions of the form
4645 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4646 // where CV12 is the union of CV1 and CV2.
4647 {
4648 for (BuiltinCandidateTypeSet::iterator Ptr =
4649 CandidateTypes.pointer_begin();
4650 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4651 QualType C1Ty = (*Ptr);
4652 QualType C1;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004653 QualifierCollector Q1;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004654 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004655 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004656 if (!isa<RecordType>(C1))
4657 continue;
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004658 // heuristic to reduce number of builtin candidates in the set.
4659 // Add volatile/restrict version only if there are conversions to a
4660 // volatile/restrict type.
4661 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4662 continue;
4663 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4664 continue;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004665 }
4666 for (BuiltinCandidateTypeSet::iterator
4667 MemPtr = CandidateTypes.member_pointer_begin(),
4668 MemPtrEnd = CandidateTypes.member_pointer_end();
4669 MemPtr != MemPtrEnd; ++MemPtr) {
4670 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4671 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian43036972009-10-07 16:56:50 +00004672 C2 = C2.getUnqualifiedType();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004673 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4674 break;
4675 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4676 // build CV12 T&
4677 QualType T = mptr->getPointeeType();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004678 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4679 T.isVolatileQualified())
4680 continue;
4681 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4682 T.isRestrictQualified())
4683 continue;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004684 T = Q1.apply(T);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004685 QualType ResultTy = Context.getLValueReferenceType(T);
4686 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4687 }
4688 }
4689 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004690 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004691
4692 case OO_Conditional:
4693 // Note that we don't consider the first argument, since it has been
4694 // contextually converted to bool long ago. The candidates below are
4695 // therefore added as binary.
4696 //
4697 // C++ [over.built]p24:
4698 // For every type T, where T is a pointer or pointer-to-member type,
4699 // there exist candidate operator functions of the form
4700 //
4701 // T operator?(bool, T, T);
4702 //
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004703 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4704 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4705 QualType ParamTypes[2] = { *Ptr, *Ptr };
4706 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4707 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00004708 for (BuiltinCandidateTypeSet::iterator Ptr =
4709 CandidateTypes.member_pointer_begin(),
4710 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4711 QualType ParamTypes[2] = { *Ptr, *Ptr };
4712 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4713 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004714 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004715 }
4716}
4717
Douglas Gregorfa047642009-02-04 00:32:51 +00004718/// \brief Add function candidates found via argument-dependent lookup
4719/// to the set of overloading candidates.
4720///
4721/// This routine performs argument-dependent name lookup based on the
4722/// given function name (which may also be an operator name) and adds
4723/// all of the overload candidates found by ADL to the overload
4724/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00004725void
Douglas Gregorfa047642009-02-04 00:32:51 +00004726Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00004727 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00004728 Expr **Args, unsigned NumArgs,
John McCalld5532b62009-11-23 01:53:49 +00004729 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004730 OverloadCandidateSet& CandidateSet,
4731 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00004732 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00004733
John McCalla113e722010-01-26 06:04:06 +00004734 // FIXME: This approach for uniquing ADL results (and removing
4735 // redundant candidates from the set) relies on pointer-equality,
4736 // which means we need to key off the canonical decl. However,
4737 // always going back to the canonical decl might not get us the
4738 // right set of default arguments. What default arguments are
4739 // we supposed to consider on ADL candidates, anyway?
4740
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004741 // FIXME: Pass in the explicit template arguments?
John McCall7edb5fd2010-01-26 07:16:45 +00004742 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00004743
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004744 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004745 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4746 CandEnd = CandidateSet.end();
4747 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00004748 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00004749 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00004750 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00004751 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00004752 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004753
4754 // For each of the ADL candidates we found, add it to the overload
4755 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00004756 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00004757 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00004758 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00004759 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004760 continue;
4761
John McCall9aa472c2010-03-19 07:35:19 +00004762 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00004763 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004764 } else
John McCall6e266892010-01-26 03:27:55 +00004765 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00004766 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004767 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00004768 }
Douglas Gregorfa047642009-02-04 00:32:51 +00004769}
4770
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004771/// isBetterOverloadCandidate - Determines whether the first overload
4772/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00004773bool
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004774Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCall5769d612010-02-08 23:07:23 +00004775 const OverloadCandidate& Cand2,
4776 SourceLocation Loc) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004777 // Define viable functions to be better candidates than non-viable
4778 // functions.
4779 if (!Cand2.Viable)
4780 return Cand1.Viable;
4781 else if (!Cand1.Viable)
4782 return false;
4783
Douglas Gregor88a35142008-12-22 05:46:06 +00004784 // C++ [over.match.best]p1:
4785 //
4786 // -- if F is a static member function, ICS1(F) is defined such
4787 // that ICS1(F) is neither better nor worse than ICS1(G) for
4788 // any function G, and, symmetrically, ICS1(G) is neither
4789 // better nor worse than ICS1(F).
4790 unsigned StartArg = 0;
4791 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4792 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004793
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004794 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00004795 // A viable function F1 is defined to be a better function than another
4796 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004797 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004798 unsigned NumArgs = Cand1.Conversions.size();
4799 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4800 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004801 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004802 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4803 Cand2.Conversions[ArgIdx])) {
4804 case ImplicitConversionSequence::Better:
4805 // Cand1 has a better conversion sequence.
4806 HasBetterConversion = true;
4807 break;
4808
4809 case ImplicitConversionSequence::Worse:
4810 // Cand1 can't be better than Cand2.
4811 return false;
4812
4813 case ImplicitConversionSequence::Indistinguishable:
4814 // Do nothing.
4815 break;
4816 }
4817 }
4818
Mike Stump1eb44332009-09-09 15:08:12 +00004819 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004820 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004821 if (HasBetterConversion)
4822 return true;
4823
Mike Stump1eb44332009-09-09 15:08:12 +00004824 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004825 // specialization, or, if not that,
4826 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4827 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4828 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004829
4830 // -- F1 and F2 are function template specializations, and the function
4831 // template for F1 is more specialized than the template for F2
4832 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004833 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00004834 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4835 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004836 if (FunctionTemplateDecl *BetterTemplate
4837 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4838 Cand2.Function->getPrimaryTemplate(),
John McCall5769d612010-02-08 23:07:23 +00004839 Loc,
Douglas Gregor5d7d3752009-09-14 23:02:14 +00004840 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4841 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004842 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004843
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004844 // -- the context is an initialization by user-defined conversion
4845 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4846 // from the return type of F1 to the destination type (i.e.,
4847 // the type of the entity being initialized) is a better
4848 // conversion sequence than the standard conversion sequence
4849 // from the return type of F2 to the destination type.
Mike Stump1eb44332009-09-09 15:08:12 +00004850 if (Cand1.Function && Cand2.Function &&
4851 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004852 isa<CXXConversionDecl>(Cand2.Function)) {
4853 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4854 Cand2.FinalConversion)) {
4855 case ImplicitConversionSequence::Better:
4856 // Cand1 has a better conversion sequence.
4857 return true;
4858
4859 case ImplicitConversionSequence::Worse:
4860 // Cand1 can't be better than Cand2.
4861 return false;
4862
4863 case ImplicitConversionSequence::Indistinguishable:
4864 // Do nothing
4865 break;
4866 }
4867 }
4868
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004869 return false;
4870}
4871
Mike Stump1eb44332009-09-09 15:08:12 +00004872/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00004873/// within an overload candidate set.
4874///
4875/// \param CandidateSet the set of candidate functions.
4876///
4877/// \param Loc the location of the function name (or operator symbol) for
4878/// which overload resolution occurs.
4879///
Mike Stump1eb44332009-09-09 15:08:12 +00004880/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00004881/// function, Best points to the candidate function found.
4882///
4883/// \returns The result of overload resolution.
Douglas Gregor20093b42009-12-09 23:02:17 +00004884OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4885 SourceLocation Loc,
4886 OverloadCandidateSet::iterator& Best) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004887 // Find the best viable function.
4888 Best = CandidateSet.end();
4889 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4890 Cand != CandidateSet.end(); ++Cand) {
4891 if (Cand->Viable) {
John McCall5769d612010-02-08 23:07:23 +00004892 if (Best == CandidateSet.end() ||
4893 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004894 Best = Cand;
4895 }
4896 }
4897
4898 // If we didn't find any viable functions, abort.
4899 if (Best == CandidateSet.end())
4900 return OR_No_Viable_Function;
4901
4902 // Make sure that this function is better than every other viable
4903 // function. If not, we have an ambiguity.
4904 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4905 Cand != CandidateSet.end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00004906 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004907 Cand != Best &&
John McCall5769d612010-02-08 23:07:23 +00004908 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004909 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004910 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004911 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004912 }
Mike Stump1eb44332009-09-09 15:08:12 +00004913
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004914 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004915 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00004916 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00004917 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00004918 return OR_Deleted;
4919
Douglas Gregore0762c92009-06-19 23:52:42 +00004920 // C++ [basic.def.odr]p2:
4921 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00004922 // when referred to from a potentially-evaluated expression. [Note: this
4923 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00004924 // (clause 13), user-defined conversions (12.3.2), allocation function for
4925 // placement new (5.3.4), as well as non-default initialization (8.5).
4926 if (Best->Function)
4927 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004928 return OR_Success;
4929}
4930
John McCall3c80f572010-01-12 02:15:36 +00004931namespace {
4932
4933enum OverloadCandidateKind {
4934 oc_function,
4935 oc_method,
4936 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00004937 oc_function_template,
4938 oc_method_template,
4939 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00004940 oc_implicit_default_constructor,
4941 oc_implicit_copy_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00004942 oc_implicit_copy_assignment
John McCall3c80f572010-01-12 02:15:36 +00004943};
4944
John McCall220ccbf2010-01-13 00:25:19 +00004945OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4946 FunctionDecl *Fn,
4947 std::string &Description) {
4948 bool isTemplate = false;
4949
4950 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4951 isTemplate = true;
4952 Description = S.getTemplateArgumentBindingsText(
4953 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4954 }
John McCallb1622a12010-01-06 09:43:14 +00004955
4956 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00004957 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00004958 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00004959
John McCall3c80f572010-01-12 02:15:36 +00004960 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4961 : oc_implicit_default_constructor;
John McCallb1622a12010-01-06 09:43:14 +00004962 }
4963
4964 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4965 // This actually gets spelled 'candidate function' for now, but
4966 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00004967 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00004968 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00004969
4970 assert(Meth->isCopyAssignment()
4971 && "implicit method is not copy assignment operator?");
John McCall3c80f572010-01-12 02:15:36 +00004972 return oc_implicit_copy_assignment;
4973 }
4974
John McCall220ccbf2010-01-13 00:25:19 +00004975 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00004976}
4977
4978} // end anonymous namespace
4979
4980// Notes the location of an overload candidate.
4981void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCall220ccbf2010-01-13 00:25:19 +00004982 std::string FnDesc;
4983 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4984 Diag(Fn->getLocation(), diag::note_ovl_candidate)
4985 << (unsigned) K << FnDesc;
John McCallb1622a12010-01-06 09:43:14 +00004986}
4987
John McCall1d318332010-01-12 00:44:57 +00004988/// Diagnoses an ambiguous conversion. The partial diagnostic is the
4989/// "lead" diagnostic; it will be given two arguments, the source and
4990/// target types of the conversion.
4991void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4992 SourceLocation CaretLoc,
4993 const PartialDiagnostic &PDiag) {
4994 Diag(CaretLoc, PDiag)
4995 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4996 for (AmbiguousConversionSequence::const_iterator
4997 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4998 NoteOverloadCandidate(*I);
4999 }
John McCall81201622010-01-08 04:41:39 +00005000}
5001
John McCall1d318332010-01-12 00:44:57 +00005002namespace {
5003
John McCalladbb8f82010-01-13 09:16:55 +00005004void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5005 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5006 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00005007 assert(Cand->Function && "for now, candidate must be a function");
5008 FunctionDecl *Fn = Cand->Function;
5009
5010 // There's a conversion slot for the object argument if this is a
5011 // non-constructor method. Note that 'I' corresponds the
5012 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00005013 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00005014 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00005015 if (I == 0)
5016 isObjectArgument = true;
5017 else
5018 I--;
John McCall220ccbf2010-01-13 00:25:19 +00005019 }
5020
John McCall220ccbf2010-01-13 00:25:19 +00005021 std::string FnDesc;
5022 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5023
John McCalladbb8f82010-01-13 09:16:55 +00005024 Expr *FromExpr = Conv.Bad.FromExpr;
5025 QualType FromTy = Conv.Bad.getFromType();
5026 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00005027
John McCall5920dbb2010-02-02 02:42:52 +00005028 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00005029 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00005030 Expr *E = FromExpr->IgnoreParens();
5031 if (isa<UnaryOperator>(E))
5032 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00005033 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00005034
5035 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5036 << (unsigned) FnKind << FnDesc
5037 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5038 << ToTy << Name << I+1;
5039 return;
5040 }
5041
John McCall258b2032010-01-23 08:10:49 +00005042 // Do some hand-waving analysis to see if the non-viability is due
5043 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00005044 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5045 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5046 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5047 CToTy = RT->getPointeeType();
5048 else {
5049 // TODO: detect and diagnose the full richness of const mismatches.
5050 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5051 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5052 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5053 }
5054
5055 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5056 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5057 // It is dumb that we have to do this here.
5058 while (isa<ArrayType>(CFromTy))
5059 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5060 while (isa<ArrayType>(CToTy))
5061 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5062
5063 Qualifiers FromQs = CFromTy.getQualifiers();
5064 Qualifiers ToQs = CToTy.getQualifiers();
5065
5066 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5067 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5068 << (unsigned) FnKind << FnDesc
5069 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5070 << FromTy
5071 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5072 << (unsigned) isObjectArgument << I+1;
5073 return;
5074 }
5075
5076 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5077 assert(CVR && "unexpected qualifiers mismatch");
5078
5079 if (isObjectArgument) {
5080 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5081 << (unsigned) FnKind << FnDesc
5082 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5083 << FromTy << (CVR - 1);
5084 } else {
5085 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5086 << (unsigned) FnKind << FnDesc
5087 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5088 << FromTy << (CVR - 1) << I+1;
5089 }
5090 return;
5091 }
5092
John McCall258b2032010-01-23 08:10:49 +00005093 // Diagnose references or pointers to incomplete types differently,
5094 // since it's far from impossible that the incompleteness triggered
5095 // the failure.
5096 QualType TempFromTy = FromTy.getNonReferenceType();
5097 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5098 TempFromTy = PTy->getPointeeType();
5099 if (TempFromTy->isIncompleteType()) {
5100 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5101 << (unsigned) FnKind << FnDesc
5102 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5103 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5104 return;
5105 }
5106
John McCall651f3ee2010-01-14 03:28:57 +00005107 // TODO: specialize more based on the kind of mismatch
John McCall220ccbf2010-01-13 00:25:19 +00005108 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5109 << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00005110 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalle81e15e2010-01-14 00:56:20 +00005111 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCalladbb8f82010-01-13 09:16:55 +00005112}
5113
5114void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5115 unsigned NumFormalArgs) {
5116 // TODO: treat calls to a missing default constructor as a special case
5117
5118 FunctionDecl *Fn = Cand->Function;
5119 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5120
5121 unsigned MinParams = Fn->getMinRequiredArguments();
5122
5123 // at least / at most / exactly
Douglas Gregora18592e2010-05-08 18:13:28 +00005124 // FIXME: variadic templates "at most" should account for parameter packs
John McCalladbb8f82010-01-13 09:16:55 +00005125 unsigned mode, modeCount;
5126 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00005127 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5128 (Cand->FailureKind == ovl_fail_bad_deduction &&
5129 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCalladbb8f82010-01-13 09:16:55 +00005130 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5131 mode = 0; // "at least"
5132 else
5133 mode = 2; // "exactly"
5134 modeCount = MinParams;
5135 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00005136 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5137 (Cand->FailureKind == ovl_fail_bad_deduction &&
5138 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00005139 if (MinParams != FnTy->getNumArgs())
5140 mode = 1; // "at most"
5141 else
5142 mode = 2; // "exactly"
5143 modeCount = FnTy->getNumArgs();
5144 }
5145
5146 std::string Description;
5147 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5148
5149 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregora18592e2010-05-08 18:13:28 +00005150 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5151 << modeCount << NumFormalArgs;
John McCall220ccbf2010-01-13 00:25:19 +00005152}
5153
John McCall342fec42010-02-01 18:53:26 +00005154/// Diagnose a failed template-argument deduction.
5155void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5156 Expr **Args, unsigned NumArgs) {
5157 FunctionDecl *Fn = Cand->Function; // pattern
5158
Douglas Gregora9333192010-05-08 17:41:32 +00005159 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00005160 NamedDecl *ParamD;
5161 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5162 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5163 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00005164 switch (Cand->DeductionFailure.Result) {
5165 case Sema::TDK_Success:
5166 llvm_unreachable("TDK_success while diagnosing bad deduction");
5167
5168 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00005169 assert(ParamD && "no parameter found for incomplete deduction result");
5170 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5171 << ParamD->getDeclName();
5172 return;
5173 }
5174
Douglas Gregora9333192010-05-08 17:41:32 +00005175 case Sema::TDK_Inconsistent:
5176 case Sema::TDK_InconsistentQuals: {
Douglas Gregorf1a84452010-05-08 19:15:54 +00005177 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00005178 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00005179 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00005180 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00005181 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00005182 which = 1;
5183 else {
Douglas Gregora9333192010-05-08 17:41:32 +00005184 which = 2;
5185 }
5186
5187 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5188 << which << ParamD->getDeclName()
5189 << *Cand->DeductionFailure.getFirstArg()
5190 << *Cand->DeductionFailure.getSecondArg();
5191 return;
5192 }
Douglas Gregora18592e2010-05-08 18:13:28 +00005193
Douglas Gregorf1a84452010-05-08 19:15:54 +00005194 case Sema::TDK_InvalidExplicitArguments:
5195 assert(ParamD && "no parameter found for invalid explicit arguments");
5196 if (ParamD->getDeclName())
5197 S.Diag(Fn->getLocation(),
5198 diag::note_ovl_candidate_explicit_arg_mismatch_named)
5199 << ParamD->getDeclName();
5200 else {
5201 int index = 0;
5202 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5203 index = TTP->getIndex();
5204 else if (NonTypeTemplateParmDecl *NTTP
5205 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5206 index = NTTP->getIndex();
5207 else
5208 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
5209 S.Diag(Fn->getLocation(),
5210 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
5211 << (index + 1);
5212 }
5213 return;
5214
Douglas Gregora18592e2010-05-08 18:13:28 +00005215 case Sema::TDK_TooManyArguments:
5216 case Sema::TDK_TooFewArguments:
5217 DiagnoseArityMismatch(S, Cand, NumArgs);
5218 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00005219
5220 case Sema::TDK_InstantiationDepth:
5221 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
5222 return;
5223
5224 case Sema::TDK_SubstitutionFailure: {
5225 std::string ArgString;
5226 if (TemplateArgumentList *Args
5227 = Cand->DeductionFailure.getTemplateArgumentList())
5228 ArgString = S.getTemplateArgumentBindingsText(
5229 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
5230 *Args);
5231 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
5232 << ArgString;
5233 return;
5234 }
Douglas Gregora9333192010-05-08 17:41:32 +00005235
John McCall342fec42010-02-01 18:53:26 +00005236 // TODO: diagnose these individually, then kill off
5237 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00005238 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00005239 case Sema::TDK_FailedOverloadResolution:
5240 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
5241 return;
5242 }
5243}
5244
5245/// Generates a 'note' diagnostic for an overload candidate. We've
5246/// already generated a primary error at the call site.
5247///
5248/// It really does need to be a single diagnostic with its caret
5249/// pointed at the candidate declaration. Yes, this creates some
5250/// major challenges of technical writing. Yes, this makes pointing
5251/// out problems with specific arguments quite awkward. It's still
5252/// better than generating twenty screens of text for every failed
5253/// overload.
5254///
5255/// It would be great to be able to express per-candidate problems
5256/// more richly for those diagnostic clients that cared, but we'd
5257/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00005258void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
5259 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00005260 FunctionDecl *Fn = Cand->Function;
5261
John McCall81201622010-01-08 04:41:39 +00005262 // Note deleted candidates, but only if they're viable.
John McCall3c80f572010-01-12 02:15:36 +00005263 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCall220ccbf2010-01-13 00:25:19 +00005264 std::string FnDesc;
5265 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00005266
5267 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00005268 << FnKind << FnDesc << Fn->isDeleted();
John McCalla1d7d622010-01-08 00:58:21 +00005269 return;
John McCall81201622010-01-08 04:41:39 +00005270 }
5271
John McCall220ccbf2010-01-13 00:25:19 +00005272 // We don't really have anything else to say about viable candidates.
5273 if (Cand->Viable) {
5274 S.NoteOverloadCandidate(Fn);
5275 return;
5276 }
John McCall1d318332010-01-12 00:44:57 +00005277
John McCalladbb8f82010-01-13 09:16:55 +00005278 switch (Cand->FailureKind) {
5279 case ovl_fail_too_many_arguments:
5280 case ovl_fail_too_few_arguments:
5281 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00005282
John McCalladbb8f82010-01-13 09:16:55 +00005283 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00005284 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5285
John McCall717e8912010-01-23 05:17:32 +00005286 case ovl_fail_trivial_conversion:
5287 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00005288 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00005289 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00005290
John McCallb1bdc622010-02-25 01:37:24 +00005291 case ovl_fail_bad_conversion: {
5292 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5293 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00005294 if (Cand->Conversions[I].isBad())
5295 return DiagnoseBadConversion(S, Cand, I);
5296
5297 // FIXME: this currently happens when we're called from SemaInit
5298 // when user-conversion overload fails. Figure out how to handle
5299 // those conditions and diagnose them well.
5300 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00005301 }
John McCallb1bdc622010-02-25 01:37:24 +00005302 }
John McCalla1d7d622010-01-08 00:58:21 +00005303}
5304
5305void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5306 // Desugar the type of the surrogate down to a function type,
5307 // retaining as many typedefs as possible while still showing
5308 // the function type (and, therefore, its parameter types).
5309 QualType FnType = Cand->Surrogate->getConversionType();
5310 bool isLValueReference = false;
5311 bool isRValueReference = false;
5312 bool isPointer = false;
5313 if (const LValueReferenceType *FnTypeRef =
5314 FnType->getAs<LValueReferenceType>()) {
5315 FnType = FnTypeRef->getPointeeType();
5316 isLValueReference = true;
5317 } else if (const RValueReferenceType *FnTypeRef =
5318 FnType->getAs<RValueReferenceType>()) {
5319 FnType = FnTypeRef->getPointeeType();
5320 isRValueReference = true;
5321 }
5322 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5323 FnType = FnTypePtr->getPointeeType();
5324 isPointer = true;
5325 }
5326 // Desugar down to a function type.
5327 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5328 // Reconstruct the pointer/reference as appropriate.
5329 if (isPointer) FnType = S.Context.getPointerType(FnType);
5330 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5331 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5332
5333 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5334 << FnType;
5335}
5336
5337void NoteBuiltinOperatorCandidate(Sema &S,
5338 const char *Opc,
5339 SourceLocation OpLoc,
5340 OverloadCandidate *Cand) {
5341 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5342 std::string TypeStr("operator");
5343 TypeStr += Opc;
5344 TypeStr += "(";
5345 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5346 if (Cand->Conversions.size() == 1) {
5347 TypeStr += ")";
5348 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5349 } else {
5350 TypeStr += ", ";
5351 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5352 TypeStr += ")";
5353 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5354 }
5355}
5356
5357void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5358 OverloadCandidate *Cand) {
5359 unsigned NoOperands = Cand->Conversions.size();
5360 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5361 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00005362 if (ICS.isBad()) break; // all meaningless after first invalid
5363 if (!ICS.isAmbiguous()) continue;
5364
5365 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005366 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00005367 }
5368}
5369
John McCall1b77e732010-01-15 23:32:50 +00005370SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5371 if (Cand->Function)
5372 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00005373 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00005374 return Cand->Surrogate->getLocation();
5375 return SourceLocation();
5376}
5377
John McCallbf65c0b2010-01-12 00:48:53 +00005378struct CompareOverloadCandidatesForDisplay {
5379 Sema &S;
5380 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00005381
5382 bool operator()(const OverloadCandidate *L,
5383 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00005384 // Fast-path this check.
5385 if (L == R) return false;
5386
John McCall81201622010-01-08 04:41:39 +00005387 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00005388 if (L->Viable) {
5389 if (!R->Viable) return true;
5390
5391 // TODO: introduce a tri-valued comparison for overload
5392 // candidates. Would be more worthwhile if we had a sort
5393 // that could exploit it.
John McCall5769d612010-02-08 23:07:23 +00005394 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5395 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00005396 } else if (R->Viable)
5397 return false;
John McCall81201622010-01-08 04:41:39 +00005398
John McCall1b77e732010-01-15 23:32:50 +00005399 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00005400
John McCall1b77e732010-01-15 23:32:50 +00005401 // Criteria by which we can sort non-viable candidates:
5402 if (!L->Viable) {
5403 // 1. Arity mismatches come after other candidates.
5404 if (L->FailureKind == ovl_fail_too_many_arguments ||
5405 L->FailureKind == ovl_fail_too_few_arguments)
5406 return false;
5407 if (R->FailureKind == ovl_fail_too_many_arguments ||
5408 R->FailureKind == ovl_fail_too_few_arguments)
5409 return true;
John McCall81201622010-01-08 04:41:39 +00005410
John McCall717e8912010-01-23 05:17:32 +00005411 // 2. Bad conversions come first and are ordered by the number
5412 // of bad conversions and quality of good conversions.
5413 if (L->FailureKind == ovl_fail_bad_conversion) {
5414 if (R->FailureKind != ovl_fail_bad_conversion)
5415 return true;
5416
5417 // If there's any ordering between the defined conversions...
5418 // FIXME: this might not be transitive.
5419 assert(L->Conversions.size() == R->Conversions.size());
5420
5421 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00005422 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5423 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall717e8912010-01-23 05:17:32 +00005424 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5425 R->Conversions[I])) {
5426 case ImplicitConversionSequence::Better:
5427 leftBetter++;
5428 break;
5429
5430 case ImplicitConversionSequence::Worse:
5431 leftBetter--;
5432 break;
5433
5434 case ImplicitConversionSequence::Indistinguishable:
5435 break;
5436 }
5437 }
5438 if (leftBetter > 0) return true;
5439 if (leftBetter < 0) return false;
5440
5441 } else if (R->FailureKind == ovl_fail_bad_conversion)
5442 return false;
5443
John McCall1b77e732010-01-15 23:32:50 +00005444 // TODO: others?
5445 }
5446
5447 // Sort everything else by location.
5448 SourceLocation LLoc = GetLocationForCandidate(L);
5449 SourceLocation RLoc = GetLocationForCandidate(R);
5450
5451 // Put candidates without locations (e.g. builtins) at the end.
5452 if (LLoc.isInvalid()) return false;
5453 if (RLoc.isInvalid()) return true;
5454
5455 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00005456 }
5457};
5458
John McCall717e8912010-01-23 05:17:32 +00005459/// CompleteNonViableCandidate - Normally, overload resolution only
5460/// computes up to the first
5461void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5462 Expr **Args, unsigned NumArgs) {
5463 assert(!Cand->Viable);
5464
5465 // Don't do anything on failures other than bad conversion.
5466 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5467
5468 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00005469 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCall717e8912010-01-23 05:17:32 +00005470 unsigned ConvCount = Cand->Conversions.size();
5471 while (true) {
5472 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5473 ConvIdx++;
5474 if (Cand->Conversions[ConvIdx - 1].isBad())
5475 break;
5476 }
5477
5478 if (ConvIdx == ConvCount)
5479 return;
5480
John McCallb1bdc622010-02-25 01:37:24 +00005481 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
5482 "remaining conversion is initialized?");
5483
Douglas Gregor23ef6c02010-04-16 17:45:54 +00005484 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00005485 // operation somehow.
5486 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00005487
5488 const FunctionProtoType* Proto;
5489 unsigned ArgIdx = ConvIdx;
5490
5491 if (Cand->IsSurrogate) {
5492 QualType ConvType
5493 = Cand->Surrogate->getConversionType().getNonReferenceType();
5494 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5495 ConvType = ConvPtrType->getPointeeType();
5496 Proto = ConvType->getAs<FunctionProtoType>();
5497 ArgIdx--;
5498 } else if (Cand->Function) {
5499 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
5500 if (isa<CXXMethodDecl>(Cand->Function) &&
5501 !isa<CXXConstructorDecl>(Cand->Function))
5502 ArgIdx--;
5503 } else {
5504 // Builtin binary operator with a bad first conversion.
5505 assert(ConvCount <= 3);
5506 for (; ConvIdx != ConvCount; ++ConvIdx)
5507 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005508 = TryCopyInitialization(S, Args[ConvIdx],
5509 Cand->BuiltinTypes.ParamTypes[ConvIdx],
5510 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00005511 /*InOverloadResolution*/ true);
John McCall717e8912010-01-23 05:17:32 +00005512 return;
5513 }
5514
5515 // Fill in the rest of the conversions.
5516 unsigned NumArgsInProto = Proto->getNumArgs();
5517 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
5518 if (ArgIdx < NumArgsInProto)
5519 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005520 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
5521 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00005522 /*InOverloadResolution=*/true);
John McCall717e8912010-01-23 05:17:32 +00005523 else
5524 Cand->Conversions[ConvIdx].setEllipsis();
5525 }
5526}
5527
John McCalla1d7d622010-01-08 00:58:21 +00005528} // end anonymous namespace
5529
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005530/// PrintOverloadCandidates - When overload resolution fails, prints
5531/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00005532/// set.
Mike Stump1eb44332009-09-09 15:08:12 +00005533void
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005534Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall81201622010-01-08 04:41:39 +00005535 OverloadCandidateDisplayKind OCD,
John McCallcbce6062010-01-12 07:18:19 +00005536 Expr **Args, unsigned NumArgs,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005537 const char *Opc,
Fariborz Jahanian16a5eac2009-10-09 00:13:15 +00005538 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00005539 // Sort the candidates by viability and position. Sorting directly would
5540 // be prohibitive, so we make a set of pointers and sort those.
5541 llvm::SmallVector<OverloadCandidate*, 32> Cands;
5542 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
5543 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5544 LastCand = CandidateSet.end();
John McCall717e8912010-01-23 05:17:32 +00005545 Cand != LastCand; ++Cand) {
5546 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00005547 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00005548 else if (OCD == OCD_AllCandidates) {
5549 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
5550 Cands.push_back(Cand);
5551 }
5552 }
5553
John McCallbf65c0b2010-01-12 00:48:53 +00005554 std::sort(Cands.begin(), Cands.end(),
5555 CompareOverloadCandidatesForDisplay(*this));
John McCall81201622010-01-08 04:41:39 +00005556
John McCall1d318332010-01-12 00:44:57 +00005557 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00005558
John McCall81201622010-01-08 04:41:39 +00005559 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
5560 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
5561 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00005562
John McCalla1d7d622010-01-08 00:58:21 +00005563 if (Cand->Function)
John McCall220ccbf2010-01-13 00:25:19 +00005564 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00005565 else if (Cand->IsSurrogate)
5566 NoteSurrogateCandidate(*this, Cand);
5567
5568 // This a builtin candidate. We do not, in general, want to list
5569 // every possible builtin candidate.
John McCall1d318332010-01-12 00:44:57 +00005570 else if (Cand->Viable) {
5571 // Generally we only see ambiguities including viable builtin
5572 // operators if overload resolution got screwed up by an
5573 // ambiguous user-defined conversion.
5574 //
5575 // FIXME: It's quite possible for different conversions to see
5576 // different ambiguities, though.
5577 if (!ReportedAmbiguousConversions) {
5578 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
5579 ReportedAmbiguousConversions = true;
5580 }
John McCalla1d7d622010-01-08 00:58:21 +00005581
John McCall1d318332010-01-12 00:44:57 +00005582 // If this is a viable builtin, print it.
John McCalla1d7d622010-01-08 00:58:21 +00005583 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005584 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005585 }
5586}
5587
John McCall9aa472c2010-03-19 07:35:19 +00005588static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCallc373d482010-01-27 01:50:18 +00005589 if (isa<UnresolvedLookupExpr>(E))
John McCall9aa472c2010-03-19 07:35:19 +00005590 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00005591
John McCall9aa472c2010-03-19 07:35:19 +00005592 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00005593}
5594
Douglas Gregor904eed32008-11-10 20:40:00 +00005595/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
5596/// an overloaded function (C++ [over.over]), where @p From is an
5597/// expression with overloaded function type and @p ToType is the type
5598/// we're trying to resolve to. For example:
5599///
5600/// @code
5601/// int f(double);
5602/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00005603///
Douglas Gregor904eed32008-11-10 20:40:00 +00005604/// int (*pfd)(double) = f; // selects f(double)
5605/// @endcode
5606///
5607/// This routine returns the resulting FunctionDecl if it could be
5608/// resolved, and NULL otherwise. When @p Complain is true, this
5609/// routine will emit diagnostics if there is an error.
5610FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00005611Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall6bb80172010-03-30 21:47:33 +00005612 bool Complain,
5613 DeclAccessPair &FoundResult) {
Douglas Gregor904eed32008-11-10 20:40:00 +00005614 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00005615 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00005616 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00005617 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00005618 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00005619 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00005620 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00005621 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00005622 FunctionType = MemTypePtr->getPointeeType();
5623 IsMember = true;
5624 }
Douglas Gregor904eed32008-11-10 20:40:00 +00005625
Douglas Gregor904eed32008-11-10 20:40:00 +00005626 // C++ [over.over]p1:
5627 // [...] [Note: any redundant set of parentheses surrounding the
5628 // overloaded function name is ignored (5.1). ]
Douglas Gregor904eed32008-11-10 20:40:00 +00005629 // C++ [over.over]p1:
5630 // [...] The overloaded function name can be preceded by the &
5631 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00005632 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5633 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
5634 if (OvlExpr->hasExplicitTemplateArgs()) {
5635 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5636 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregor904eed32008-11-10 20:40:00 +00005637 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00005638
5639 // We expect a pointer or reference to function, or a function pointer.
5640 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
5641 if (!FunctionType->isFunctionType()) {
5642 if (Complain)
5643 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
5644 << OvlExpr->getName() << ToType;
5645
5646 return 0;
5647 }
5648
5649 assert(From->getType() == Context.OverloadTy);
Douglas Gregor904eed32008-11-10 20:40:00 +00005650
Douglas Gregor904eed32008-11-10 20:40:00 +00005651 // Look through all of the overloaded functions, searching for one
5652 // whose type matches exactly.
John McCall9aa472c2010-03-19 07:35:19 +00005653 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb7a09262010-04-01 18:32:35 +00005654 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
5655
Douglas Gregor00aeb522009-07-08 23:33:52 +00005656 bool FoundNonTemplateFunction = false;
John McCall7bb12da2010-02-02 06:20:04 +00005657 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5658 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00005659 // Look through any using declarations to find the underlying function.
5660 NamedDecl *Fn = (*I)->getUnderlyingDecl();
5661
Douglas Gregor904eed32008-11-10 20:40:00 +00005662 // C++ [over.over]p3:
5663 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00005664 // targets of type "pointer-to-function" or "reference-to-function."
5665 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00005666 // type "pointer-to-member-function."
5667 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00005668
Mike Stump1eb44332009-09-09 15:08:12 +00005669 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthbd647292009-12-29 06:17:27 +00005670 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump1eb44332009-09-09 15:08:12 +00005671 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00005672 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00005673 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00005674 // static when converting to member pointer.
5675 if (Method->isStatic() == IsMember)
5676 continue;
5677 } else if (IsMember)
5678 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00005679
Douglas Gregor00aeb522009-07-08 23:33:52 +00005680 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00005681 // If the name is a function template, template argument deduction is
5682 // done (14.8.2.2), and if the argument deduction succeeds, the
5683 // resulting template argument list is used to generate a single
5684 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00005685 // overloaded functions considered.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005686 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor83314aa2009-07-08 20:55:45 +00005687 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00005688 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor83314aa2009-07-08 20:55:45 +00005689 if (TemplateDeductionResult Result
John McCall7bb12da2010-02-02 06:20:04 +00005690 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00005691 FunctionType, Specialization, Info)) {
5692 // FIXME: make a note of the failed deduction for diagnostics.
5693 (void)Result;
5694 } else {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005695 // FIXME: If the match isn't exact, shouldn't we just drop this as
5696 // a candidate? Find a testcase before changing the code.
Mike Stump1eb44332009-09-09 15:08:12 +00005697 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00005698 == Context.getCanonicalType(Specialization->getType()));
John McCall9aa472c2010-03-19 07:35:19 +00005699 Matches.push_back(std::make_pair(I.getPair(),
5700 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor83314aa2009-07-08 20:55:45 +00005701 }
John McCallba135432009-11-21 08:51:07 +00005702
5703 continue;
Douglas Gregor83314aa2009-07-08 20:55:45 +00005704 }
Mike Stump1eb44332009-09-09 15:08:12 +00005705
Chandler Carruthbd647292009-12-29 06:17:27 +00005706 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00005707 // Skip non-static functions when converting to pointer, and static
5708 // when converting to member pointer.
5709 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00005710 continue;
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005711
5712 // If we have explicit template arguments, skip non-templates.
John McCall7bb12da2010-02-02 06:20:04 +00005713 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005714 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00005715 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00005716 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00005717
Chandler Carruthbd647292009-12-29 06:17:27 +00005718 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00005719 QualType ResultTy;
5720 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5721 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5722 ResultTy)) {
John McCall9aa472c2010-03-19 07:35:19 +00005723 Matches.push_back(std::make_pair(I.getPair(),
5724 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00005725 FoundNonTemplateFunction = true;
5726 }
Mike Stump1eb44332009-09-09 15:08:12 +00005727 }
Douglas Gregor904eed32008-11-10 20:40:00 +00005728 }
5729
Douglas Gregor00aeb522009-07-08 23:33:52 +00005730 // If there were 0 or 1 matches, we're done.
Douglas Gregor1a8cf732010-04-14 23:11:21 +00005731 if (Matches.empty()) {
5732 if (Complain) {
5733 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
5734 << OvlExpr->getName() << FunctionType;
5735 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5736 E = OvlExpr->decls_end();
5737 I != E; ++I)
5738 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
5739 NoteOverloadCandidate(F);
5740 }
5741
Douglas Gregor00aeb522009-07-08 23:33:52 +00005742 return 0;
Douglas Gregor1a8cf732010-04-14 23:11:21 +00005743 } else if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00005744 FunctionDecl *Result = Matches[0].second;
John McCall6bb80172010-03-30 21:47:33 +00005745 FoundResult = Matches[0].first;
Sebastian Redl07ab2022009-10-17 21:12:09 +00005746 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCallc373d482010-01-27 01:50:18 +00005747 if (Complain)
John McCall6bb80172010-03-30 21:47:33 +00005748 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redl07ab2022009-10-17 21:12:09 +00005749 return Result;
5750 }
Douglas Gregor00aeb522009-07-08 23:33:52 +00005751
5752 // C++ [over.over]p4:
5753 // If more than one function is selected, [...]
Douglas Gregor312a2022009-09-26 03:56:17 +00005754 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005755 // [...] and any given function template specialization F1 is
5756 // eliminated if the set contains a second function template
5757 // specialization whose function template is more specialized
5758 // than the function template of F1 according to the partial
5759 // ordering rules of 14.5.5.2.
5760
5761 // The algorithm specified above is quadratic. We instead use a
5762 // two-pass algorithm (similar to the one used to identify the
5763 // best viable function in an overload set) that identifies the
5764 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00005765
5766 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
5767 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5768 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCallc373d482010-01-27 01:50:18 +00005769
5770 UnresolvedSetIterator Result =
John McCall9aa472c2010-03-19 07:35:19 +00005771 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redl07ab2022009-10-17 21:12:09 +00005772 TPOC_Other, From->getLocStart(),
5773 PDiag(),
5774 PDiag(diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00005775 << Matches[0].second->getDeclName(),
John McCall220ccbf2010-01-13 00:25:19 +00005776 PDiag(diag::note_ovl_candidate)
5777 << (unsigned) oc_function_template);
John McCall9aa472c2010-03-19 07:35:19 +00005778 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCallc373d482010-01-27 01:50:18 +00005779 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall6bb80172010-03-30 21:47:33 +00005780 FoundResult = Matches[Result - MatchesCopy.begin()].first;
John McCallb697e082010-05-06 18:15:07 +00005781 if (Complain) {
John McCall6bb80172010-03-30 21:47:33 +00005782 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCallb697e082010-05-06 18:15:07 +00005783 DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc());
5784 }
John McCallc373d482010-01-27 01:50:18 +00005785 return cast<FunctionDecl>(*Result);
Douglas Gregor00aeb522009-07-08 23:33:52 +00005786 }
Mike Stump1eb44332009-09-09 15:08:12 +00005787
Douglas Gregor312a2022009-09-26 03:56:17 +00005788 // [...] any function template specializations in the set are
5789 // eliminated if the set also contains a non-template function, [...]
John McCallc373d482010-01-27 01:50:18 +00005790 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCall9aa472c2010-03-19 07:35:19 +00005791 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCallc373d482010-01-27 01:50:18 +00005792 ++I;
5793 else {
John McCall9aa472c2010-03-19 07:35:19 +00005794 Matches[I] = Matches[--N];
5795 Matches.set_size(N);
John McCallc373d482010-01-27 01:50:18 +00005796 }
5797 }
Douglas Gregor312a2022009-09-26 03:56:17 +00005798
Mike Stump1eb44332009-09-09 15:08:12 +00005799 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00005800 // selected function.
John McCallc373d482010-01-27 01:50:18 +00005801 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00005802 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall6bb80172010-03-30 21:47:33 +00005803 FoundResult = Matches[0].first;
John McCallb697e082010-05-06 18:15:07 +00005804 if (Complain) {
John McCall9aa472c2010-03-19 07:35:19 +00005805 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
John McCallb697e082010-05-06 18:15:07 +00005806 DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc());
5807 }
John McCall9aa472c2010-03-19 07:35:19 +00005808 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redl07ab2022009-10-17 21:12:09 +00005809 }
Mike Stump1eb44332009-09-09 15:08:12 +00005810
Douglas Gregor00aeb522009-07-08 23:33:52 +00005811 // FIXME: We should probably return the same thing that BestViableFunction
5812 // returns (even if we issue the diagnostics here).
5813 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00005814 << Matches[0].second->getDeclName();
5815 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5816 NoteOverloadCandidate(Matches[I].second);
Douglas Gregor904eed32008-11-10 20:40:00 +00005817 return 0;
5818}
5819
Douglas Gregor4b52e252009-12-21 23:17:24 +00005820/// \brief Given an expression that refers to an overloaded function, try to
5821/// resolve that overloaded function expression down to a single function.
5822///
5823/// This routine can only resolve template-ids that refer to a single function
5824/// template, where that template-id refers to a single template whose template
5825/// arguments are either provided by the template-id or have defaults,
5826/// as described in C++0x [temp.arg.explicit]p3.
5827FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5828 // C++ [over.over]p1:
5829 // [...] [Note: any redundant set of parentheses surrounding the
5830 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00005831 // C++ [over.over]p1:
5832 // [...] The overloaded function name can be preceded by the &
5833 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00005834
5835 if (From->getType() != Context.OverloadTy)
5836 return 0;
5837
5838 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor4b52e252009-12-21 23:17:24 +00005839
5840 // If we didn't actually find any template-ids, we're done.
John McCall7bb12da2010-02-02 06:20:04 +00005841 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00005842 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00005843
5844 TemplateArgumentListInfo ExplicitTemplateArgs;
5845 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor4b52e252009-12-21 23:17:24 +00005846
5847 // Look through all of the overloaded functions, searching for one
5848 // whose type matches exactly.
5849 FunctionDecl *Matched = 0;
John McCall7bb12da2010-02-02 06:20:04 +00005850 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5851 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00005852 // C++0x [temp.arg.explicit]p3:
5853 // [...] In contexts where deduction is done and fails, or in contexts
5854 // where deduction is not done, if a template argument list is
5855 // specified and it, along with any default template arguments,
5856 // identifies a single function template specialization, then the
5857 // template-id is an lvalue for the function template specialization.
5858 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
5859
5860 // C++ [over.over]p2:
5861 // If the name is a function template, template argument deduction is
5862 // done (14.8.2.2), and if the argument deduction succeeds, the
5863 // resulting template argument list is used to generate a single
5864 // function template specialization, which is added to the set of
5865 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00005866 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00005867 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00005868 if (TemplateDeductionResult Result
5869 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5870 Specialization, Info)) {
5871 // FIXME: make a note of the failed deduction for diagnostics.
5872 (void)Result;
5873 continue;
5874 }
5875
5876 // Multiple matches; we can't resolve to a single declaration.
5877 if (Matched)
5878 return 0;
5879
5880 Matched = Specialization;
5881 }
5882
5883 return Matched;
5884}
5885
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005886/// \brief Add a single candidate to the overload set.
5887static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00005888 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00005889 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005890 Expr **Args, unsigned NumArgs,
5891 OverloadCandidateSet &CandidateSet,
5892 bool PartialOverloading) {
John McCall9aa472c2010-03-19 07:35:19 +00005893 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00005894 if (isa<UsingShadowDecl>(Callee))
5895 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
5896
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005897 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00005898 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCall9aa472c2010-03-19 07:35:19 +00005899 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00005900 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005901 return;
John McCallba135432009-11-21 08:51:07 +00005902 }
5903
5904 if (FunctionTemplateDecl *FuncTemplate
5905 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00005906 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
5907 ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00005908 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00005909 return;
5910 }
5911
5912 assert(false && "unhandled case in overloaded call candidate");
5913
5914 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005915}
5916
5917/// \brief Add the overload candidates named by callee and/or found by argument
5918/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00005919void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005920 Expr **Args, unsigned NumArgs,
5921 OverloadCandidateSet &CandidateSet,
5922 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00005923
5924#ifndef NDEBUG
5925 // Verify that ArgumentDependentLookup is consistent with the rules
5926 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005927 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005928 // Let X be the lookup set produced by unqualified lookup (3.4.1)
5929 // and let Y be the lookup set produced by argument dependent
5930 // lookup (defined as follows). If X contains
5931 //
5932 // -- a declaration of a class member, or
5933 //
5934 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00005935 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005936 //
5937 // -- a declaration that is neither a function or a function
5938 // template
5939 //
5940 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00005941
John McCall3b4294e2009-12-16 12:17:52 +00005942 if (ULE->requiresADL()) {
5943 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5944 E = ULE->decls_end(); I != E; ++I) {
5945 assert(!(*I)->getDeclContext()->isRecord());
5946 assert(isa<UsingShadowDecl>(*I) ||
5947 !(*I)->getDeclContext()->isFunctionOrMethod());
5948 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00005949 }
5950 }
5951#endif
5952
John McCall3b4294e2009-12-16 12:17:52 +00005953 // It would be nice to avoid this copy.
5954 TemplateArgumentListInfo TABuffer;
5955 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5956 if (ULE->hasExplicitTemplateArgs()) {
5957 ULE->copyTemplateArgumentsInto(TABuffer);
5958 ExplicitTemplateArgs = &TABuffer;
5959 }
5960
5961 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5962 E = ULE->decls_end(); I != E; ++I)
John McCall9aa472c2010-03-19 07:35:19 +00005963 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00005964 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005965 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00005966
John McCall3b4294e2009-12-16 12:17:52 +00005967 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00005968 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
5969 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005970 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005971 CandidateSet,
5972 PartialOverloading);
5973}
John McCall578b69b2009-12-16 08:11:27 +00005974
John McCall3b4294e2009-12-16 12:17:52 +00005975static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5976 Expr **Args, unsigned NumArgs) {
5977 Fn->Destroy(SemaRef.Context);
5978 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5979 Args[Arg]->Destroy(SemaRef.Context);
5980 return SemaRef.ExprError();
5981}
5982
John McCall578b69b2009-12-16 08:11:27 +00005983/// Attempts to recover from a call where no functions were found.
5984///
5985/// Returns true if new candidates were found.
John McCall3b4294e2009-12-16 12:17:52 +00005986static Sema::OwningExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00005987BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00005988 UnresolvedLookupExpr *ULE,
5989 SourceLocation LParenLoc,
5990 Expr **Args, unsigned NumArgs,
5991 SourceLocation *CommaLocs,
5992 SourceLocation RParenLoc) {
John McCall578b69b2009-12-16 08:11:27 +00005993
5994 CXXScopeSpec SS;
5995 if (ULE->getQualifier()) {
5996 SS.setScopeRep(ULE->getQualifier());
5997 SS.setRange(ULE->getQualifierRange());
5998 }
5999
John McCall3b4294e2009-12-16 12:17:52 +00006000 TemplateArgumentListInfo TABuffer;
6001 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6002 if (ULE->hasExplicitTemplateArgs()) {
6003 ULE->copyTemplateArgumentsInto(TABuffer);
6004 ExplicitTemplateArgs = &TABuffer;
6005 }
6006
John McCall578b69b2009-12-16 08:11:27 +00006007 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6008 Sema::LookupOrdinaryName);
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006009 if (SemaRef.DiagnoseEmptyLookup(S, SS, R))
John McCall3b4294e2009-12-16 12:17:52 +00006010 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCall578b69b2009-12-16 08:11:27 +00006011
John McCall3b4294e2009-12-16 12:17:52 +00006012 assert(!R.empty() && "lookup results empty despite recovery");
6013
6014 // Build an implicit member call if appropriate. Just drop the
6015 // casts and such from the call, we don't really care.
6016 Sema::OwningExprResult NewFn = SemaRef.ExprError();
6017 if ((*R.begin())->isCXXClassMember())
6018 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6019 else if (ExplicitTemplateArgs)
6020 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6021 else
6022 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6023
6024 if (NewFn.isInvalid())
6025 return Destroy(SemaRef, Fn, Args, NumArgs);
6026
6027 Fn->Destroy(SemaRef.Context);
6028
6029 // This shouldn't cause an infinite loop because we're giving it
6030 // an expression with non-empty lookup results, which should never
6031 // end up here.
6032 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
6033 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
6034 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00006035}
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006036
Douglas Gregorf6b89692008-11-26 05:54:23 +00006037/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00006038/// (which eventually refers to the declaration Func) and the call
6039/// arguments Args/NumArgs, attempt to resolve the function call down
6040/// to a specific function. If overload resolution succeeds, returns
6041/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00006042/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00006043/// arguments and Fn, and returns NULL.
John McCall3b4294e2009-12-16 12:17:52 +00006044Sema::OwningExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006045Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00006046 SourceLocation LParenLoc,
6047 Expr **Args, unsigned NumArgs,
6048 SourceLocation *CommaLocs,
6049 SourceLocation RParenLoc) {
6050#ifndef NDEBUG
6051 if (ULE->requiresADL()) {
6052 // To do ADL, we must have found an unqualified name.
6053 assert(!ULE->getQualifier() && "qualified name with ADL");
6054
6055 // We don't perform ADL for implicit declarations of builtins.
6056 // Verify that this was correctly set up.
6057 FunctionDecl *F;
6058 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6059 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6060 F->getBuiltinID() && F->isImplicit())
6061 assert(0 && "performing ADL for builtin");
6062
6063 // We don't perform ADL in C.
6064 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6065 }
6066#endif
6067
John McCall5769d612010-02-08 23:07:23 +00006068 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00006069
John McCall3b4294e2009-12-16 12:17:52 +00006070 // Add the functions denoted by the callee to the set of candidate
6071 // functions, including those from argument-dependent lookup.
6072 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00006073
6074 // If we found nothing, try to recover.
6075 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6076 // bailout out if it fails.
John McCall3b4294e2009-12-16 12:17:52 +00006077 if (CandidateSet.empty())
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006078 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00006079 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00006080
Douglas Gregorf6b89692008-11-26 05:54:23 +00006081 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006082 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00006083 case OR_Success: {
6084 FunctionDecl *FDecl = Best->Function;
John McCall9aa472c2010-03-19 07:35:19 +00006085 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00006086 DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00006087 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall3b4294e2009-12-16 12:17:52 +00006088 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6089 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00006090
6091 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00006092 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00006093 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00006094 << ULE->getName() << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006095 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00006096 break;
6097
6098 case OR_Ambiguous:
6099 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00006100 << ULE->getName() << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006101 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00006102 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006103
6104 case OR_Deleted:
6105 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6106 << Best->Function->isDeleted()
John McCall3b4294e2009-12-16 12:17:52 +00006107 << ULE->getName()
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006108 << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006109 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006110 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00006111 }
6112
6113 // Overload resolution failed. Destroy all of the subexpressions and
6114 // return NULL.
6115 Fn->Destroy(Context);
6116 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
6117 Args[Arg]->Destroy(Context);
John McCall3b4294e2009-12-16 12:17:52 +00006118 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00006119}
6120
John McCall6e266892010-01-26 03:27:55 +00006121static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00006122 return Functions.size() > 1 ||
6123 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6124}
6125
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006126/// \brief Create a unary operation that may resolve to an overloaded
6127/// operator.
6128///
6129/// \param OpLoc The location of the operator itself (e.g., '*').
6130///
6131/// \param OpcIn The UnaryOperator::Opcode that describes this
6132/// operator.
6133///
6134/// \param Functions The set of non-member functions that will be
6135/// considered by overload resolution. The caller needs to build this
6136/// set based on the context using, e.g.,
6137/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6138/// set should not contain any member functions; those will be added
6139/// by CreateOverloadedUnaryOp().
6140///
6141/// \param input The input argument.
John McCall6e266892010-01-26 03:27:55 +00006142Sema::OwningExprResult
6143Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6144 const UnresolvedSetImpl &Fns,
6145 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006146 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
6147 Expr *Input = (Expr *)input.get();
6148
6149 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6150 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6151 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6152
6153 Expr *Args[2] = { Input, 0 };
6154 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00006155
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006156 // For post-increment and post-decrement, add the implicit '0' as
6157 // the second argument, so that we know this is a post-increment or
6158 // post-decrement.
6159 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
6160 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump1eb44332009-09-09 15:08:12 +00006161 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006162 SourceLocation());
6163 NumArgs = 2;
6164 }
6165
6166 if (Input->isTypeDependent()) {
John McCallc373d482010-01-27 01:50:18 +00006167 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00006168 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00006169 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00006170 0, SourceRange(), OpName, OpLoc,
John McCall6e266892010-01-26 03:27:55 +00006171 /*ADL*/ true, IsOverloaded(Fns));
6172 Fn->addDecls(Fns.begin(), Fns.end());
Mike Stump1eb44332009-09-09 15:08:12 +00006173
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006174 input.release();
6175 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6176 &Args[0], NumArgs,
6177 Context.DependentTy,
6178 OpLoc));
6179 }
6180
6181 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00006182 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006183
6184 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00006185 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006186
6187 // Add operator candidates that are member functions.
6188 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6189
John McCall6e266892010-01-26 03:27:55 +00006190 // Add candidates from ADL.
6191 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregordc81c882010-02-05 05:15:43 +00006192 Args, NumArgs,
John McCall6e266892010-01-26 03:27:55 +00006193 /*ExplicitTemplateArgs*/ 0,
6194 CandidateSet);
6195
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006196 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00006197 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006198
6199 // Perform overload resolution.
6200 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006201 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006202 case OR_Success: {
6203 // We found a built-in operator or an overloaded operator.
6204 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00006205
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006206 if (FnDecl) {
6207 // We matched an overloaded operator. Build a call to that
6208 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00006209
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006210 // Convert the arguments.
6211 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00006212 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00006213
John McCall6bb80172010-03-30 21:47:33 +00006214 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6215 Best->FoundDecl, Method))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006216 return ExprError();
6217 } else {
6218 // Convert the arguments.
Douglas Gregore1a5c172009-12-23 17:40:29 +00006219 OwningExprResult InputInit
6220 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregorbaecfed2009-12-23 00:02:00 +00006221 FnDecl->getParamDecl(0)),
Douglas Gregore1a5c172009-12-23 17:40:29 +00006222 SourceLocation(),
6223 move(input));
6224 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006225 return ExprError();
Douglas Gregorbaecfed2009-12-23 00:02:00 +00006226
Douglas Gregore1a5c172009-12-23 17:40:29 +00006227 input = move(InputInit);
Douglas Gregorbaecfed2009-12-23 00:02:00 +00006228 Input = (Expr *)input.get();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006229 }
6230
John McCallb697e082010-05-06 18:15:07 +00006231 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6232
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006233 // Determine the result type
Anders Carlsson26a2a072009-10-13 21:19:37 +00006234 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00006235
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006236 // Build the actual expression node.
6237 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6238 SourceLocation());
6239 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00006240
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006241 input.release();
Eli Friedman4c3b8962009-11-18 03:58:17 +00006242 Args[0] = Input;
Anders Carlsson26a2a072009-10-13 21:19:37 +00006243 ExprOwningPtr<CallExpr> TheCall(this,
6244 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman4c3b8962009-11-18 03:58:17 +00006245 Args, NumArgs, ResultTy, OpLoc));
John McCallb697e082010-05-06 18:15:07 +00006246
Anders Carlsson26a2a072009-10-13 21:19:37 +00006247 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6248 FnDecl))
6249 return ExprError();
6250
6251 return MaybeBindToTemporary(TheCall.release());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006252 } else {
6253 // We matched a built-in operator. Convert the arguments, then
6254 // break out so that we will build the appropriate built-in
6255 // operator node.
6256 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00006257 Best->Conversions[0], AA_Passing))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006258 return ExprError();
6259
6260 break;
6261 }
6262 }
6263
6264 case OR_No_Viable_Function:
6265 // No viable function; fall through to handling this as a
6266 // built-in operator, which will produce an error message for us.
6267 break;
6268
6269 case OR_Ambiguous:
6270 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6271 << UnaryOperator::getOpcodeStr(Opc)
6272 << Input->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006273 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00006274 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006275 return ExprError();
6276
6277 case OR_Deleted:
6278 Diag(OpLoc, diag::err_ovl_deleted_oper)
6279 << Best->Function->isDeleted()
6280 << UnaryOperator::getOpcodeStr(Opc)
6281 << Input->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006282 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006283 return ExprError();
6284 }
6285
6286 // Either we found no viable overloaded operator or we matched a
6287 // built-in operator. In either case, fall through to trying to
6288 // build a built-in operation.
6289 input.release();
6290 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
6291}
6292
Douglas Gregor063daf62009-03-13 18:40:31 +00006293/// \brief Create a binary operation that may resolve to an overloaded
6294/// operator.
6295///
6296/// \param OpLoc The location of the operator itself (e.g., '+').
6297///
6298/// \param OpcIn The BinaryOperator::Opcode that describes this
6299/// operator.
6300///
6301/// \param Functions The set of non-member functions that will be
6302/// considered by overload resolution. The caller needs to build this
6303/// set based on the context using, e.g.,
6304/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6305/// set should not contain any member functions; those will be added
6306/// by CreateOverloadedBinOp().
6307///
6308/// \param LHS Left-hand argument.
6309/// \param RHS Right-hand argument.
Mike Stump1eb44332009-09-09 15:08:12 +00006310Sema::OwningExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00006311Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006312 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00006313 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00006314 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00006315 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006316 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00006317
6318 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6319 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6320 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6321
6322 // If either side is type-dependent, create an appropriate dependent
6323 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006324 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00006325 if (Fns.empty()) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006326 // If there are no functions to store, just build a dependent
6327 // BinaryOperator or CompoundAssignment.
6328 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
6329 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6330 Context.DependentTy, OpLoc));
6331
6332 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6333 Context.DependentTy,
6334 Context.DependentTy,
6335 Context.DependentTy,
6336 OpLoc));
6337 }
John McCall6e266892010-01-26 03:27:55 +00006338
6339 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00006340 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00006341 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00006342 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00006343 0, SourceRange(), OpName, OpLoc,
John McCall6e266892010-01-26 03:27:55 +00006344 /*ADL*/ true, IsOverloaded(Fns));
Mike Stump1eb44332009-09-09 15:08:12 +00006345
John McCall6e266892010-01-26 03:27:55 +00006346 Fn->addDecls(Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00006347 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00006348 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00006349 Context.DependentTy,
6350 OpLoc));
6351 }
6352
6353 // If this is the .* operator, which is not overloadable, just
6354 // create a built-in binary operator.
6355 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006356 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00006357
Sebastian Redl275c2b42009-11-18 23:10:33 +00006358 // If this is the assignment operator, we only perform overload resolution
6359 // if the left-hand side is a class or enumeration type. This is actually
6360 // a hack. The standard requires that we do overload resolution between the
6361 // various built-in candidates, but as DR507 points out, this can lead to
6362 // problems. So we do it this way, which pretty much follows what GCC does.
6363 // Note that we go the traditional code path for compound assignment forms.
6364 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006365 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00006366
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006367 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00006368 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00006369
6370 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00006371 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00006372
6373 // Add operator candidates that are member functions.
6374 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6375
John McCall6e266892010-01-26 03:27:55 +00006376 // Add candidates from ADL.
6377 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6378 Args, 2,
6379 /*ExplicitTemplateArgs*/ 0,
6380 CandidateSet);
6381
Douglas Gregor063daf62009-03-13 18:40:31 +00006382 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00006383 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00006384
6385 // Perform overload resolution.
6386 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006387 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00006388 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00006389 // We found a built-in operator or an overloaded operator.
6390 FunctionDecl *FnDecl = Best->Function;
6391
6392 if (FnDecl) {
6393 // We matched an overloaded operator. Build a call to that
6394 // operator.
6395
6396 // Convert the arguments.
6397 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00006398 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +00006399 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00006400
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006401 OwningExprResult Arg1
6402 = PerformCopyInitialization(
6403 InitializedEntity::InitializeParameter(
6404 FnDecl->getParamDecl(0)),
6405 SourceLocation(),
6406 Owned(Args[1]));
6407 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00006408 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006409
Douglas Gregor5fccd362010-03-03 23:55:11 +00006410 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00006411 Best->FoundDecl, Method))
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006412 return ExprError();
6413
6414 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00006415 } else {
6416 // Convert the arguments.
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006417 OwningExprResult Arg0
6418 = PerformCopyInitialization(
6419 InitializedEntity::InitializeParameter(
6420 FnDecl->getParamDecl(0)),
6421 SourceLocation(),
6422 Owned(Args[0]));
6423 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00006424 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006425
6426 OwningExprResult Arg1
6427 = PerformCopyInitialization(
6428 InitializedEntity::InitializeParameter(
6429 FnDecl->getParamDecl(1)),
6430 SourceLocation(),
6431 Owned(Args[1]));
6432 if (Arg1.isInvalid())
6433 return ExprError();
6434 Args[0] = LHS = Arg0.takeAs<Expr>();
6435 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00006436 }
6437
John McCallb697e082010-05-06 18:15:07 +00006438 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6439
Douglas Gregor063daf62009-03-13 18:40:31 +00006440 // Determine the result type
6441 QualType ResultTy
John McCall183700f2009-09-21 23:43:11 +00006442 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor063daf62009-03-13 18:40:31 +00006443 ResultTy = ResultTy.getNonReferenceType();
6444
6445 // Build the actual expression node.
6446 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00006447 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00006448 UsualUnaryConversions(FnExpr);
6449
Anders Carlsson15ea3782009-10-13 22:43:21 +00006450 ExprOwningPtr<CXXOperatorCallExpr>
6451 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6452 Args, 2, ResultTy,
6453 OpLoc));
6454
6455 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6456 FnDecl))
6457 return ExprError();
6458
6459 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor063daf62009-03-13 18:40:31 +00006460 } else {
6461 // We matched a built-in operator. Convert the arguments, then
6462 // break out so that we will build the appropriate built-in
6463 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006464 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00006465 Best->Conversions[0], AA_Passing) ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006466 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00006467 Best->Conversions[1], AA_Passing))
Douglas Gregor063daf62009-03-13 18:40:31 +00006468 return ExprError();
6469
6470 break;
6471 }
6472 }
6473
Douglas Gregor33074752009-09-30 21:46:01 +00006474 case OR_No_Viable_Function: {
6475 // C++ [over.match.oper]p9:
6476 // If the operator is the operator , [...] and there are no
6477 // viable functions, then the operator is assumed to be the
6478 // built-in operator and interpreted according to clause 5.
6479 if (Opc == BinaryOperator::Comma)
6480 break;
6481
Sebastian Redl8593c782009-05-21 11:50:50 +00006482 // For class as left operand for assignment or compound assigment operator
6483 // do not fall through to handling in built-in, but report that no overloaded
6484 // assignment operator found
Douglas Gregor33074752009-09-30 21:46:01 +00006485 OwningExprResult Result = ExprError();
6486 if (Args[0]->getType()->isRecordType() &&
6487 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00006488 Diag(OpLoc, diag::err_ovl_no_viable_oper)
6489 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006490 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00006491 } else {
6492 // No viable function; try to create a built-in operation, which will
6493 // produce an error. Then, show the non-viable candidates.
6494 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00006495 }
Douglas Gregor33074752009-09-30 21:46:01 +00006496 assert(Result.isInvalid() &&
6497 "C++ binary operator overloading is missing candidates!");
6498 if (Result.isInvalid())
John McCallcbce6062010-01-12 07:18:19 +00006499 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00006500 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00006501 return move(Result);
6502 }
Douglas Gregor063daf62009-03-13 18:40:31 +00006503
6504 case OR_Ambiguous:
6505 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6506 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006507 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006508 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00006509 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00006510 return ExprError();
6511
6512 case OR_Deleted:
6513 Diag(OpLoc, diag::err_ovl_deleted_oper)
6514 << Best->Function->isDeleted()
6515 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006516 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006517 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor063daf62009-03-13 18:40:31 +00006518 return ExprError();
John McCall1d318332010-01-12 00:44:57 +00006519 }
Douglas Gregor063daf62009-03-13 18:40:31 +00006520
Douglas Gregor33074752009-09-30 21:46:01 +00006521 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006522 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00006523}
6524
Sebastian Redlf322ed62009-10-29 20:17:01 +00006525Action::OwningExprResult
6526Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
6527 SourceLocation RLoc,
6528 ExprArg Base, ExprArg Idx) {
6529 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
6530 static_cast<Expr*>(Idx.get()) };
6531 DeclarationName OpName =
6532 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
6533
6534 // If either side is type-dependent, create an appropriate dependent
6535 // expression.
6536 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
6537
John McCallc373d482010-01-27 01:50:18 +00006538 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00006539 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00006540 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00006541 0, SourceRange(), OpName, LLoc,
John McCall7453ed42009-11-22 00:44:51 +00006542 /*ADL*/ true, /*Overloaded*/ false);
John McCallf7a1a742009-11-24 19:00:30 +00006543 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00006544
6545 Base.release();
6546 Idx.release();
6547 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
6548 Args, 2,
6549 Context.DependentTy,
6550 RLoc));
6551 }
6552
6553 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00006554 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00006555
6556 // Subscript can only be overloaded as a member function.
6557
6558 // Add operator candidates that are member functions.
6559 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6560
6561 // Add builtin operator candidates.
6562 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6563
6564 // Perform overload resolution.
6565 OverloadCandidateSet::iterator Best;
6566 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
6567 case OR_Success: {
6568 // We found a built-in operator or an overloaded operator.
6569 FunctionDecl *FnDecl = Best->Function;
6570
6571 if (FnDecl) {
6572 // We matched an overloaded operator. Build a call to that
6573 // operator.
6574
John McCall9aa472c2010-03-19 07:35:19 +00006575 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00006576 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +00006577
Sebastian Redlf322ed62009-10-29 20:17:01 +00006578 // Convert the arguments.
6579 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregor5fccd362010-03-03 23:55:11 +00006580 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00006581 Best->FoundDecl, Method))
Sebastian Redlf322ed62009-10-29 20:17:01 +00006582 return ExprError();
6583
Anders Carlsson38f88ab2010-01-29 18:37:50 +00006584 // Convert the arguments.
6585 OwningExprResult InputInit
6586 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6587 FnDecl->getParamDecl(0)),
6588 SourceLocation(),
6589 Owned(Args[1]));
6590 if (InputInit.isInvalid())
6591 return ExprError();
6592
6593 Args[1] = InputInit.takeAs<Expr>();
6594
Sebastian Redlf322ed62009-10-29 20:17:01 +00006595 // Determine the result type
6596 QualType ResultTy
6597 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
6598 ResultTy = ResultTy.getNonReferenceType();
6599
6600 // Build the actual expression node.
6601 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6602 LLoc);
6603 UsualUnaryConversions(FnExpr);
6604
6605 Base.release();
6606 Idx.release();
6607 ExprOwningPtr<CXXOperatorCallExpr>
6608 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
6609 FnExpr, Args, 2,
6610 ResultTy, RLoc));
6611
6612 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
6613 FnDecl))
6614 return ExprError();
6615
6616 return MaybeBindToTemporary(TheCall.release());
6617 } else {
6618 // We matched a built-in operator. Convert the arguments, then
6619 // break out so that we will build the appropriate built-in
6620 // operator node.
6621 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00006622 Best->Conversions[0], AA_Passing) ||
Sebastian Redlf322ed62009-10-29 20:17:01 +00006623 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00006624 Best->Conversions[1], AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00006625 return ExprError();
6626
6627 break;
6628 }
6629 }
6630
6631 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00006632 if (CandidateSet.empty())
6633 Diag(LLoc, diag::err_ovl_no_oper)
6634 << Args[0]->getType() << /*subscript*/ 0
6635 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6636 else
6637 Diag(LLoc, diag::err_ovl_no_viable_subscript)
6638 << Args[0]->getType()
6639 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006640 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall1eb3e102010-01-07 02:04:15 +00006641 "[]", LLoc);
6642 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00006643 }
6644
6645 case OR_Ambiguous:
6646 Diag(LLoc, diag::err_ovl_ambiguous_oper)
6647 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006648 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redlf322ed62009-10-29 20:17:01 +00006649 "[]", LLoc);
6650 return ExprError();
6651
6652 case OR_Deleted:
6653 Diag(LLoc, diag::err_ovl_deleted_oper)
6654 << Best->Function->isDeleted() << "[]"
6655 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006656 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall81201622010-01-08 04:41:39 +00006657 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00006658 return ExprError();
6659 }
6660
6661 // We matched a built-in operator; build it.
6662 Base.release();
6663 Idx.release();
6664 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
6665 Owned(Args[1]), RLoc);
6666}
6667
Douglas Gregor88a35142008-12-22 05:46:06 +00006668/// BuildCallToMemberFunction - Build a call to a member
6669/// function. MemExpr is the expression that refers to the member
6670/// function (and includes the object parameter), Args/NumArgs are the
6671/// arguments to the function call (not including the object
6672/// parameter). The caller needs to validate that the member
6673/// expression refers to a member function or an overloaded member
6674/// function.
John McCallaa81e162009-12-01 22:10:20 +00006675Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00006676Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
6677 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor88a35142008-12-22 05:46:06 +00006678 unsigned NumArgs, SourceLocation *CommaLocs,
6679 SourceLocation RParenLoc) {
6680 // Dig out the member expression. This holds both the object
6681 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00006682 Expr *NakedMemExpr = MemExprE->IgnoreParens();
6683
John McCall129e2df2009-11-30 22:42:35 +00006684 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00006685 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +00006686 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +00006687 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +00006688 if (isa<MemberExpr>(NakedMemExpr)) {
6689 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00006690 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +00006691 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +00006692 Qualifier = MemExpr->getQualifier();
John McCall129e2df2009-11-30 22:42:35 +00006693 } else {
6694 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +00006695 Qualifier = UnresExpr->getQualifier();
6696
John McCall701c89e2009-12-03 04:06:58 +00006697 QualType ObjectType = UnresExpr->getBaseType();
John McCall129e2df2009-11-30 22:42:35 +00006698
Douglas Gregor88a35142008-12-22 05:46:06 +00006699 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +00006700 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00006701
John McCallaa81e162009-12-01 22:10:20 +00006702 // FIXME: avoid copy.
6703 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6704 if (UnresExpr->hasExplicitTemplateArgs()) {
6705 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6706 TemplateArgs = &TemplateArgsBuffer;
6707 }
6708
John McCall129e2df2009-11-30 22:42:35 +00006709 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6710 E = UnresExpr->decls_end(); I != E; ++I) {
6711
John McCall701c89e2009-12-03 04:06:58 +00006712 NamedDecl *Func = *I;
6713 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6714 if (isa<UsingShadowDecl>(Func))
6715 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6716
John McCall129e2df2009-11-30 22:42:35 +00006717 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006718 // If explicit template arguments were provided, we can't call a
6719 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00006720 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006721 continue;
6722
John McCall9aa472c2010-03-19 07:35:19 +00006723 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCall86820f52010-01-26 01:37:31 +00006724 Args, NumArgs,
John McCall701c89e2009-12-03 04:06:58 +00006725 CandidateSet, /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00006726 } else {
John McCall129e2df2009-11-30 22:42:35 +00006727 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +00006728 I.getPair(), ActingDC, TemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00006729 ObjectType, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00006730 CandidateSet,
6731 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00006732 }
Douglas Gregordec06662009-08-21 18:42:58 +00006733 }
Mike Stump1eb44332009-09-09 15:08:12 +00006734
John McCall129e2df2009-11-30 22:42:35 +00006735 DeclarationName DeclName = UnresExpr->getMemberName();
6736
Douglas Gregor88a35142008-12-22 05:46:06 +00006737 OverloadCandidateSet::iterator Best;
John McCall129e2df2009-11-30 22:42:35 +00006738 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00006739 case OR_Success:
6740 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00006741 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +00006742 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00006743 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +00006744 break;
6745
6746 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00006747 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00006748 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00006749 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006750 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00006751 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00006752 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006753
6754 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00006755 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00006756 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006757 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00006758 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00006759 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006760
6761 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00006762 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006763 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00006764 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006765 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006766 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00006767 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006768 }
6769
John McCall6bb80172010-03-30 21:47:33 +00006770 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +00006771
John McCallaa81e162009-12-01 22:10:20 +00006772 // If overload resolution picked a static member, build a
6773 // non-member call based on that function.
6774 if (Method->isStatic()) {
6775 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6776 Args, NumArgs, RParenLoc);
6777 }
6778
John McCall129e2df2009-11-30 22:42:35 +00006779 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00006780 }
6781
6782 assert(Method && "Member call to something that isn't a method?");
Mike Stump1eb44332009-09-09 15:08:12 +00006783 ExprOwningPtr<CXXMemberCallExpr>
John McCallaa81e162009-12-01 22:10:20 +00006784 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump1eb44332009-09-09 15:08:12 +00006785 NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00006786 Method->getResultType().getNonReferenceType(),
6787 RParenLoc));
6788
Anders Carlssoneed3e692009-10-10 00:06:20 +00006789 // Check for a valid return type.
6790 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6791 TheCall.get(), Method))
John McCallaa81e162009-12-01 22:10:20 +00006792 return ExprError();
Anders Carlssoneed3e692009-10-10 00:06:20 +00006793
Douglas Gregor88a35142008-12-22 05:46:06 +00006794 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +00006795 // We only need to do this if there was actually an overload; otherwise
6796 // it was done at lookup.
John McCallaa81e162009-12-01 22:10:20 +00006797 Expr *ObjectArg = MemExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00006798 if (!Method->isStatic() &&
John McCall6bb80172010-03-30 21:47:33 +00006799 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
6800 FoundDecl, Method))
John McCallaa81e162009-12-01 22:10:20 +00006801 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006802 MemExpr->setBase(ObjectArg);
6803
6804 // Convert the rest of the arguments
Douglas Gregor5f970ee2010-05-04 18:18:31 +00006805 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006806 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00006807 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00006808 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006809
Anders Carlssond406bf02009-08-16 01:56:34 +00006810 if (CheckFunctionCall(Method, TheCall.get()))
John McCallaa81e162009-12-01 22:10:20 +00006811 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00006812
John McCallaa81e162009-12-01 22:10:20 +00006813 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor88a35142008-12-22 05:46:06 +00006814}
6815
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006816/// BuildCallToObjectOfClassType - Build a call to an object of class
6817/// type (C++ [over.call.object]), which can end up invoking an
6818/// overloaded function call operator (@c operator()) or performing a
6819/// user-defined conversion on the object argument.
Mike Stump1eb44332009-09-09 15:08:12 +00006820Sema::ExprResult
6821Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00006822 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006823 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00006824 SourceLocation *CommaLocs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006825 SourceLocation RParenLoc) {
6826 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00006827 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006828
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006829 // C++ [over.call.object]p1:
6830 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00006831 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006832 // candidate functions includes at least the function call
6833 // operators of T. The function call operators of T are obtained by
6834 // ordinary lookup of the name operator() in the context of
6835 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +00006836 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00006837 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00006838
6839 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006840 PDiag(diag::err_incomplete_object_call)
Douglas Gregor593564b2009-11-15 07:48:03 +00006841 << Object->getSourceRange()))
6842 return true;
6843
John McCalla24dc2e2009-11-17 02:14:36 +00006844 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
6845 LookupQualifiedName(R, Record->getDecl());
6846 R.suppressDiagnostics();
6847
Douglas Gregor593564b2009-11-15 07:48:03 +00006848 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00006849 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00006850 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCall86820f52010-01-26 01:37:31 +00006851 Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00006852 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00006853 }
Douglas Gregor4a27d702009-10-21 06:18:39 +00006854
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006855 // C++ [over.call.object]p2:
6856 // In addition, for each conversion function declared in T of the
6857 // form
6858 //
6859 // operator conversion-type-id () cv-qualifier;
6860 //
6861 // where cv-qualifier is the same cv-qualification as, or a
6862 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00006863 // denotes the type "pointer to function of (P1,...,Pn) returning
6864 // R", or the type "reference to pointer to function of
6865 // (P1,...,Pn) returning R", or the type "reference to function
6866 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006867 // is also considered as a candidate function. Similarly,
6868 // surrogate call functions are added to the set of candidate
6869 // functions for each conversion function declared in an
6870 // accessible base class provided the function is not hidden
6871 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +00006872 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00006873 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00006874 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00006875 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00006876 NamedDecl *D = *I;
6877 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6878 if (isa<UsingShadowDecl>(D))
6879 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6880
Douglas Gregor4a27d702009-10-21 06:18:39 +00006881 // Skip over templated conversion functions; they aren't
6882 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00006883 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00006884 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006885
John McCall701c89e2009-12-03 04:06:58 +00006886 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCallba135432009-11-21 08:51:07 +00006887
Douglas Gregor4a27d702009-10-21 06:18:39 +00006888 // Strip the reference type (if any) and then the pointer type (if
6889 // any) to get down to what might be a function type.
6890 QualType ConvType = Conv->getConversionType().getNonReferenceType();
6891 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6892 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006893
Douglas Gregor4a27d702009-10-21 06:18:39 +00006894 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall9aa472c2010-03-19 07:35:19 +00006895 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall701c89e2009-12-03 04:06:58 +00006896 Object->getType(), Args, NumArgs,
6897 CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006898 }
Mike Stump1eb44332009-09-09 15:08:12 +00006899
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006900 // Perform overload resolution.
6901 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006902 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006903 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006904 // Overload resolution succeeded; we'll build the appropriate call
6905 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006906 break;
6907
6908 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00006909 if (CandidateSet.empty())
6910 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
6911 << Object->getType() << /*call*/ 1
6912 << Object->getSourceRange();
6913 else
6914 Diag(Object->getSourceRange().getBegin(),
6915 diag::err_ovl_no_viable_object_call)
6916 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006917 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006918 break;
6919
6920 case OR_Ambiguous:
6921 Diag(Object->getSourceRange().getBegin(),
6922 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00006923 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006924 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006925 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006926
6927 case OR_Deleted:
6928 Diag(Object->getSourceRange().getBegin(),
6929 diag::err_ovl_deleted_object_call)
6930 << Best->Function->isDeleted()
6931 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006932 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006933 break;
Mike Stump1eb44332009-09-09 15:08:12 +00006934 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006935
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006936 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006937 // We had an error; delete all of the subexpressions and return
6938 // the error.
Ted Kremenek8189cde2009-02-07 01:47:29 +00006939 Object->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006940 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek8189cde2009-02-07 01:47:29 +00006941 Args[ArgIdx]->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006942 return true;
6943 }
6944
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006945 if (Best->Function == 0) {
6946 // Since there is no function declaration, this is one of the
6947 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00006948 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006949 = cast<CXXConversionDecl>(
6950 Best->Conversions[0].UserDefined.ConversionFunction);
6951
John McCall9aa472c2010-03-19 07:35:19 +00006952 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00006953 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00006954
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006955 // We selected one of the surrogate functions that converts the
6956 // object parameter to a function pointer. Perform the conversion
6957 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00006958
6959 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00006960 // and then call it.
John McCall6bb80172010-03-30 21:47:33 +00006961 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
6962 Conv);
Fariborz Jahanianb7400232009-09-28 23:23:40 +00006963
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00006964 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00006965 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
Douglas Gregoraa0be172010-04-13 15:50:39 +00006966 CommaLocs, RParenLoc).result();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006967 }
6968
John McCall9aa472c2010-03-19 07:35:19 +00006969 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00006970 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00006971
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006972 // We found an overloaded operator(). Build a CXXOperatorCallExpr
6973 // that calls this method, using Object for the implicit object
6974 // parameter and passing along the remaining arguments.
6975 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall183700f2009-09-21 23:43:11 +00006976 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006977
6978 unsigned NumArgsInProto = Proto->getNumArgs();
6979 unsigned NumArgsToCheck = NumArgs;
6980
6981 // Build the full argument list for the method call (the
6982 // implicit object parameter is placed at the beginning of the
6983 // list).
6984 Expr **MethodArgs;
6985 if (NumArgs < NumArgsInProto) {
6986 NumArgsToCheck = NumArgsInProto;
6987 MethodArgs = new Expr*[NumArgsInProto + 1];
6988 } else {
6989 MethodArgs = new Expr*[NumArgs + 1];
6990 }
6991 MethodArgs[0] = Object;
6992 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6993 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00006994
6995 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00006996 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006997 UsualUnaryConversions(NewFn);
6998
6999 // Once we've built TheCall, all of the expressions are properly
7000 // owned.
7001 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00007002 ExprOwningPtr<CXXOperatorCallExpr>
7003 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor063daf62009-03-13 18:40:31 +00007004 MethodArgs, NumArgs + 1,
Ted Kremenek8189cde2009-02-07 01:47:29 +00007005 ResultTy, RParenLoc));
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007006 delete [] MethodArgs;
7007
Anders Carlsson07d68f12009-10-13 21:49:31 +00007008 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
7009 Method))
7010 return true;
7011
Douglas Gregor518fda12009-01-13 05:10:00 +00007012 // We may have default arguments. If so, we need to allocate more
7013 // slots in the call for them.
7014 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00007015 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00007016 else if (NumArgs > NumArgsInProto)
7017 NumArgsToCheck = NumArgsInProto;
7018
Chris Lattner312531a2009-04-12 08:11:20 +00007019 bool IsError = false;
7020
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007021 // Initialize the implicit object parameter.
Douglas Gregor5fccd362010-03-03 23:55:11 +00007022 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007023 Best->FoundDecl, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007024 TheCall->setArg(0, Object);
7025
Chris Lattner312531a2009-04-12 08:11:20 +00007026
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007027 // Check the argument types.
7028 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007029 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00007030 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007031 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00007032
Douglas Gregor518fda12009-01-13 05:10:00 +00007033 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +00007034
7035 OwningExprResult InputInit
7036 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7037 Method->getParamDecl(i)),
7038 SourceLocation(), Owned(Arg));
7039
7040 IsError |= InputInit.isInvalid();
7041 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00007042 } else {
Douglas Gregord47c47d2009-11-09 19:27:57 +00007043 OwningExprResult DefArg
7044 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7045 if (DefArg.isInvalid()) {
7046 IsError = true;
7047 break;
7048 }
7049
7050 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00007051 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007052
7053 TheCall->setArg(i + 1, Arg);
7054 }
7055
7056 // If this is a variadic call, handle args passed through "...".
7057 if (Proto->isVariadic()) {
7058 // Promote the arguments (C99 6.5.2.2p7).
7059 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7060 Expr *Arg = Args[i];
Chris Lattner312531a2009-04-12 08:11:20 +00007061 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007062 TheCall->setArg(i + 1, Arg);
7063 }
7064 }
7065
Chris Lattner312531a2009-04-12 08:11:20 +00007066 if (IsError) return true;
7067
Anders Carlssond406bf02009-08-16 01:56:34 +00007068 if (CheckFunctionCall(Method, TheCall.get()))
7069 return true;
7070
Douglas Gregoraa0be172010-04-13 15:50:39 +00007071 return MaybeBindToTemporary(TheCall.release()).result();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007072}
7073
Douglas Gregor8ba10742008-11-20 16:27:02 +00007074/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00007075/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00007076/// @c Member is the name of the member we're trying to find.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007077Sema::OwningExprResult
7078Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
7079 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor8ba10742008-11-20 16:27:02 +00007080 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00007081
John McCall5769d612010-02-08 23:07:23 +00007082 SourceLocation Loc = Base->getExprLoc();
7083
Douglas Gregor8ba10742008-11-20 16:27:02 +00007084 // C++ [over.ref]p1:
7085 //
7086 // [...] An expression x->m is interpreted as (x.operator->())->m
7087 // for a class object x of type T if T::operator->() exists and if
7088 // the operator is selected as the best match function by the
7089 // overload resolution mechanism (13.3).
Douglas Gregor8ba10742008-11-20 16:27:02 +00007090 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +00007091 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +00007092 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007093
John McCall5769d612010-02-08 23:07:23 +00007094 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +00007095 PDiag(diag::err_typecheck_incomplete_tag)
7096 << Base->getSourceRange()))
7097 return ExprError();
7098
John McCalla24dc2e2009-11-17 02:14:36 +00007099 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7100 LookupQualifiedName(R, BaseRecord->getDecl());
7101 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00007102
7103 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00007104 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00007105 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00007106 /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00007107 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00007108
7109 // Perform overload resolution.
7110 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00007111 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00007112 case OR_Success:
7113 // Overload resolution succeeded; we'll build the call below.
7114 break;
7115
7116 case OR_No_Viable_Function:
7117 if (CandidateSet.empty())
7118 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007119 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007120 else
7121 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007122 << "operator->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007123 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007124 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007125
7126 case OR_Ambiguous:
7127 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlssone30572a2009-09-10 23:18:36 +00007128 << "->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007129 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007130 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007131
7132 case OR_Deleted:
7133 Diag(OpLoc, diag::err_ovl_deleted_oper)
7134 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00007135 << "->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007136 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007137 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007138 }
7139
John McCall9aa472c2010-03-19 07:35:19 +00007140 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007141 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +00007142
Douglas Gregor8ba10742008-11-20 16:27:02 +00007143 // Convert the object parameter.
7144 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00007145 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7146 Best->FoundDecl, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007147 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00007148
7149 // No concerns about early exits now.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007150 BaseIn.release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007151
7152 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00007153 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7154 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00007155 UsualUnaryConversions(FnExpr);
Anders Carlsson15ea3782009-10-13 22:43:21 +00007156
7157 QualType ResultTy = Method->getResultType().getNonReferenceType();
7158 ExprOwningPtr<CXXOperatorCallExpr>
7159 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7160 &Base, 1, ResultTy, OpLoc));
7161
7162 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
7163 Method))
7164 return ExprError();
7165 return move(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00007166}
7167
Douglas Gregor904eed32008-11-10 20:40:00 +00007168/// FixOverloadedFunctionReference - E is an expression that refers to
7169/// a C++ overloaded function (possibly with some parentheses and
7170/// perhaps a '&' around it). We have resolved the overloaded function
7171/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00007172/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +00007173Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +00007174 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00007175 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00007176 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7177 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00007178 if (SubExpr == PE->getSubExpr())
7179 return PE->Retain();
7180
7181 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7182 }
7183
7184 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00007185 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7186 Found, Fn);
Douglas Gregor097bfb12009-10-23 22:18:25 +00007187 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00007188 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00007189 "Implicit cast type cannot be determined from overload");
Douglas Gregor699ee522009-11-20 19:42:02 +00007190 if (SubExpr == ICE->getSubExpr())
7191 return ICE->Retain();
7192
7193 return new (Context) ImplicitCastExpr(ICE->getType(),
7194 ICE->getCastKind(),
Anders Carlssonf1b48b72010-04-24 16:57:13 +00007195 SubExpr, CXXBaseSpecifierArray(),
Douglas Gregor699ee522009-11-20 19:42:02 +00007196 ICE->isLvalueCast());
7197 }
7198
7199 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007200 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00007201 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00007202 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7203 if (Method->isStatic()) {
7204 // Do nothing: static member functions aren't any different
7205 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00007206 } else {
John McCallf7a1a742009-11-24 19:00:30 +00007207 // Fix the sub expression, which really has to be an
7208 // UnresolvedLookupExpr holding an overloaded member function
7209 // or template.
John McCall6bb80172010-03-30 21:47:33 +00007210 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7211 Found, Fn);
John McCallba135432009-11-21 08:51:07 +00007212 if (SubExpr == UnOp->getSubExpr())
7213 return UnOp->Retain();
Douglas Gregor699ee522009-11-20 19:42:02 +00007214
John McCallba135432009-11-21 08:51:07 +00007215 assert(isa<DeclRefExpr>(SubExpr)
7216 && "fixed to something other than a decl ref");
7217 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7218 && "fixed to a member ref with no nested name qualifier");
7219
7220 // We have taken the address of a pointer to member
7221 // function. Perform the computation here so that we get the
7222 // appropriate pointer to member type.
7223 QualType ClassType
7224 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7225 QualType MemPtrType
7226 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7227
7228 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7229 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00007230 }
7231 }
John McCall6bb80172010-03-30 21:47:33 +00007232 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7233 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00007234 if (SubExpr == UnOp->getSubExpr())
7235 return UnOp->Retain();
Anders Carlsson96ad5332009-10-21 17:16:23 +00007236
Douglas Gregor699ee522009-11-20 19:42:02 +00007237 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7238 Context.getPointerType(SubExpr->getType()),
7239 UnOp->getOperatorLoc());
Douglas Gregor699ee522009-11-20 19:42:02 +00007240 }
John McCallba135432009-11-21 08:51:07 +00007241
7242 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00007243 // FIXME: avoid copy.
7244 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00007245 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00007246 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7247 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00007248 }
7249
John McCallba135432009-11-21 08:51:07 +00007250 return DeclRefExpr::Create(Context,
7251 ULE->getQualifier(),
7252 ULE->getQualifierRange(),
7253 Fn,
7254 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00007255 Fn->getType(),
7256 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00007257 }
7258
John McCall129e2df2009-11-30 22:42:35 +00007259 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00007260 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00007261 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7262 if (MemExpr->hasExplicitTemplateArgs()) {
7263 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7264 TemplateArgs = &TemplateArgsBuffer;
7265 }
John McCalld5532b62009-11-23 01:53:49 +00007266
John McCallaa81e162009-12-01 22:10:20 +00007267 Expr *Base;
7268
7269 // If we're filling in
7270 if (MemExpr->isImplicitAccess()) {
7271 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7272 return DeclRefExpr::Create(Context,
7273 MemExpr->getQualifier(),
7274 MemExpr->getQualifierRange(),
7275 Fn,
7276 MemExpr->getMemberLoc(),
7277 Fn->getType(),
7278 TemplateArgs);
Douglas Gregor828a1972010-01-07 23:12:05 +00007279 } else {
7280 SourceLocation Loc = MemExpr->getMemberLoc();
7281 if (MemExpr->getQualifier())
7282 Loc = MemExpr->getQualifierRange().getBegin();
7283 Base = new (Context) CXXThisExpr(Loc,
7284 MemExpr->getBaseType(),
7285 /*isImplicit=*/true);
7286 }
John McCallaa81e162009-12-01 22:10:20 +00007287 } else
7288 Base = MemExpr->getBase()->Retain();
7289
7290 return MemberExpr::Create(Context, Base,
Douglas Gregor699ee522009-11-20 19:42:02 +00007291 MemExpr->isArrow(),
7292 MemExpr->getQualifier(),
7293 MemExpr->getQualifierRange(),
7294 Fn,
John McCall6bb80172010-03-30 21:47:33 +00007295 Found,
John McCalld5532b62009-11-23 01:53:49 +00007296 MemExpr->getMemberLoc(),
John McCallaa81e162009-12-01 22:10:20 +00007297 TemplateArgs,
Douglas Gregor699ee522009-11-20 19:42:02 +00007298 Fn->getType());
7299 }
7300
Douglas Gregor699ee522009-11-20 19:42:02 +00007301 assert(false && "Invalid reference to overloaded function");
7302 return E->Retain();
Douglas Gregor904eed32008-11-10 20:40:00 +00007303}
7304
Douglas Gregor20093b42009-12-09 23:02:17 +00007305Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCall161755a2010-04-06 21:38:20 +00007306 DeclAccessPair Found,
Douglas Gregor20093b42009-12-09 23:02:17 +00007307 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +00007308 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +00007309}
7310
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007311} // end namespace clang