blob: d3e8243f94f6ca2e585c3cd958c25c88efb615f3 [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 Gregorfb4a5432010-05-18 22:42:18 +000055 ICC_Conversion,
56 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000057 ICC_Conversion
58 };
59 return Category[(int)Kind];
60}
61
62/// GetConversionRank - Retrieve the implicit conversion rank
63/// corresponding to the given implicit conversion kind.
64ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
65 static const ImplicitConversionRank
66 Rank[(int)ICK_Num_Conversion_Kinds] = {
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Exact_Match,
70 ICR_Exact_Match,
71 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +000072 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000073 ICR_Promotion,
74 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000075 ICR_Promotion,
76 ICR_Conversion,
77 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000078 ICR_Conversion,
79 ICR_Conversion,
80 ICR_Conversion,
81 ICR_Conversion,
82 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000083 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000084 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +000085 ICR_Conversion,
86 ICR_Conversion,
Chandler Carruth23a370f2010-02-25 07:20:54 +000087 ICR_Complex_Real_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000088 };
89 return Rank[(int)Kind];
90}
91
92/// GetImplicitConversionName - Return the name of this kind of
93/// implicit conversion.
94const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +000095 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000096 "No conversion",
97 "Lvalue-to-rvalue",
98 "Array-to-pointer",
99 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000100 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000101 "Qualification",
102 "Integral promotion",
103 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000104 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000105 "Integral conversion",
106 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000107 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000108 "Floating-integral conversion",
109 "Pointer conversion",
110 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000111 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000112 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000113 "Derived-to-base conversion",
114 "Vector conversion",
115 "Vector splat",
116 "Complex-real conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000117 };
118 return Name[Kind];
119}
120
Douglas Gregor60d62c22008-10-31 16:23:19 +0000121/// StandardConversionSequence - Set the standard conversion
122/// sequence to the identity conversion.
123void StandardConversionSequence::setAsIdentityConversion() {
124 First = ICK_Identity;
125 Second = ICK_Identity;
126 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000127 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000128 ReferenceBinding = false;
129 DirectBinding = false;
Sebastian Redl85002392009-03-29 22:46:24 +0000130 RRefBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000131 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000132}
133
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000134/// getRank - Retrieve the rank of this standard conversion sequence
135/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
136/// implicit conversions.
137ImplicitConversionRank StandardConversionSequence::getRank() const {
138 ImplicitConversionRank Rank = ICR_Exact_Match;
139 if (GetConversionRank(First) > Rank)
140 Rank = GetConversionRank(First);
141 if (GetConversionRank(Second) > Rank)
142 Rank = GetConversionRank(Second);
143 if (GetConversionRank(Third) > Rank)
144 Rank = GetConversionRank(Third);
145 return Rank;
146}
147
148/// isPointerConversionToBool - Determines whether this conversion is
149/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000150/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000151/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000152bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000153 // Note that FromType has not necessarily been transformed by the
154 // array-to-pointer or function-to-pointer implicit conversions, so
155 // check for their presence as well as checking whether FromType is
156 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000157 if (getToType(1)->isBooleanType() &&
John McCall1d318332010-01-12 00:44:57 +0000158 (getFromType()->isPointerType() || getFromType()->isBlockPointerType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000159 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
160 return true;
161
162 return false;
163}
164
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000165/// isPointerConversionToVoidPointer - Determines whether this
166/// conversion is a conversion of a pointer to a void pointer. This is
167/// used as part of the ranking of standard conversion sequences (C++
168/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000169bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000170StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000171isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000172 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000173 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000174
175 // Note that FromType has not necessarily been transformed by the
176 // array-to-pointer implicit conversion, so check for its presence
177 // and redo the conversion to get a pointer.
178 if (First == ICK_Array_To_Pointer)
179 FromType = Context.getArrayDecayedType(FromType);
180
Douglas Gregor01919692009-12-13 21:37:05 +0000181 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000182 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000183 return ToPtrType->getPointeeType()->isVoidType();
184
185 return false;
186}
187
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000188/// DebugPrint - Print this standard conversion sequence to standard
189/// error. Useful for debugging overloading issues.
190void StandardConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000191 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000192 bool PrintedSomething = false;
193 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000194 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000195 PrintedSomething = true;
196 }
197
198 if (Second != ICK_Identity) {
199 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000200 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000201 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000202 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000203
204 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000205 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000206 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000207 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000208 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000209 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000210 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000211 PrintedSomething = true;
212 }
213
214 if (Third != ICK_Identity) {
215 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000216 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000217 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000218 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000219 PrintedSomething = true;
220 }
221
222 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000223 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000224 }
225}
226
227/// DebugPrint - Print this user-defined conversion sequence to standard
228/// error. Useful for debugging overloading issues.
229void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000230 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000231 if (Before.First || Before.Second || Before.Third) {
232 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000233 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000234 }
Benjamin Kramer900fc632010-04-17 09:33:03 +0000235 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000236 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000237 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000238 After.DebugPrint();
239 }
240}
241
242/// DebugPrint - Print this implicit conversion sequence to standard
243/// error. Useful for debugging overloading issues.
244void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000245 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000246 switch (ConversionKind) {
247 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000248 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000249 Standard.DebugPrint();
250 break;
251 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000252 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000253 UserDefined.DebugPrint();
254 break;
255 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000256 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000257 break;
John McCall1d318332010-01-12 00:44:57 +0000258 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000259 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000260 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000261 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000262 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000263 break;
264 }
265
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000266 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000267}
268
John McCall1d318332010-01-12 00:44:57 +0000269void AmbiguousConversionSequence::construct() {
270 new (&conversions()) ConversionSet();
271}
272
273void AmbiguousConversionSequence::destruct() {
274 conversions().~ConversionSet();
275}
276
277void
278AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
279 FromTypePtr = O.FromTypePtr;
280 ToTypePtr = O.ToTypePtr;
281 new (&conversions()) ConversionSet(O.conversions());
282}
283
Douglas Gregora9333192010-05-08 17:41:32 +0000284namespace {
285 // Structure used by OverloadCandidate::DeductionFailureInfo to store
286 // template parameter and template argument information.
287 struct DFIParamWithArguments {
288 TemplateParameter Param;
289 TemplateArgument FirstArg;
290 TemplateArgument SecondArg;
291 };
292}
293
294/// \brief Convert from Sema's representation of template deduction information
295/// to the form used in overload-candidate information.
296OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000297static MakeDeductionFailureInfo(ASTContext &Context,
298 Sema::TemplateDeductionResult TDK,
Douglas Gregorec20f462010-05-08 20:07:26 +0000299 Sema::TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000300 OverloadCandidate::DeductionFailureInfo Result;
301 Result.Result = static_cast<unsigned>(TDK);
302 Result.Data = 0;
303 switch (TDK) {
304 case Sema::TDK_Success:
305 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000306 case Sema::TDK_TooManyArguments:
307 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000308 break;
309
310 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000311 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000312 Result.Data = Info.Param.getOpaqueValue();
313 break;
314
Douglas Gregora9333192010-05-08 17:41:32 +0000315 case Sema::TDK_Inconsistent:
316 case Sema::TDK_InconsistentQuals: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000317 // FIXME: Should allocate from normal heap so that we can free this later.
318 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000319 Saved->Param = Info.Param;
320 Saved->FirstArg = Info.FirstArg;
321 Saved->SecondArg = Info.SecondArg;
322 Result.Data = Saved;
323 break;
324 }
325
326 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000327 Result.Data = Info.take();
328 break;
329
Douglas Gregora9333192010-05-08 17:41:32 +0000330 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000331 case Sema::TDK_FailedOverloadResolution:
332 break;
333 }
334
335 return Result;
336}
John McCall1d318332010-01-12 00:44:57 +0000337
Douglas Gregora9333192010-05-08 17:41:32 +0000338void OverloadCandidate::DeductionFailureInfo::Destroy() {
339 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
340 case Sema::TDK_Success:
341 case Sema::TDK_InstantiationDepth:
342 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000343 case Sema::TDK_TooManyArguments:
344 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000345 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000346 break;
347
Douglas Gregora9333192010-05-08 17:41:32 +0000348 case Sema::TDK_Inconsistent:
349 case Sema::TDK_InconsistentQuals:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000350 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000351 Data = 0;
352 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000353
354 case Sema::TDK_SubstitutionFailure:
355 // FIXME: Destroy the template arugment list?
356 Data = 0;
357 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000358
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000359 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000360 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000361 case Sema::TDK_FailedOverloadResolution:
362 break;
363 }
364}
365
366TemplateParameter
367OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
368 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
369 case Sema::TDK_Success:
370 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000371 case Sema::TDK_TooManyArguments:
372 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000373 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000374 return TemplateParameter();
375
376 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000377 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000378 return TemplateParameter::getFromOpaqueValue(Data);
379
380 case Sema::TDK_Inconsistent:
381 case Sema::TDK_InconsistentQuals:
382 return static_cast<DFIParamWithArguments*>(Data)->Param;
383
384 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000385 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000386 case Sema::TDK_FailedOverloadResolution:
387 break;
388 }
389
390 return TemplateParameter();
391}
Douglas Gregorec20f462010-05-08 20:07:26 +0000392
393TemplateArgumentList *
394OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
395 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
396 case Sema::TDK_Success:
397 case Sema::TDK_InstantiationDepth:
398 case Sema::TDK_TooManyArguments:
399 case Sema::TDK_TooFewArguments:
400 case Sema::TDK_Incomplete:
401 case Sema::TDK_InvalidExplicitArguments:
402 case Sema::TDK_Inconsistent:
403 case Sema::TDK_InconsistentQuals:
404 return 0;
405
406 case Sema::TDK_SubstitutionFailure:
407 return static_cast<TemplateArgumentList*>(Data);
408
409 // Unhandled
410 case Sema::TDK_NonDeducedMismatch:
411 case Sema::TDK_FailedOverloadResolution:
412 break;
413 }
414
415 return 0;
416}
417
Douglas Gregora9333192010-05-08 17:41:32 +0000418const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
419 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
420 case Sema::TDK_Success:
421 case Sema::TDK_InstantiationDepth:
422 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000423 case Sema::TDK_TooManyArguments:
424 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000425 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000426 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000427 return 0;
428
Douglas Gregora9333192010-05-08 17:41:32 +0000429 case Sema::TDK_Inconsistent:
430 case Sema::TDK_InconsistentQuals:
431 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
432
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000433 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000434 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000435 case Sema::TDK_FailedOverloadResolution:
436 break;
437 }
438
439 return 0;
440}
441
442const TemplateArgument *
443OverloadCandidate::DeductionFailureInfo::getSecondArg() {
444 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
445 case Sema::TDK_Success:
446 case Sema::TDK_InstantiationDepth:
447 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000448 case Sema::TDK_TooManyArguments:
449 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000450 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000451 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000452 return 0;
453
Douglas Gregora9333192010-05-08 17:41:32 +0000454 case Sema::TDK_Inconsistent:
455 case Sema::TDK_InconsistentQuals:
456 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
457
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000458 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000459 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000460 case Sema::TDK_FailedOverloadResolution:
461 break;
462 }
463
464 return 0;
465}
466
467void OverloadCandidateSet::clear() {
Douglas Gregora9333192010-05-08 17:41:32 +0000468 inherited::clear();
469 Functions.clear();
470}
471
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000472// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000473// overload of the declarations in Old. This routine returns false if
474// New and Old cannot be overloaded, e.g., if New has the same
475// signature as some function in Old (C++ 1.3.10) or if the Old
476// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000477// it does return false, MatchedDecl will point to the decl that New
478// cannot be overloaded with. This decl may be a UsingShadowDecl on
479// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000480//
481// Example: Given the following input:
482//
483// void f(int, float); // #1
484// void f(int, int); // #2
485// int f(int, int); // #3
486//
487// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000488// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000489//
John McCall51fa86f2009-12-02 08:47:38 +0000490// When we process #2, Old contains only the FunctionDecl for #1. By
491// comparing the parameter types, we see that #1 and #2 are overloaded
492// (since they have different signatures), so this routine returns
493// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000494//
John McCall51fa86f2009-12-02 08:47:38 +0000495// When we process #3, Old is an overload set containing #1 and #2. We
496// compare the signatures of #3 to #1 (they're overloaded, so we do
497// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
498// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000499// signature), IsOverload returns false and MatchedDecl will be set to
500// point to the FunctionDecl for #2.
John McCall871b2e72009-12-09 03:35:25 +0000501Sema::OverloadKind
John McCall9f54ad42009-12-10 09:41:52 +0000502Sema::CheckOverload(FunctionDecl *New, const LookupResult &Old,
503 NamedDecl *&Match) {
John McCall51fa86f2009-12-02 08:47:38 +0000504 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000505 I != E; ++I) {
John McCall51fa86f2009-12-02 08:47:38 +0000506 NamedDecl *OldD = (*I)->getUnderlyingDecl();
507 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCall68263142009-11-18 22:49:29 +0000508 if (!IsOverload(New, OldT->getTemplatedDecl())) {
John McCall871b2e72009-12-09 03:35:25 +0000509 Match = *I;
510 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000511 }
John McCall51fa86f2009-12-02 08:47:38 +0000512 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCall68263142009-11-18 22:49:29 +0000513 if (!IsOverload(New, OldF)) {
John McCall871b2e72009-12-09 03:35:25 +0000514 Match = *I;
515 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000516 }
John McCall9f54ad42009-12-10 09:41:52 +0000517 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
518 // We can overload with these, which can show up when doing
519 // redeclaration checks for UsingDecls.
520 assert(Old.getLookupKind() == LookupUsingDeclName);
521 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
522 // Optimistically assume that an unresolved using decl will
523 // overload; if it doesn't, we'll have to diagnose during
524 // template instantiation.
525 } else {
John McCall68263142009-11-18 22:49:29 +0000526 // (C++ 13p1):
527 // Only function declarations can be overloaded; object and type
528 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000529 Match = *I;
530 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000531 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000532 }
John McCall68263142009-11-18 22:49:29 +0000533
John McCall871b2e72009-12-09 03:35:25 +0000534 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000535}
536
537bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
538 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
539 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
540
541 // C++ [temp.fct]p2:
542 // A function template can be overloaded with other function templates
543 // and with normal (non-template) functions.
544 if ((OldTemplate == 0) != (NewTemplate == 0))
545 return true;
546
547 // Is the function New an overload of the function Old?
548 QualType OldQType = Context.getCanonicalType(Old->getType());
549 QualType NewQType = Context.getCanonicalType(New->getType());
550
551 // Compare the signatures (C++ 1.3.10) of the two functions to
552 // determine whether they are overloads. If we find any mismatch
553 // in the signature, they are overloads.
554
555 // If either of these functions is a K&R-style function (no
556 // prototype), then we consider them to have matching signatures.
557 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
558 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
559 return false;
560
561 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
562 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
563
564 // The signature of a function includes the types of its
565 // parameters (C++ 1.3.10), which includes the presence or absence
566 // of the ellipsis; see C++ DR 357).
567 if (OldQType != NewQType &&
568 (OldType->getNumArgs() != NewType->getNumArgs() ||
569 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000570 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000571 return true;
572
573 // C++ [temp.over.link]p4:
574 // The signature of a function template consists of its function
575 // signature, its return type and its template parameter list. The names
576 // of the template parameters are significant only for establishing the
577 // relationship between the template parameters and the rest of the
578 // signature.
579 //
580 // We check the return type and template parameter lists for function
581 // templates first; the remaining checks follow.
582 if (NewTemplate &&
583 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
584 OldTemplate->getTemplateParameters(),
585 false, TPL_TemplateMatch) ||
586 OldType->getResultType() != NewType->getResultType()))
587 return true;
588
589 // If the function is a class member, its signature includes the
590 // cv-qualifiers (if any) on the function itself.
591 //
592 // As part of this, also check whether one of the member functions
593 // is static, in which case they are not overloads (C++
594 // 13.1p2). While not part of the definition of the signature,
595 // this check is important to determine whether these functions
596 // can be overloaded.
597 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
598 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
599 if (OldMethod && NewMethod &&
600 !OldMethod->isStatic() && !NewMethod->isStatic() &&
601 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
602 return true;
603
604 // The signatures match; this is not an overload.
605 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000606}
607
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000608/// TryImplicitConversion - Attempt to perform an implicit conversion
609/// from the given expression (Expr) to the given type (ToType). This
610/// function returns an implicit conversion sequence that can be used
611/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000612///
613/// void f(float f);
614/// void g(int i) { f(i); }
615///
616/// this routine would produce an implicit conversion sequence to
617/// describe the initialization of f from i, which will be a standard
618/// conversion sequence containing an lvalue-to-rvalue conversion (C++
619/// 4.1) followed by a floating-integral conversion (C++ 4.9).
620//
621/// Note that this routine only determines how the conversion can be
622/// performed; it does not actually perform the conversion. As such,
623/// it will not produce any diagnostics if no conversion is available,
624/// but will instead return an implicit conversion sequence of kind
625/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000626///
627/// If @p SuppressUserConversions, then user-defined conversions are
628/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000629/// If @p AllowExplicit, then explicit user-defined conversions are
630/// permitted.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000631ImplicitConversionSequence
Anders Carlsson2974b5c2009-08-27 17:14:02 +0000632Sema::TryImplicitConversion(Expr* From, QualType ToType,
633 bool SuppressUserConversions,
Douglas Gregor74e386e2010-04-16 18:00:29 +0000634 bool AllowExplicit,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000635 bool InOverloadResolution) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000636 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +0000637 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
John McCall1d318332010-01-12 00:44:57 +0000638 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +0000639 return ICS;
640 }
641
642 if (!getLangOptions().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +0000643 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +0000644 return ICS;
645 }
646
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000647 if (SuppressUserConversions) {
648 // C++ [over.ics.user]p4:
649 // A conversion of an expression of class type to the same class
650 // type is given Exact Match rank, and a conversion of an
651 // expression of class type to a base class of that type is
652 // given Conversion rank, in spite of the fact that a copy/move
653 // constructor (i.e., a user-defined conversion function) is
654 // called for those cases.
655 QualType FromType = From->getType();
656 if (!ToType->getAs<RecordType>() || !FromType->getAs<RecordType>() ||
657 !(Context.hasSameUnqualifiedType(FromType, ToType) ||
658 IsDerivedFrom(FromType, ToType))) {
659 // We're not in the case above, so there is no conversion that
660 // we can perform.
661 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
662 return ICS;
663 }
664
665 ICS.setStandard();
666 ICS.Standard.setAsIdentityConversion();
667 ICS.Standard.setFromType(FromType);
668 ICS.Standard.setAllToTypes(ToType);
669
670 // We don't actually check at this point whether there is a valid
671 // copy/move constructor, since overloading just assumes that it
672 // exists. When we actually perform initialization, we'll find the
673 // appropriate constructor to copy the returned object, if needed.
674 ICS.Standard.CopyConstructor = 0;
675
676 // Determine whether this is considered a derived-to-base conversion.
677 if (!Context.hasSameUnqualifiedType(FromType, ToType))
678 ICS.Standard.Second = ICK_Derived_To_Base;
679
680 return ICS;
681 }
682
683 // Attempt user-defined conversion.
John McCall5769d612010-02-08 23:07:23 +0000684 OverloadCandidateSet Conversions(From->getExprLoc());
685 OverloadingResult UserDefResult
686 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000687 AllowExplicit);
John McCall5769d612010-02-08 23:07:23 +0000688
689 if (UserDefResult == OR_Success) {
John McCall1d318332010-01-12 00:44:57 +0000690 ICS.setUserDefined();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000691 // C++ [over.ics.user]p4:
692 // A conversion of an expression of class type to the same class
693 // type is given Exact Match rank, and a conversion of an
694 // expression of class type to a base class of that type is
695 // given Conversion rank, in spite of the fact that a copy
696 // constructor (i.e., a user-defined conversion function) is
697 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000698 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000699 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000700 QualType FromCanon
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000701 = Context.getCanonicalType(From->getType().getUnqualifiedType());
702 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor9e9199d2009-12-22 00:34:07 +0000703 if (Constructor->isCopyConstructor() &&
Douglas Gregor0d6d12b2009-12-22 00:21:20 +0000704 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000705 // Turn this into a "standard" conversion sequence, so that it
706 // gets ranked with standard conversion sequences.
John McCall1d318332010-01-12 00:44:57 +0000707 ICS.setStandard();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000708 ICS.Standard.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +0000709 ICS.Standard.setFromType(From->getType());
Douglas Gregorad323a82010-01-27 03:51:04 +0000710 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000711 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000712 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000713 ICS.Standard.Second = ICK_Derived_To_Base;
714 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000715 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000716
717 // C++ [over.best.ics]p4:
718 // However, when considering the argument of a user-defined
719 // conversion function that is a candidate by 13.3.1.3 when
720 // invoked for the copying of the temporary in the second step
721 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
722 // 13.3.1.6 in all cases, only standard conversion sequences and
723 // ellipsis conversion sequences are allowed.
John McCalladbb8f82010-01-13 09:16:55 +0000724 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCallb1bdc622010-02-25 01:37:24 +0000725 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCalladbb8f82010-01-13 09:16:55 +0000726 }
John McCallcefd3ad2010-01-13 22:30:33 +0000727 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall1d318332010-01-12 00:44:57 +0000728 ICS.setAmbiguous();
729 ICS.Ambiguous.setFromType(From->getType());
730 ICS.Ambiguous.setToType(ToType);
731 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
732 Cand != Conversions.end(); ++Cand)
733 if (Cand->Viable)
734 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000735 } else {
John McCallb1bdc622010-02-25 01:37:24 +0000736 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000737 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000738
739 return ICS;
740}
741
Douglas Gregor575c63a2010-04-16 22:27:05 +0000742/// PerformImplicitConversion - Perform an implicit conversion of the
743/// expression From to the type ToType. Returns true if there was an
744/// error, false otherwise. The expression From is replaced with the
745/// converted expression. Flavor is the kind of conversion we're
746/// performing, used in the error message. If @p AllowExplicit,
747/// explicit user-defined conversions are permitted.
748bool
749Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
750 AssignmentAction Action, bool AllowExplicit) {
751 ImplicitConversionSequence ICS;
752 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
753}
754
755bool
756Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
757 AssignmentAction Action, bool AllowExplicit,
758 ImplicitConversionSequence& ICS) {
759 ICS = TryImplicitConversion(From, ToType,
760 /*SuppressUserConversions=*/false,
761 AllowExplicit,
762 /*InOverloadResolution=*/false);
763 return PerformImplicitConversion(From, ToType, ICS, Action);
764}
765
Douglas Gregor43c79c22009-12-09 00:47:37 +0000766/// \brief Determine whether the conversion from FromType to ToType is a valid
767/// conversion that strips "noreturn" off the nested function type.
768static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
769 QualType ToType, QualType &ResultTy) {
770 if (Context.hasSameUnqualifiedType(FromType, ToType))
771 return false;
772
773 // Strip the noreturn off the type we're converting from; noreturn can
774 // safely be removed.
775 FromType = Context.getNoReturnType(FromType, false);
776 if (!Context.hasSameUnqualifiedType(FromType, ToType))
777 return false;
778
779 ResultTy = FromType;
780 return true;
781}
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000782
783/// \brief Determine whether the conversion from FromType to ToType is a valid
784/// vector conversion.
785///
786/// \param ICK Will be set to the vector conversion kind, if this is a vector
787/// conversion.
788static bool IsVectorConversion(ASTContext &Context, QualType FromType,
789 QualType ToType, ImplicitConversionKind &ICK) {
790 // We need at least one of these types to be a vector type to have a vector
791 // conversion.
792 if (!ToType->isVectorType() && !FromType->isVectorType())
793 return false;
794
795 // Identical types require no conversions.
796 if (Context.hasSameUnqualifiedType(FromType, ToType))
797 return false;
798
799 // There are no conversions between extended vector types, only identity.
800 if (ToType->isExtVectorType()) {
801 // There are no conversions between extended vector types other than the
802 // identity conversion.
803 if (FromType->isExtVectorType())
804 return false;
805
806 // Vector splat from any arithmetic type to a vector.
807 if (!FromType->isVectorType() && FromType->isArithmeticType()) {
808 ICK = ICK_Vector_Splat;
809 return true;
810 }
811 }
812
813 // If lax vector conversions are permitted and the vector types are of the
814 // same size, we can perform the conversion.
815 if (Context.getLangOptions().LaxVectorConversions &&
816 FromType->isVectorType() && ToType->isVectorType() &&
817 Context.getTypeSize(FromType) == Context.getTypeSize(ToType)) {
818 ICK = ICK_Vector_Conversion;
819 return true;
820 }
821
822 return false;
823}
Douglas Gregor43c79c22009-12-09 00:47:37 +0000824
Douglas Gregor60d62c22008-10-31 16:23:19 +0000825/// IsStandardConversion - Determines whether there is a standard
826/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
827/// expression From to the type ToType. Standard conversion sequences
828/// only consider non-class types; for conversions that involve class
829/// types, use TryImplicitConversion. If a conversion exists, SCS will
830/// contain the standard conversion sequence required to perform this
831/// conversion and this routine will return true. Otherwise, this
832/// routine will return false and the value of SCS is unspecified.
Mike Stump1eb44332009-09-09 15:08:12 +0000833bool
834Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000835 bool InOverloadResolution,
Mike Stump1eb44332009-09-09 15:08:12 +0000836 StandardConversionSequence &SCS) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000837 QualType FromType = From->getType();
838
Douglas Gregor60d62c22008-10-31 16:23:19 +0000839 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000840 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +0000841 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000842 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +0000843 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000844 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000845
Douglas Gregorf9201e02009-02-11 23:02:49 +0000846 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +0000847 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +0000848 if (FromType->isRecordType() || ToType->isRecordType()) {
849 if (getLangOptions().CPlusPlus)
850 return false;
851
Mike Stump1eb44332009-09-09 15:08:12 +0000852 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000853 }
854
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000855 // The first conversion can be an lvalue-to-rvalue conversion,
856 // array-to-pointer conversion, or function-to-pointer conversion
857 // (C++ 4p1).
858
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000859 if (FromType == Context.OverloadTy) {
860 DeclAccessPair AccessPair;
861 if (FunctionDecl *Fn
862 = ResolveAddressOfOverloadedFunction(From, ToType, false,
863 AccessPair)) {
864 // We were able to resolve the address of the overloaded function,
865 // so we can convert to the type of that function.
866 FromType = Fn->getType();
867 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
868 if (!Method->isStatic()) {
869 Type *ClassType
870 = Context.getTypeDeclType(Method->getParent()).getTypePtr();
871 FromType = Context.getMemberPointerType(FromType, ClassType);
872 }
873 }
874
875 // If the "from" expression takes the address of the overloaded
876 // function, update the type of the resulting expression accordingly.
877 if (FromType->getAs<FunctionType>())
878 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
879 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
880 FromType = Context.getPointerType(FromType);
881
882 // Check that we've computed the proper type after overload resolution.
883 assert(Context.hasSameType(FromType,
884 FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
885 } else {
886 return false;
887 }
888 }
Mike Stump1eb44332009-09-09 15:08:12 +0000889 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000890 // An lvalue (3.10) of a non-function, non-array type T can be
891 // converted to an rvalue.
892 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000893 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000894 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor063daf62009-03-13 18:40:31 +0000895 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000896 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000897
898 // If T is a non-class type, the type of the rvalue is the
899 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +0000900 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
901 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000902 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000903 } else if (FromType->isArrayType()) {
904 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000905 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000906
907 // An lvalue or rvalue of type "array of N T" or "array of unknown
908 // bound of T" can be converted to an rvalue of type "pointer to
909 // T" (C++ 4.2p1).
910 FromType = Context.getArrayDecayedType(FromType);
911
912 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
913 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +0000914 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000915
916 // For the purpose of ranking in overload resolution
917 // (13.3.3.1.1), this conversion is considered an
918 // array-to-pointer conversion followed by a qualification
919 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000920 SCS.Second = ICK_Identity;
921 SCS.Third = ICK_Qualification;
Douglas Gregorad323a82010-01-27 03:51:04 +0000922 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000923 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000924 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000925 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
926 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000927 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000928
929 // An lvalue of function type T can be converted to an rvalue of
930 // type "pointer to T." The result is a pointer to the
931 // function. (C++ 4.3p1).
932 FromType = Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000933 } else {
934 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000935 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000936 }
Douglas Gregorad323a82010-01-27 03:51:04 +0000937 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000938
939 // The second conversion can be an integral promotion, floating
940 // point promotion, integral conversion, floating point conversion,
941 // floating-integral conversion, pointer conversion,
942 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +0000943 // For overloading in C, this can also be a "compatible-type"
944 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +0000945 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000946 ImplicitConversionKind SecondICK = ICK_Identity;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000947 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000948 // The unqualified versions of the types are the same: there's no
949 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000950 SCS.Second = ICK_Identity;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000951 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000952 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000953 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000954 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000955 } else if (IsFloatingPointPromotion(FromType, ToType)) {
956 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000957 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000958 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000959 } else if (IsComplexPromotion(FromType, ToType)) {
960 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000961 SCS.Second = ICK_Complex_Promotion;
962 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000963 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl07779722008-10-31 14:43:28 +0000964 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000965 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000966 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000967 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000968 } else if (FromType->isComplexType() && ToType->isComplexType()) {
969 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000970 SCS.Second = ICK_Complex_Conversion;
971 FromType = ToType.getUnqualifiedType();
Chandler Carruth23a370f2010-02-25 07:20:54 +0000972 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
973 (ToType->isComplexType() && FromType->isArithmeticType())) {
974 // Complex-real conversions (C99 6.3.1.7)
975 SCS.Second = ICK_Complex_Real;
976 FromType = ToType.getUnqualifiedType();
977 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
978 // Floating point conversions (C++ 4.8).
979 SCS.Second = ICK_Floating_Conversion;
980 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000981 } else if ((FromType->isFloatingType() &&
982 ToType->isIntegralType() && (!ToType->isBooleanType() &&
983 !ToType->isEnumeralType())) ||
Mike Stump1eb44332009-09-09 15:08:12 +0000984 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000985 ToType->isFloatingType())) {
986 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000987 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000988 FromType = ToType.getUnqualifiedType();
Anders Carlsson08972922009-08-28 15:33:32 +0000989 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
990 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000991 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000992 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +0000993 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregorce940492009-09-25 04:25:58 +0000994 } else if (IsMemberPointerConversion(From, FromType, ToType,
995 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000996 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +0000997 SCS.Second = ICK_Pointer_Member;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000998 } else if (ToType->isBooleanType() &&
999 (FromType->isArithmeticType() ||
1000 FromType->isEnumeralType() ||
Fariborz Jahanian1f7711d2009-12-11 21:23:13 +00001001 FromType->isAnyPointerType() ||
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001002 FromType->isBlockPointerType() ||
1003 FromType->isMemberPointerType() ||
1004 FromType->isNullPtrType())) {
1005 // Boolean conversions (C++ 4.12).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001006 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001007 FromType = Context.BoolTy;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001008 } else if (IsVectorConversion(Context, FromType, ToType, SecondICK)) {
1009 SCS.Second = SecondICK;
1010 FromType = ToType.getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00001011 } else if (!getLangOptions().CPlusPlus &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001012 Context.typesAreCompatible(ToType, FromType)) {
1013 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001014 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001015 FromType = ToType.getUnqualifiedType();
Douglas Gregor43c79c22009-12-09 00:47:37 +00001016 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
1017 // Treat a conversion that strips "noreturn" as an identity conversion.
1018 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001019 } else {
1020 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001021 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001022 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001023 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001024
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001025 QualType CanonFrom;
1026 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001027 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +00001028 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001029 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001030 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001031 CanonFrom = Context.getCanonicalType(FromType);
1032 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001033 } else {
1034 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001035 SCS.Third = ICK_Identity;
1036
Mike Stump1eb44332009-09-09 15:08:12 +00001037 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001038 // [...] Any difference in top-level cv-qualification is
1039 // subsumed by the initialization itself and does not constitute
1040 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001041 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +00001042 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00001043 if (CanonFrom.getLocalUnqualifiedType()
1044 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001045 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1046 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001047 FromType = ToType;
1048 CanonFrom = CanonTo;
1049 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001050 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001051 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001052
1053 // If we have not converted the argument type to the parameter type,
1054 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001055 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001056 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001057
Douglas Gregor60d62c22008-10-31 16:23:19 +00001058 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001059}
1060
1061/// IsIntegralPromotion - Determines whether the conversion from the
1062/// expression From (whose potentially-adjusted type is FromType) to
1063/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1064/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001065bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001066 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001067 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001068 if (!To) {
1069 return false;
1070 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001071
1072 // An rvalue of type char, signed char, unsigned char, short int, or
1073 // unsigned short int can be converted to an rvalue of type int if
1074 // int can represent all the values of the source type; otherwise,
1075 // the source rvalue can be converted to an rvalue of type unsigned
1076 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001077 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1078 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001079 if (// We can promote any signed, promotable integer type to an int
1080 (FromType->isSignedIntegerType() ||
1081 // We can promote any unsigned integer type whose size is
1082 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001083 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001084 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001085 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001086 }
1087
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001088 return To->getKind() == BuiltinType::UInt;
1089 }
1090
1091 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
1092 // can be converted to an rvalue of the first of the following types
1093 // that can represent all the values of its underlying type: int,
1094 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall842aef82009-12-09 09:09:27 +00001095
1096 // We pre-calculate the promotion type for enum types.
1097 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
1098 if (ToType->isIntegerType())
1099 return Context.hasSameUnqualifiedType(ToType,
1100 FromEnumType->getDecl()->getPromotionType());
1101
1102 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001103 // Determine whether the type we're converting from is signed or
1104 // unsigned.
1105 bool FromIsSigned;
1106 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall842aef82009-12-09 09:09:27 +00001107
1108 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1109 FromIsSigned = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001110
1111 // The types we'll try to promote to, in the appropriate
1112 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001113 QualType PromoteTypes[6] = {
1114 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001115 Context.LongTy, Context.UnsignedLongTy ,
1116 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001117 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001118 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001119 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1120 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001121 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001122 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1123 // We found the type that we can promote to. If this is the
1124 // type we wanted, we have a promotion. Otherwise, no
1125 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001126 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001127 }
1128 }
1129 }
1130
1131 // An rvalue for an integral bit-field (9.6) can be converted to an
1132 // rvalue of type int if int can represent all the values of the
1133 // bit-field; otherwise, it can be converted to unsigned int if
1134 // unsigned int can represent all the values of the bit-field. If
1135 // the bit-field is larger yet, no integral promotion applies to
1136 // it. If the bit-field has an enumerated type, it is treated as any
1137 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001138 // FIXME: We should delay checking of bit-fields until we actually perform the
1139 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001140 using llvm::APSInt;
1141 if (From)
1142 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001143 APSInt BitWidth;
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001144 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
1145 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1146 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1147 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001148
Douglas Gregor86f19402008-12-20 23:49:58 +00001149 // Are we promoting to an int from a bitfield that fits in an int?
1150 if (BitWidth < ToSize ||
1151 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1152 return To->getKind() == BuiltinType::Int;
1153 }
Mike Stump1eb44332009-09-09 15:08:12 +00001154
Douglas Gregor86f19402008-12-20 23:49:58 +00001155 // Are we promoting to an unsigned int from an unsigned bitfield
1156 // that fits into an unsigned int?
1157 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1158 return To->getKind() == BuiltinType::UInt;
1159 }
Mike Stump1eb44332009-09-09 15:08:12 +00001160
Douglas Gregor86f19402008-12-20 23:49:58 +00001161 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001162 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001163 }
Mike Stump1eb44332009-09-09 15:08:12 +00001164
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001165 // An rvalue of type bool can be converted to an rvalue of type int,
1166 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001167 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001168 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001169 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001170
1171 return false;
1172}
1173
1174/// IsFloatingPointPromotion - Determines whether the conversion from
1175/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1176/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001177bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001178 /// An rvalue of type float can be converted to an rvalue of type
1179 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +00001180 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1181 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001182 if (FromBuiltin->getKind() == BuiltinType::Float &&
1183 ToBuiltin->getKind() == BuiltinType::Double)
1184 return true;
1185
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001186 // C99 6.3.1.5p1:
1187 // When a float is promoted to double or long double, or a
1188 // double is promoted to long double [...].
1189 if (!getLangOptions().CPlusPlus &&
1190 (FromBuiltin->getKind() == BuiltinType::Float ||
1191 FromBuiltin->getKind() == BuiltinType::Double) &&
1192 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1193 return true;
1194 }
1195
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001196 return false;
1197}
1198
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001199/// \brief Determine if a conversion is a complex promotion.
1200///
1201/// A complex promotion is defined as a complex -> complex conversion
1202/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001203/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001204bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001205 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001206 if (!FromComplex)
1207 return false;
1208
John McCall183700f2009-09-21 23:43:11 +00001209 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001210 if (!ToComplex)
1211 return false;
1212
1213 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001214 ToComplex->getElementType()) ||
1215 IsIntegralPromotion(0, FromComplex->getElementType(),
1216 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001217}
1218
Douglas Gregorcb7de522008-11-26 23:31:11 +00001219/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1220/// the pointer type FromPtr to a pointer to type ToPointee, with the
1221/// same type qualifiers as FromPtr has on its pointee type. ToType,
1222/// if non-empty, will be a pointer to ToType that may or may not have
1223/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +00001224static QualType
1225BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001226 QualType ToPointee, QualType ToType,
1227 ASTContext &Context) {
1228 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1229 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001230 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001231
1232 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001233 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001234 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001235 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001236 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001237
1238 // Build a pointer to ToPointee. It has the right qualifiers
1239 // already.
1240 return Context.getPointerType(ToPointee);
1241 }
1242
1243 // Just build a canonical type that has the right qualifiers.
John McCall0953e762009-09-24 19:53:00 +00001244 return Context.getPointerType(
Douglas Gregora4923eb2009-11-16 21:35:15 +00001245 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1246 Quals));
Douglas Gregorcb7de522008-11-26 23:31:11 +00001247}
1248
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001249/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1250/// the FromType, which is an objective-c pointer, to ToType, which may or may
1251/// not have the right set of qualifiers.
1252static QualType
1253BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1254 QualType ToType,
1255 ASTContext &Context) {
1256 QualType CanonFromType = Context.getCanonicalType(FromType);
1257 QualType CanonToType = Context.getCanonicalType(ToType);
1258 Qualifiers Quals = CanonFromType.getQualifiers();
1259
1260 // Exact qualifier match -> return the pointer type we're converting to.
1261 if (CanonToType.getLocalQualifiers() == Quals)
1262 return ToType;
1263
1264 // Just build a canonical type that has the right qualifiers.
1265 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1266}
1267
Mike Stump1eb44332009-09-09 15:08:12 +00001268static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001269 bool InOverloadResolution,
1270 ASTContext &Context) {
1271 // Handle value-dependent integral null pointer constants correctly.
1272 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1273 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1274 Expr->getType()->isIntegralType())
1275 return !InOverloadResolution;
1276
Douglas Gregorce940492009-09-25 04:25:58 +00001277 return Expr->isNullPointerConstant(Context,
1278 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1279 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001280}
Mike Stump1eb44332009-09-09 15:08:12 +00001281
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001282/// IsPointerConversion - Determines whether the conversion of the
1283/// expression From, which has the (possibly adjusted) type FromType,
1284/// can be converted to the type ToType via a pointer conversion (C++
1285/// 4.10). If so, returns true and places the converted type (that
1286/// might differ from ToType in its cv-qualifiers at some level) into
1287/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001288///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001289/// This routine also supports conversions to and from block pointers
1290/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1291/// pointers to interfaces. FIXME: Once we've determined the
1292/// appropriate overloading rules for Objective-C, we may want to
1293/// split the Objective-C checks into a different routine; however,
1294/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001295/// conversions, so for now they live here. IncompatibleObjC will be
1296/// set if the conversion is an allowed Objective-C conversion that
1297/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001298bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001299 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001300 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001301 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001302 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +00001303 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1304 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001305
Mike Stump1eb44332009-09-09 15:08:12 +00001306 // Conversion from a null pointer constant to any Objective-C pointer type.
1307 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001308 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001309 ConvertedType = ToType;
1310 return true;
1311 }
1312
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001313 // Blocks: Block pointers can be converted to void*.
1314 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001315 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001316 ConvertedType = ToType;
1317 return true;
1318 }
1319 // Blocks: A null pointer constant can be converted to a block
1320 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001321 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001322 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001323 ConvertedType = ToType;
1324 return true;
1325 }
1326
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001327 // If the left-hand-side is nullptr_t, the right side can be a null
1328 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001329 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001330 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001331 ConvertedType = ToType;
1332 return true;
1333 }
1334
Ted Kremenek6217b802009-07-29 21:53:49 +00001335 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001336 if (!ToTypePtr)
1337 return false;
1338
1339 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001340 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001341 ConvertedType = ToType;
1342 return true;
1343 }
Sebastian Redl07779722008-10-31 14:43:28 +00001344
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001345 // Beyond this point, both types need to be pointers
1346 // , including objective-c pointers.
1347 QualType ToPointeeType = ToTypePtr->getPointeeType();
1348 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1349 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1350 ToType, Context);
1351 return true;
1352
1353 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001354 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001355 if (!FromTypePtr)
1356 return false;
1357
1358 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001359
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001360 // An rvalue of type "pointer to cv T," where T is an object type,
1361 // can be converted to an rvalue of type "pointer to cv void" (C++
1362 // 4.10p2).
Douglas Gregorbad0e652009-03-24 20:32:41 +00001363 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001364 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001365 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001366 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001367 return true;
1368 }
1369
Douglas Gregorf9201e02009-02-11 23:02:49 +00001370 // When we're overloading in C, we allow a special kind of pointer
1371 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001372 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001373 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001374 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001375 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001376 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001377 return true;
1378 }
1379
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001380 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001381 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001382 // An rvalue of type "pointer to cv D," where D is a class type,
1383 // can be converted to an rvalue of type "pointer to cv B," where
1384 // B is a base class (clause 10) of D. If B is an inaccessible
1385 // (clause 11) or ambiguous (10.2) base class of D, a program that
1386 // necessitates this conversion is ill-formed. The result of the
1387 // conversion is a pointer to the base class sub-object of the
1388 // derived class object. The null pointer value is converted to
1389 // the null pointer value of the destination type.
1390 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001391 // Note that we do not check for ambiguity or inaccessibility
1392 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001393 if (getLangOptions().CPlusPlus &&
1394 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001395 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001396 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001397 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001398 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001399 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001400 ToType, Context);
1401 return true;
1402 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001403
Douglas Gregorc7887512008-12-19 19:13:09 +00001404 return false;
1405}
1406
1407/// isObjCPointerConversion - Determines whether this is an
1408/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1409/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001410bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001411 QualType& ConvertedType,
1412 bool &IncompatibleObjC) {
1413 if (!getLangOptions().ObjC1)
1414 return false;
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001415
Steve Naroff14108da2009-07-10 23:34:53 +00001416 // First, we handle all conversions on ObjC object pointer types.
John McCall183700f2009-09-21 23:43:11 +00001417 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001418 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001419 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001420
Steve Naroff14108da2009-07-10 23:34:53 +00001421 if (ToObjCPtr && FromObjCPtr) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00001422 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001423 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001424 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001425 ConvertedType = ToType;
1426 return true;
1427 }
1428 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001429 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001430 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001431 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001432 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001433 ConvertedType = ToType;
1434 return true;
1435 }
1436 // Objective C++: We're able to convert from a pointer to an
1437 // interface to a pointer to a different interface.
1438 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00001439 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1440 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1441 if (getLangOptions().CPlusPlus && LHS && RHS &&
1442 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1443 FromObjCPtr->getPointeeType()))
1444 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00001445 ConvertedType = ToType;
1446 return true;
1447 }
1448
1449 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1450 // Okay: this is some kind of implicit downcast of Objective-C
1451 // interfaces, which is permitted. However, we're going to
1452 // complain about it.
1453 IncompatibleObjC = true;
1454 ConvertedType = FromType;
1455 return true;
1456 }
Mike Stump1eb44332009-09-09 15:08:12 +00001457 }
Steve Naroff14108da2009-07-10 23:34:53 +00001458 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001459 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001460 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001461 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001462 else if (const BlockPointerType *ToBlockPtr =
1463 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00001464 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001465 // to a block pointer type.
1466 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1467 ConvertedType = ToType;
1468 return true;
1469 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001470 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001471 }
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001472 else if (FromType->getAs<BlockPointerType>() &&
1473 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1474 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00001475 // pointer to any object.
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001476 ConvertedType = ToType;
1477 return true;
1478 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001479 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001480 return false;
1481
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001482 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001483 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001484 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001485 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001486 FromPointeeType = FromBlockPtr->getPointeeType();
1487 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001488 return false;
1489
Douglas Gregorc7887512008-12-19 19:13:09 +00001490 // If we have pointers to pointers, recursively check whether this
1491 // is an Objective-C conversion.
1492 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1493 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1494 IncompatibleObjC)) {
1495 // We always complain about this conversion.
1496 IncompatibleObjC = true;
1497 ConvertedType = ToType;
1498 return true;
1499 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001500 // Allow conversion of pointee being objective-c pointer to another one;
1501 // as in I* to id.
1502 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1503 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1504 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1505 IncompatibleObjC)) {
1506 ConvertedType = ToType;
1507 return true;
1508 }
1509
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001510 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001511 // differences in the argument and result types are in Objective-C
1512 // pointer conversions. If so, we permit the conversion (but
1513 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001514 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001515 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001516 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001517 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001518 if (FromFunctionType && ToFunctionType) {
1519 // If the function types are exactly the same, this isn't an
1520 // Objective-C pointer conversion.
1521 if (Context.getCanonicalType(FromPointeeType)
1522 == Context.getCanonicalType(ToPointeeType))
1523 return false;
1524
1525 // Perform the quick checks that will tell us whether these
1526 // function types are obviously different.
1527 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1528 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1529 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1530 return false;
1531
1532 bool HasObjCConversion = false;
1533 if (Context.getCanonicalType(FromFunctionType->getResultType())
1534 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1535 // Okay, the types match exactly. Nothing to do.
1536 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1537 ToFunctionType->getResultType(),
1538 ConvertedType, IncompatibleObjC)) {
1539 // Okay, we have an Objective-C pointer conversion.
1540 HasObjCConversion = true;
1541 } else {
1542 // Function types are too different. Abort.
1543 return false;
1544 }
Mike Stump1eb44332009-09-09 15:08:12 +00001545
Douglas Gregorc7887512008-12-19 19:13:09 +00001546 // Check argument types.
1547 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1548 ArgIdx != NumArgs; ++ArgIdx) {
1549 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1550 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1551 if (Context.getCanonicalType(FromArgType)
1552 == Context.getCanonicalType(ToArgType)) {
1553 // Okay, the types match exactly. Nothing to do.
1554 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1555 ConvertedType, IncompatibleObjC)) {
1556 // Okay, we have an Objective-C pointer conversion.
1557 HasObjCConversion = true;
1558 } else {
1559 // Argument types are too different. Abort.
1560 return false;
1561 }
1562 }
1563
1564 if (HasObjCConversion) {
1565 // We had an Objective-C conversion. Allow this pointer
1566 // conversion, but complain about it.
1567 ConvertedType = ToType;
1568 IncompatibleObjC = true;
1569 return true;
1570 }
1571 }
1572
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001573 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001574}
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001575
1576/// FunctionArgTypesAreEqual - This routine checks two function proto types
1577/// for equlity of their argument types. Caller has already checked that
1578/// they have same number of arguments. This routine assumes that Objective-C
1579/// pointer types which only differ in their protocol qualifiers are equal.
1580bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1581 FunctionProtoType* NewType){
1582 if (!getLangOptions().ObjC1)
1583 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1584 NewType->arg_type_begin());
1585
1586 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1587 N = NewType->arg_type_begin(),
1588 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1589 QualType ToType = (*O);
1590 QualType FromType = (*N);
1591 if (ToType != FromType) {
1592 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1593 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00001594 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1595 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1596 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1597 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001598 continue;
1599 }
John McCallc12c5bb2010-05-15 11:32:37 +00001600 else if (const ObjCObjectPointerType *PTTo =
1601 ToType->getAs<ObjCObjectPointerType>()) {
1602 if (const ObjCObjectPointerType *PTFr =
1603 FromType->getAs<ObjCObjectPointerType>())
1604 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1605 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001606 }
1607 return false;
1608 }
1609 }
1610 return true;
1611}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001612
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001613/// CheckPointerConversion - Check the pointer conversion from the
1614/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001615/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001616/// conversions for which IsPointerConversion has already returned
1617/// true. It returns true and produces a diagnostic if there was an
1618/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001619bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001620 CastExpr::CastKind &Kind,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001621 CXXBaseSpecifierArray& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001622 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001623 QualType FromType = From->getType();
1624
Douglas Gregord7a95972010-06-08 17:35:15 +00001625 if (CXXBoolLiteralExpr* LitBool
1626 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
1627 if (LitBool->getValue() == false)
1628 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1629 << ToType;
1630
Ted Kremenek6217b802009-07-29 21:53:49 +00001631 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1632 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001633 QualType FromPointeeType = FromPtrType->getPointeeType(),
1634 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001635
Douglas Gregor5fccd362010-03-03 23:55:11 +00001636 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1637 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001638 // We must have a derived-to-base conversion. Check an
1639 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001640 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1641 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001642 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001643 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001644 return true;
1645
1646 // The conversion was successful.
1647 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001648 }
1649 }
Mike Stump1eb44332009-09-09 15:08:12 +00001650 if (const ObjCObjectPointerType *FromPtrType =
John McCall183700f2009-09-21 23:43:11 +00001651 FromType->getAs<ObjCObjectPointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001652 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00001653 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001654 // Objective-C++ conversions are always okay.
1655 // FIXME: We should have a different class of conversions for the
1656 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001657 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001658 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001659
Steve Naroff14108da2009-07-10 23:34:53 +00001660 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001661 return false;
1662}
1663
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001664/// IsMemberPointerConversion - Determines whether the conversion of the
1665/// expression From, which has the (possibly adjusted) type FromType, can be
1666/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1667/// If so, returns true and places the converted type (that might differ from
1668/// ToType in its cv-qualifiers at some level) into ConvertedType.
1669bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregorce940492009-09-25 04:25:58 +00001670 QualType ToType,
1671 bool InOverloadResolution,
1672 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001673 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001674 if (!ToTypePtr)
1675 return false;
1676
1677 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00001678 if (From->isNullPointerConstant(Context,
1679 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1680 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001681 ConvertedType = ToType;
1682 return true;
1683 }
1684
1685 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001686 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001687 if (!FromTypePtr)
1688 return false;
1689
1690 // A pointer to member of B can be converted to a pointer to member of D,
1691 // where D is derived from B (C++ 4.11p2).
1692 QualType FromClass(FromTypePtr->getClass(), 0);
1693 QualType ToClass(ToTypePtr->getClass(), 0);
1694 // FIXME: What happens when these are dependent? Is this function even called?
1695
1696 if (IsDerivedFrom(ToClass, FromClass)) {
1697 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1698 ToClass.getTypePtr());
1699 return true;
1700 }
1701
1702 return false;
1703}
Douglas Gregor43c79c22009-12-09 00:47:37 +00001704
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001705/// CheckMemberPointerConversion - Check the member pointer conversion from the
1706/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00001707/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001708/// for which IsMemberPointerConversion has already returned true. It returns
1709/// true and produces a diagnostic if there was an error, or returns false
1710/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001711bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001712 CastExpr::CastKind &Kind,
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001713 CXXBaseSpecifierArray &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001714 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001715 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001716 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001717 if (!FromPtrType) {
1718 // This must be a null pointer to member pointer conversion
Douglas Gregorce940492009-09-25 04:25:58 +00001719 assert(From->isNullPointerConstant(Context,
1720 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001721 "Expr must be null pointer constant!");
1722 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001723 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001724 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001725
Ted Kremenek6217b802009-07-29 21:53:49 +00001726 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001727 assert(ToPtrType && "No member pointer cast has a target type "
1728 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001729
Sebastian Redl21593ac2009-01-28 18:33:18 +00001730 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1731 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001732
Sebastian Redl21593ac2009-01-28 18:33:18 +00001733 // FIXME: What about dependent types?
1734 assert(FromClass->isRecordType() && "Pointer into non-class.");
1735 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001736
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001737 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001738 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00001739 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1740 assert(DerivationOkay &&
1741 "Should not have been called if derivation isn't OK.");
1742 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001743
Sebastian Redl21593ac2009-01-28 18:33:18 +00001744 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1745 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001746 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1747 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1748 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1749 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001750 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001751
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001752 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001753 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1754 << FromClass << ToClass << QualType(VBase, 0)
1755 << From->getSourceRange();
1756 return true;
1757 }
1758
John McCall6b2accb2010-02-10 09:31:12 +00001759 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00001760 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1761 Paths.front(),
1762 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00001763
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001764 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001765 BuildBasePathArray(Paths, BasePath);
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001766 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001767 return false;
1768}
1769
Douglas Gregor98cd5992008-10-21 23:43:52 +00001770/// IsQualificationConversion - Determines whether the conversion from
1771/// an rvalue of type FromType to ToType is a qualification conversion
1772/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001773bool
1774Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001775 FromType = Context.getCanonicalType(FromType);
1776 ToType = Context.getCanonicalType(ToType);
1777
1778 // If FromType and ToType are the same type, this is not a
1779 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00001780 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00001781 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001782
Douglas Gregor98cd5992008-10-21 23:43:52 +00001783 // (C++ 4.4p4):
1784 // A conversion can add cv-qualifiers at levels other than the first
1785 // in multi-level pointers, subject to the following rules: [...]
1786 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001787 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00001788 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001789 // Within each iteration of the loop, we check the qualifiers to
1790 // determine if this still looks like a qualification
1791 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001792 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001793 // until there are no more pointers or pointers-to-members left to
1794 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001795 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001796
1797 // -- for every j > 0, if const is in cv 1,j then const is in cv
1798 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001799 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001800 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001801
Douglas Gregor98cd5992008-10-21 23:43:52 +00001802 // -- if the cv 1,j and cv 2,j are different, then const is in
1803 // every cv for 0 < k < j.
1804 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001805 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001806 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001807
Douglas Gregor98cd5992008-10-21 23:43:52 +00001808 // Keep track of whether all prior cv-qualifiers in the "to" type
1809 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00001810 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00001811 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001812 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001813
1814 // We are left with FromType and ToType being the pointee types
1815 // after unwrapping the original FromType and ToType the same number
1816 // of types. If we unwrapped any pointers, and if FromType and
1817 // ToType have the same unqualified type (since we checked
1818 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001819 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00001820}
1821
Douglas Gregor734d9862009-01-30 23:27:23 +00001822/// Determines whether there is a user-defined conversion sequence
1823/// (C++ [over.ics.user]) that converts expression From to the type
1824/// ToType. If such a conversion exists, User will contain the
1825/// user-defined conversion sequence that performs such a conversion
1826/// and this routine will return true. Otherwise, this routine returns
1827/// false and User is unspecified.
1828///
Douglas Gregor734d9862009-01-30 23:27:23 +00001829/// \param AllowExplicit true if the conversion should consider C++0x
1830/// "explicit" conversion functions as well as non-explicit conversion
1831/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor20093b42009-12-09 23:02:17 +00001832OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1833 UserDefinedConversionSequence& User,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001834 OverloadCandidateSet& CandidateSet,
1835 bool AllowExplicit) {
1836 // Whether we will only visit constructors.
1837 bool ConstructorsOnly = false;
1838
1839 // If the type we are conversion to is a class type, enumerate its
1840 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00001841 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001842 // C++ [over.match.ctor]p1:
1843 // When objects of class type are direct-initialized (8.5), or
1844 // copy-initialized from an expression of the same or a
1845 // derived class type (8.5), overload resolution selects the
1846 // constructor. [...] For copy-initialization, the candidate
1847 // functions are all the converting constructors (12.3.1) of
1848 // that class. The argument list is the expression-list within
1849 // the parentheses of the initializer.
1850 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1851 (From->getType()->getAs<RecordType>() &&
1852 IsDerivedFrom(From->getType(), ToType)))
1853 ConstructorsOnly = true;
1854
Douglas Gregor393896f2009-11-05 13:06:35 +00001855 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1856 // We're not going to find any constructors.
1857 } else if (CXXRecordDecl *ToRecordDecl
1858 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001859 DeclarationName ConstructorName
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001860 = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001861 Context.getCanonicalType(ToType).getUnqualifiedType());
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001862 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump1eb44332009-09-09 15:08:12 +00001863 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001864 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001865 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00001866 NamedDecl *D = *Con;
1867 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1868
Douglas Gregordec06662009-08-21 18:42:58 +00001869 // Find the constructor (which may be a template).
1870 CXXConstructorDecl *Constructor = 0;
1871 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00001872 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00001873 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00001874 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00001875 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1876 else
John McCall9aa472c2010-03-19 07:35:19 +00001877 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001878
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00001879 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00001880 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001881 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00001882 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001883 /*ExplicitArgs*/ 0,
John McCalld5532b62009-11-23 01:53:49 +00001884 &From, 1, CandidateSet,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001885 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00001886 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001887 // Allow one user-defined conversion when user specifies a
1888 // From->ToType conversion via an static cast (c-style, etc).
John McCall9aa472c2010-03-19 07:35:19 +00001889 AddOverloadCandidate(Constructor, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001890 &From, 1, CandidateSet,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001891 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00001892 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001893 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001894 }
1895 }
1896
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001897 // Enumerate conversion functions, if we're allowed to.
1898 if (ConstructorsOnly) {
Mike Stump1eb44332009-09-09 15:08:12 +00001899 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001900 PDiag(0) << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00001901 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00001902 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001903 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001904 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001905 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1906 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00001907 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00001908 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001909 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001910 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00001911 DeclAccessPair FoundDecl = I.getPair();
1912 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00001913 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1914 if (isa<UsingShadowDecl>(D))
1915 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1916
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001917 CXXConversionDecl *Conv;
1918 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00001919 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1920 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001921 else
John McCall32daa422010-03-31 01:36:47 +00001922 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001923
1924 if (AllowExplicit || !Conv->isExplicit()) {
1925 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00001926 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001927 ActingContext, From, ToType,
1928 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001929 else
John McCall9aa472c2010-03-19 07:35:19 +00001930 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCall86820f52010-01-26 01:37:31 +00001931 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001932 }
1933 }
1934 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001935 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001936
1937 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001938 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001939 case OR_Success:
1940 // Record the standard conversion we used and the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00001941 if (CXXConstructorDecl *Constructor
Douglas Gregor60d62c22008-10-31 16:23:19 +00001942 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1943 // C++ [over.ics.user]p1:
1944 // If the user-defined conversion is specified by a
1945 // constructor (12.3.1), the initial standard conversion
1946 // sequence converts the source type to the type required by
1947 // the argument of the constructor.
1948 //
Douglas Gregor60d62c22008-10-31 16:23:19 +00001949 QualType ThisType = Constructor->getThisType(Context);
John McCall1d318332010-01-12 00:44:57 +00001950 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001951 User.EllipsisConversion = true;
1952 else {
1953 User.Before = Best->Conversions[0].Standard;
1954 User.EllipsisConversion = false;
1955 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001956 User.ConversionFunction = Constructor;
1957 User.After.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +00001958 User.After.setFromType(
1959 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregorad323a82010-01-27 03:51:04 +00001960 User.After.setAllToTypes(ToType);
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001961 return OR_Success;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001962 } else if (CXXConversionDecl *Conversion
1963 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1964 // C++ [over.ics.user]p1:
1965 //
1966 // [...] If the user-defined conversion is specified by a
1967 // conversion function (12.3.2), the initial standard
1968 // conversion sequence converts the source type to the
1969 // implicit object parameter of the conversion function.
1970 User.Before = Best->Conversions[0].Standard;
1971 User.ConversionFunction = Conversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001972 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001973
1974 // C++ [over.ics.user]p2:
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001975 // The second standard conversion sequence converts the
1976 // result of the user-defined conversion to the target type
1977 // for the sequence. Since an implicit conversion sequence
1978 // is an initialization, the special rules for
1979 // initialization by user-defined conversion apply when
1980 // selecting the best user-defined conversion for a
1981 // user-defined conversion sequence (see 13.3.3 and
1982 // 13.3.3.1).
1983 User.After = Best->FinalConversion;
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001984 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001985 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001986 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001987 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001988 }
Mike Stump1eb44332009-09-09 15:08:12 +00001989
Douglas Gregor60d62c22008-10-31 16:23:19 +00001990 case OR_No_Viable_Function:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001991 return OR_No_Viable_Function;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001992 case OR_Deleted:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001993 // No conversion here! We're done.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001994 return OR_Deleted;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001995
1996 case OR_Ambiguous:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001997 return OR_Ambiguous;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001998 }
1999
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002000 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002001}
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002002
2003bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002004Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002005 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00002006 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002007 OverloadingResult OvResult =
2008 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002009 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002010 if (OvResult == OR_Ambiguous)
2011 Diag(From->getSourceRange().getBegin(),
2012 diag::err_typecheck_ambiguous_condition)
2013 << From->getType() << ToType << From->getSourceRange();
2014 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2015 Diag(From->getSourceRange().getBegin(),
2016 diag::err_typecheck_nonviable_condition)
2017 << From->getType() << ToType << From->getSourceRange();
2018 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002019 return false;
John McCallcbce6062010-01-12 07:18:19 +00002020 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002021 return true;
2022}
Douglas Gregor60d62c22008-10-31 16:23:19 +00002023
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002024/// CompareImplicitConversionSequences - Compare two implicit
2025/// conversion sequences to determine whether one is better than the
2026/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump1eb44332009-09-09 15:08:12 +00002027ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002028Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
2029 const ImplicitConversionSequence& ICS2)
2030{
2031 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2032 // conversion sequences (as defined in 13.3.3.1)
2033 // -- a standard conversion sequence (13.3.3.1.1) is a better
2034 // conversion sequence than a user-defined conversion sequence or
2035 // an ellipsis conversion sequence, and
2036 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2037 // conversion sequence than an ellipsis conversion sequence
2038 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002039 //
John McCall1d318332010-01-12 00:44:57 +00002040 // C++0x [over.best.ics]p10:
2041 // For the purpose of ranking implicit conversion sequences as
2042 // described in 13.3.3.2, the ambiguous conversion sequence is
2043 // treated as a user-defined sequence that is indistinguishable
2044 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002045 if (ICS1.getKindRank() < ICS2.getKindRank())
2046 return ImplicitConversionSequence::Better;
2047 else if (ICS2.getKindRank() < ICS1.getKindRank())
2048 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002049
Benjamin Kramerb6eee072010-04-18 12:05:54 +00002050 // The following checks require both conversion sequences to be of
2051 // the same kind.
2052 if (ICS1.getKind() != ICS2.getKind())
2053 return ImplicitConversionSequence::Indistinguishable;
2054
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002055 // Two implicit conversion sequences of the same form are
2056 // indistinguishable conversion sequences unless one of the
2057 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00002058 if (ICS1.isStandard())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002059 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00002060 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002061 // User-defined conversion sequence U1 is a better conversion
2062 // sequence than another user-defined conversion sequence U2 if
2063 // they contain the same user-defined conversion function or
2064 // constructor and if the second standard conversion sequence of
2065 // U1 is better than the second standard conversion sequence of
2066 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002067 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002068 ICS2.UserDefined.ConversionFunction)
2069 return CompareStandardConversionSequences(ICS1.UserDefined.After,
2070 ICS2.UserDefined.After);
2071 }
2072
2073 return ImplicitConversionSequence::Indistinguishable;
2074}
2075
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002076static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2077 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2078 Qualifiers Quals;
2079 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2080 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2081 }
2082
2083 return Context.hasSameUnqualifiedType(T1, T2);
2084}
2085
Douglas Gregorad323a82010-01-27 03:51:04 +00002086// Per 13.3.3.2p3, compare the given standard conversion sequences to
2087// determine if one is a proper subset of the other.
2088static ImplicitConversionSequence::CompareKind
2089compareStandardConversionSubsets(ASTContext &Context,
2090 const StandardConversionSequence& SCS1,
2091 const StandardConversionSequence& SCS2) {
2092 ImplicitConversionSequence::CompareKind Result
2093 = ImplicitConversionSequence::Indistinguishable;
2094
Douglas Gregorae65f4b2010-05-23 22:10:15 +00002095 // the identity conversion sequence is considered to be a subsequence of
2096 // any non-identity conversion sequence
2097 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2098 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2099 return ImplicitConversionSequence::Better;
2100 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2101 return ImplicitConversionSequence::Worse;
2102 }
2103
Douglas Gregorad323a82010-01-27 03:51:04 +00002104 if (SCS1.Second != SCS2.Second) {
2105 if (SCS1.Second == ICK_Identity)
2106 Result = ImplicitConversionSequence::Better;
2107 else if (SCS2.Second == ICK_Identity)
2108 Result = ImplicitConversionSequence::Worse;
2109 else
2110 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002111 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00002112 return ImplicitConversionSequence::Indistinguishable;
2113
2114 if (SCS1.Third == SCS2.Third) {
2115 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2116 : ImplicitConversionSequence::Indistinguishable;
2117 }
2118
2119 if (SCS1.Third == ICK_Identity)
2120 return Result == ImplicitConversionSequence::Worse
2121 ? ImplicitConversionSequence::Indistinguishable
2122 : ImplicitConversionSequence::Better;
2123
2124 if (SCS2.Third == ICK_Identity)
2125 return Result == ImplicitConversionSequence::Better
2126 ? ImplicitConversionSequence::Indistinguishable
2127 : ImplicitConversionSequence::Worse;
2128
2129 return ImplicitConversionSequence::Indistinguishable;
2130}
2131
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002132/// CompareStandardConversionSequences - Compare two standard
2133/// conversion sequences to determine whether one is better than the
2134/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002135ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002136Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
2137 const StandardConversionSequence& SCS2)
2138{
2139 // Standard conversion sequence S1 is a better conversion sequence
2140 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2141
2142 // -- S1 is a proper subsequence of S2 (comparing the conversion
2143 // sequences in the canonical form defined by 13.3.3.1.1,
2144 // excluding any Lvalue Transformation; the identity conversion
2145 // sequence is considered to be a subsequence of any
2146 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00002147 if (ImplicitConversionSequence::CompareKind CK
2148 = compareStandardConversionSubsets(Context, SCS1, SCS2))
2149 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002150
2151 // -- the rank of S1 is better than the rank of S2 (by the rules
2152 // defined below), or, if not that,
2153 ImplicitConversionRank Rank1 = SCS1.getRank();
2154 ImplicitConversionRank Rank2 = SCS2.getRank();
2155 if (Rank1 < Rank2)
2156 return ImplicitConversionSequence::Better;
2157 else if (Rank2 < Rank1)
2158 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002159
Douglas Gregor57373262008-10-22 14:17:15 +00002160 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2161 // are indistinguishable unless one of the following rules
2162 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00002163
Douglas Gregor57373262008-10-22 14:17:15 +00002164 // A conversion that is not a conversion of a pointer, or
2165 // pointer to member, to bool is better than another conversion
2166 // that is such a conversion.
2167 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2168 return SCS2.isPointerConversionToBool()
2169 ? ImplicitConversionSequence::Better
2170 : ImplicitConversionSequence::Worse;
2171
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002172 // C++ [over.ics.rank]p4b2:
2173 //
2174 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002175 // conversion of B* to A* is better than conversion of B* to
2176 // void*, and conversion of A* to void* is better than conversion
2177 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00002178 bool SCS1ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002179 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002180 bool SCS2ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002181 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002182 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2183 // Exactly one of the conversion sequences is a conversion to
2184 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002185 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2186 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002187 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2188 // Neither conversion sequence converts to a void pointer; compare
2189 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002190 if (ImplicitConversionSequence::CompareKind DerivedCK
2191 = CompareDerivedToBaseConversions(SCS1, SCS2))
2192 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002193 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2194 // Both conversion sequences are conversions to void
2195 // pointers. Compare the source types to determine if there's an
2196 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00002197 QualType FromType1 = SCS1.getFromType();
2198 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002199
2200 // Adjust the types we're converting from via the array-to-pointer
2201 // conversion, if we need to.
2202 if (SCS1.First == ICK_Array_To_Pointer)
2203 FromType1 = Context.getArrayDecayedType(FromType1);
2204 if (SCS2.First == ICK_Array_To_Pointer)
2205 FromType2 = Context.getArrayDecayedType(FromType2);
2206
Douglas Gregor01919692009-12-13 21:37:05 +00002207 QualType FromPointee1
2208 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2209 QualType FromPointee2
2210 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002211
Douglas Gregor01919692009-12-13 21:37:05 +00002212 if (IsDerivedFrom(FromPointee2, FromPointee1))
2213 return ImplicitConversionSequence::Better;
2214 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2215 return ImplicitConversionSequence::Worse;
2216
2217 // Objective-C++: If one interface is more specific than the
2218 // other, it is the better one.
John McCallc12c5bb2010-05-15 11:32:37 +00002219 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2220 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor01919692009-12-13 21:37:05 +00002221 if (FromIface1 && FromIface1) {
2222 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2223 return ImplicitConversionSequence::Better;
2224 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2225 return ImplicitConversionSequence::Worse;
2226 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002227 }
Douglas Gregor57373262008-10-22 14:17:15 +00002228
2229 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2230 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00002231 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00002232 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002233 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00002234
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002235 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002236 // C++0x [over.ics.rank]p3b4:
2237 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2238 // implicit object parameter of a non-static member function declared
2239 // without a ref-qualifier, and S1 binds an rvalue reference to an
2240 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00002241 // FIXME: We don't know if we're dealing with the implicit object parameter,
2242 // or if the member function in this case has a ref qualifier.
2243 // (Of course, we don't have ref qualifiers yet.)
2244 if (SCS1.RRefBinding != SCS2.RRefBinding)
2245 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2246 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002247
2248 // C++ [over.ics.rank]p3b4:
2249 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2250 // which the references refer are the same type except for
2251 // top-level cv-qualifiers, and the type to which the reference
2252 // initialized by S2 refers is more cv-qualified than the type
2253 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00002254 QualType T1 = SCS1.getToType(2);
2255 QualType T2 = SCS2.getToType(2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002256 T1 = Context.getCanonicalType(T1);
2257 T2 = Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002258 Qualifiers T1Quals, T2Quals;
2259 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2260 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2261 if (UnqualT1 == UnqualT2) {
2262 // If the type is an array type, promote the element qualifiers to the type
2263 // for comparison.
2264 if (isa<ArrayType>(T1) && T1Quals)
2265 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2266 if (isa<ArrayType>(T2) && T2Quals)
2267 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002268 if (T2.isMoreQualifiedThan(T1))
2269 return ImplicitConversionSequence::Better;
2270 else if (T1.isMoreQualifiedThan(T2))
2271 return ImplicitConversionSequence::Worse;
2272 }
2273 }
Douglas Gregor57373262008-10-22 14:17:15 +00002274
2275 return ImplicitConversionSequence::Indistinguishable;
2276}
2277
2278/// CompareQualificationConversions - Compares two standard conversion
2279/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00002280/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2281ImplicitConversionSequence::CompareKind
Douglas Gregor57373262008-10-22 14:17:15 +00002282Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump1eb44332009-09-09 15:08:12 +00002283 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00002284 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00002285 // -- S1 and S2 differ only in their qualification conversion and
2286 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2287 // cv-qualification signature of type T1 is a proper subset of
2288 // the cv-qualification signature of type T2, and S1 is not the
2289 // deprecated string literal array-to-pointer conversion (4.2).
2290 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2291 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2292 return ImplicitConversionSequence::Indistinguishable;
2293
2294 // FIXME: the example in the standard doesn't use a qualification
2295 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00002296 QualType T1 = SCS1.getToType(2);
2297 QualType T2 = SCS2.getToType(2);
Douglas Gregor57373262008-10-22 14:17:15 +00002298 T1 = Context.getCanonicalType(T1);
2299 T2 = Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002300 Qualifiers T1Quals, T2Quals;
2301 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2302 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00002303
2304 // If the types are the same, we won't learn anything by unwrapped
2305 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00002306 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00002307 return ImplicitConversionSequence::Indistinguishable;
2308
Chandler Carruth28e318c2009-12-29 07:16:59 +00002309 // If the type is an array type, promote the element qualifiers to the type
2310 // for comparison.
2311 if (isa<ArrayType>(T1) && T1Quals)
2312 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2313 if (isa<ArrayType>(T2) && T2Quals)
2314 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2315
Mike Stump1eb44332009-09-09 15:08:12 +00002316 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00002317 = ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002318 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00002319 // Within each iteration of the loop, we check the qualifiers to
2320 // determine if this still looks like a qualification
2321 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002322 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00002323 // until there are no more pointers or pointers-to-members left
2324 // to unwrap. This essentially mimics what
2325 // IsQualificationConversion does, but here we're checking for a
2326 // strict subset of qualifiers.
2327 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2328 // The qualifiers are the same, so this doesn't tell us anything
2329 // about how the sequences rank.
2330 ;
2331 else if (T2.isMoreQualifiedThan(T1)) {
2332 // T1 has fewer qualifiers, so it could be the better sequence.
2333 if (Result == ImplicitConversionSequence::Worse)
2334 // Neither has qualifiers that are a subset of the other's
2335 // qualifiers.
2336 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002337
Douglas Gregor57373262008-10-22 14:17:15 +00002338 Result = ImplicitConversionSequence::Better;
2339 } else if (T1.isMoreQualifiedThan(T2)) {
2340 // T2 has fewer qualifiers, so it could be the better sequence.
2341 if (Result == ImplicitConversionSequence::Better)
2342 // Neither has qualifiers that are a subset of the other's
2343 // qualifiers.
2344 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002345
Douglas Gregor57373262008-10-22 14:17:15 +00002346 Result = ImplicitConversionSequence::Worse;
2347 } else {
2348 // Qualifiers are disjoint.
2349 return ImplicitConversionSequence::Indistinguishable;
2350 }
2351
2352 // If the types after this point are equivalent, we're done.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002353 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00002354 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002355 }
2356
Douglas Gregor57373262008-10-22 14:17:15 +00002357 // Check that the winning standard conversion sequence isn't using
2358 // the deprecated string literal array to pointer conversion.
2359 switch (Result) {
2360 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00002361 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002362 Result = ImplicitConversionSequence::Indistinguishable;
2363 break;
2364
2365 case ImplicitConversionSequence::Indistinguishable:
2366 break;
2367
2368 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00002369 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002370 Result = ImplicitConversionSequence::Indistinguishable;
2371 break;
2372 }
2373
2374 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002375}
2376
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002377/// CompareDerivedToBaseConversions - Compares two standard conversion
2378/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00002379/// various kinds of derived-to-base conversions (C++
2380/// [over.ics.rank]p4b3). As part of these checks, we also look at
2381/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002382ImplicitConversionSequence::CompareKind
2383Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2384 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00002385 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002386 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00002387 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002388 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002389
2390 // Adjust the types we're converting from via the array-to-pointer
2391 // conversion, if we need to.
2392 if (SCS1.First == ICK_Array_To_Pointer)
2393 FromType1 = Context.getArrayDecayedType(FromType1);
2394 if (SCS2.First == ICK_Array_To_Pointer)
2395 FromType2 = Context.getArrayDecayedType(FromType2);
2396
2397 // Canonicalize all of the types.
2398 FromType1 = Context.getCanonicalType(FromType1);
2399 ToType1 = Context.getCanonicalType(ToType1);
2400 FromType2 = Context.getCanonicalType(FromType2);
2401 ToType2 = Context.getCanonicalType(ToType2);
2402
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002403 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002404 //
2405 // If class B is derived directly or indirectly from class A and
2406 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002407 //
2408 // For Objective-C, we let A, B, and C also be Objective-C
2409 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002410
2411 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00002412 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00002413 SCS2.Second == ICK_Pointer_Conversion &&
2414 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2415 FromType1->isPointerType() && FromType2->isPointerType() &&
2416 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002417 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002418 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002419 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002420 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002421 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002422 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002423 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002424 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002425
John McCallc12c5bb2010-05-15 11:32:37 +00002426 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2427 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2428 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2429 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002430
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002431 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002432 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2433 if (IsDerivedFrom(ToPointee1, ToPointee2))
2434 return ImplicitConversionSequence::Better;
2435 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2436 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00002437
2438 if (ToIface1 && ToIface2) {
2439 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2440 return ImplicitConversionSequence::Better;
2441 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2442 return ImplicitConversionSequence::Worse;
2443 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002444 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002445
2446 // -- conversion of B* to A* is better than conversion of C* to A*,
2447 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2448 if (IsDerivedFrom(FromPointee2, FromPointee1))
2449 return ImplicitConversionSequence::Better;
2450 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2451 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00002452
Douglas Gregorcb7de522008-11-26 23:31:11 +00002453 if (FromIface1 && FromIface2) {
2454 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2455 return ImplicitConversionSequence::Better;
2456 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2457 return ImplicitConversionSequence::Worse;
2458 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002459 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002460 }
2461
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002462 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002463 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2464 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2465 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2466 const MemberPointerType * FromMemPointer1 =
2467 FromType1->getAs<MemberPointerType>();
2468 const MemberPointerType * ToMemPointer1 =
2469 ToType1->getAs<MemberPointerType>();
2470 const MemberPointerType * FromMemPointer2 =
2471 FromType2->getAs<MemberPointerType>();
2472 const MemberPointerType * ToMemPointer2 =
2473 ToType2->getAs<MemberPointerType>();
2474 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2475 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2476 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2477 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2478 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2479 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2480 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2481 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002482 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002483 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2484 if (IsDerivedFrom(ToPointee1, ToPointee2))
2485 return ImplicitConversionSequence::Worse;
2486 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2487 return ImplicitConversionSequence::Better;
2488 }
2489 // conversion of B::* to C::* is better than conversion of A::* to C::*
2490 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2491 if (IsDerivedFrom(FromPointee1, FromPointee2))
2492 return ImplicitConversionSequence::Better;
2493 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2494 return ImplicitConversionSequence::Worse;
2495 }
2496 }
2497
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002498 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002499 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00002500 // -- binding of an expression of type C to a reference of type
2501 // B& is better than binding an expression of type C to a
2502 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002503 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2504 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002505 if (IsDerivedFrom(ToType1, ToType2))
2506 return ImplicitConversionSequence::Better;
2507 else if (IsDerivedFrom(ToType2, ToType1))
2508 return ImplicitConversionSequence::Worse;
2509 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002510
Douglas Gregor225c41e2008-11-03 19:09:14 +00002511 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00002512 // -- binding of an expression of type B to a reference of type
2513 // A& is better than binding an expression of type C to a
2514 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002515 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2516 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002517 if (IsDerivedFrom(FromType2, FromType1))
2518 return ImplicitConversionSequence::Better;
2519 else if (IsDerivedFrom(FromType1, FromType2))
2520 return ImplicitConversionSequence::Worse;
2521 }
2522 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002523
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002524 return ImplicitConversionSequence::Indistinguishable;
2525}
2526
Douglas Gregorabe183d2010-04-13 16:31:36 +00002527/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2528/// determine whether they are reference-related,
2529/// reference-compatible, reference-compatible with added
2530/// qualification, or incompatible, for use in C++ initialization by
2531/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2532/// type, and the first type (T1) is the pointee type of the reference
2533/// type being initialized.
2534Sema::ReferenceCompareResult
2535Sema::CompareReferenceRelationship(SourceLocation Loc,
2536 QualType OrigT1, QualType OrigT2,
2537 bool& DerivedToBase) {
2538 assert(!OrigT1->isReferenceType() &&
2539 "T1 must be the pointee type of the reference type");
2540 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2541
2542 QualType T1 = Context.getCanonicalType(OrigT1);
2543 QualType T2 = Context.getCanonicalType(OrigT2);
2544 Qualifiers T1Quals, T2Quals;
2545 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2546 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2547
2548 // C++ [dcl.init.ref]p4:
2549 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2550 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2551 // T1 is a base class of T2.
2552 if (UnqualT1 == UnqualT2)
2553 DerivedToBase = false;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002554 else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00002555 IsDerivedFrom(UnqualT2, UnqualT1))
2556 DerivedToBase = true;
2557 else
2558 return Ref_Incompatible;
2559
2560 // At this point, we know that T1 and T2 are reference-related (at
2561 // least).
2562
2563 // If the type is an array type, promote the element qualifiers to the type
2564 // for comparison.
2565 if (isa<ArrayType>(T1) && T1Quals)
2566 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2567 if (isa<ArrayType>(T2) && T2Quals)
2568 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2569
2570 // C++ [dcl.init.ref]p4:
2571 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2572 // reference-related to T2 and cv1 is the same cv-qualification
2573 // as, or greater cv-qualification than, cv2. For purposes of
2574 // overload resolution, cases for which cv1 is greater
2575 // cv-qualification than cv2 are identified as
2576 // reference-compatible with added qualification (see 13.3.3.2).
2577 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2578 return Ref_Compatible;
2579 else if (T1.isMoreQualifiedThan(T2))
2580 return Ref_Compatible_With_Added_Qualification;
2581 else
2582 return Ref_Related;
2583}
2584
2585/// \brief Compute an implicit conversion sequence for reference
2586/// initialization.
2587static ImplicitConversionSequence
2588TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2589 SourceLocation DeclLoc,
2590 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00002591 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002592 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2593
2594 // Most paths end in a failed conversion.
2595 ImplicitConversionSequence ICS;
2596 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2597
2598 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2599 QualType T2 = Init->getType();
2600
2601 // If the initializer is the address of an overloaded function, try
2602 // to resolve the overloaded function. If all goes well, T2 is the
2603 // type of the resulting function.
2604 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2605 DeclAccessPair Found;
2606 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2607 false, Found))
2608 T2 = Fn->getType();
2609 }
2610
2611 // Compute some basic properties of the types and the initializer.
2612 bool isRValRef = DeclType->isRValueReferenceType();
2613 bool DerivedToBase = false;
Douglas Gregor23ef6c02010-04-16 17:45:54 +00002614 Expr::isLvalueResult InitLvalue = Init->isLvalue(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002615 Sema::ReferenceCompareResult RefRelationship
2616 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
2617
Douglas Gregorabe183d2010-04-13 16:31:36 +00002618
2619 // C++ [over.ics.ref]p3:
2620 // Except for an implicit object parameter, for which see 13.3.1,
2621 // a standard conversion sequence cannot be formed if it requires
2622 // binding an lvalue reference to non-const to an rvalue or
2623 // binding an rvalue reference to an lvalue.
Douglas Gregor66821b52010-04-18 09:22:00 +00002624 //
2625 // FIXME: DPG doesn't trust this code. It seems far too early to
2626 // abort because of a binding of an rvalue reference to an lvalue.
Douglas Gregorabe183d2010-04-13 16:31:36 +00002627 if (isRValRef && InitLvalue == Expr::LV_Valid)
2628 return ICS;
2629
Douglas Gregor66821b52010-04-18 09:22:00 +00002630 // C++0x [dcl.init.ref]p16:
2631 // A reference to type "cv1 T1" is initialized by an expression
2632 // of type "cv2 T2" as follows:
2633
2634 // -- If the initializer expression
Douglas Gregorabe183d2010-04-13 16:31:36 +00002635 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2636 // reference-compatible with "cv2 T2," or
2637 //
2638 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2639 if (InitLvalue == Expr::LV_Valid &&
2640 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2641 // C++ [over.ics.ref]p1:
2642 // When a parameter of reference type binds directly (8.5.3)
2643 // to an argument expression, the implicit conversion sequence
2644 // is the identity conversion, unless the argument expression
2645 // has a type that is a derived class of the parameter type,
2646 // in which case the implicit conversion sequence is a
2647 // derived-to-base Conversion (13.3.3.1).
2648 ICS.setStandard();
2649 ICS.Standard.First = ICK_Identity;
2650 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2651 ICS.Standard.Third = ICK_Identity;
2652 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2653 ICS.Standard.setToType(0, T2);
2654 ICS.Standard.setToType(1, T1);
2655 ICS.Standard.setToType(2, T1);
2656 ICS.Standard.ReferenceBinding = true;
2657 ICS.Standard.DirectBinding = true;
2658 ICS.Standard.RRefBinding = false;
2659 ICS.Standard.CopyConstructor = 0;
2660
2661 // Nothing more to do: the inaccessibility/ambiguity check for
2662 // derived-to-base conversions is suppressed when we're
2663 // computing the implicit conversion sequence (C++
2664 // [over.best.ics]p2).
2665 return ICS;
2666 }
2667
2668 // -- has a class type (i.e., T2 is a class type), where T1 is
2669 // not reference-related to T2, and can be implicitly
2670 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2671 // is reference-compatible with "cv3 T3" 92) (this
2672 // conversion is selected by enumerating the applicable
2673 // conversion functions (13.3.1.6) and choosing the best
2674 // one through overload resolution (13.3)),
2675 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
2676 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2677 RefRelationship == Sema::Ref_Incompatible) {
2678 CXXRecordDecl *T2RecordDecl
2679 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2680
2681 OverloadCandidateSet CandidateSet(DeclLoc);
2682 const UnresolvedSetImpl *Conversions
2683 = T2RecordDecl->getVisibleConversionFunctions();
2684 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2685 E = Conversions->end(); I != E; ++I) {
2686 NamedDecl *D = *I;
2687 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2688 if (isa<UsingShadowDecl>(D))
2689 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2690
2691 FunctionTemplateDecl *ConvTemplate
2692 = dyn_cast<FunctionTemplateDecl>(D);
2693 CXXConversionDecl *Conv;
2694 if (ConvTemplate)
2695 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2696 else
2697 Conv = cast<CXXConversionDecl>(D);
2698
2699 // If the conversion function doesn't return a reference type,
2700 // it can't be considered for this conversion.
2701 if (Conv->getConversionType()->isLValueReferenceType() &&
2702 (AllowExplicit || !Conv->isExplicit())) {
2703 if (ConvTemplate)
2704 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2705 Init, DeclType, CandidateSet);
2706 else
2707 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2708 DeclType, CandidateSet);
2709 }
2710 }
2711
2712 OverloadCandidateSet::iterator Best;
2713 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2714 case OR_Success:
2715 // C++ [over.ics.ref]p1:
2716 //
2717 // [...] If the parameter binds directly to the result of
2718 // applying a conversion function to the argument
2719 // expression, the implicit conversion sequence is a
2720 // user-defined conversion sequence (13.3.3.1.2), with the
2721 // second standard conversion sequence either an identity
2722 // conversion or, if the conversion function returns an
2723 // entity of a type that is a derived class of the parameter
2724 // type, a derived-to-base Conversion.
2725 if (!Best->FinalConversion.DirectBinding)
2726 break;
2727
2728 ICS.setUserDefined();
2729 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2730 ICS.UserDefined.After = Best->FinalConversion;
2731 ICS.UserDefined.ConversionFunction = Best->Function;
2732 ICS.UserDefined.EllipsisConversion = false;
2733 assert(ICS.UserDefined.After.ReferenceBinding &&
2734 ICS.UserDefined.After.DirectBinding &&
2735 "Expected a direct reference binding!");
2736 return ICS;
2737
2738 case OR_Ambiguous:
2739 ICS.setAmbiguous();
2740 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2741 Cand != CandidateSet.end(); ++Cand)
2742 if (Cand->Viable)
2743 ICS.Ambiguous.addConversion(Cand->Function);
2744 return ICS;
2745
2746 case OR_No_Viable_Function:
2747 case OR_Deleted:
2748 // There was no suitable conversion, or we found a deleted
2749 // conversion; continue with other checks.
2750 break;
2751 }
2752 }
2753
2754 // -- Otherwise, the reference shall be to a non-volatile const
2755 // type (i.e., cv1 shall be const), or the reference shall be an
2756 // rvalue reference and the initializer expression shall be an rvalue.
Douglas Gregor66821b52010-04-18 09:22:00 +00002757 //
2758 // We actually handle one oddity of C++ [over.ics.ref] at this
2759 // point, which is that, due to p2 (which short-circuits reference
2760 // binding by only attempting a simple conversion for non-direct
2761 // bindings) and p3's strange wording, we allow a const volatile
2762 // reference to bind to an rvalue. Hence the check for the presence
2763 // of "const" rather than checking for "const" being the only
2764 // qualifier.
2765 if (!isRValRef && !T1.isConstQualified())
Douglas Gregorabe183d2010-04-13 16:31:36 +00002766 return ICS;
2767
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002768 // -- if T2 is a class type and
2769 // -- the initializer expression is an rvalue and "cv1 T1"
2770 // is reference-compatible with "cv2 T2," or
Douglas Gregorabe183d2010-04-13 16:31:36 +00002771 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002772 // -- T1 is not reference-related to T2 and the initializer
2773 // expression can be implicitly converted to an rvalue
2774 // of type "cv3 T3" (this conversion is selected by
2775 // enumerating the applicable conversion functions
2776 // (13.3.1.6) and choosing the best one through overload
2777 // resolution (13.3)),
Douglas Gregorabe183d2010-04-13 16:31:36 +00002778 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002779 // then the reference is bound to the initializer
2780 // expression rvalue in the first case and to the object
2781 // that is the result of the conversion in the second case
2782 // (or, in either case, to the appropriate base class
2783 // subobject of the object).
Douglas Gregorabe183d2010-04-13 16:31:36 +00002784 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002785 // We're only checking the first case here, which is a direct
2786 // binding in C++0x but not in C++03.
Douglas Gregorabe183d2010-04-13 16:31:36 +00002787 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
2788 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2789 ICS.setStandard();
2790 ICS.Standard.First = ICK_Identity;
2791 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2792 ICS.Standard.Third = ICK_Identity;
2793 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2794 ICS.Standard.setToType(0, T2);
2795 ICS.Standard.setToType(1, T1);
2796 ICS.Standard.setToType(2, T1);
2797 ICS.Standard.ReferenceBinding = true;
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002798 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002799 ICS.Standard.RRefBinding = isRValRef;
2800 ICS.Standard.CopyConstructor = 0;
2801 return ICS;
2802 }
2803
2804 // -- Otherwise, a temporary of type "cv1 T1" is created and
2805 // initialized from the initializer expression using the
2806 // rules for a non-reference copy initialization (8.5). The
2807 // reference is then bound to the temporary. If T1 is
2808 // reference-related to T2, cv1 must be the same
2809 // cv-qualification as, or greater cv-qualification than,
2810 // cv2; otherwise, the program is ill-formed.
2811 if (RefRelationship == Sema::Ref_Related) {
2812 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2813 // we would be reference-compatible or reference-compatible with
2814 // added qualification. But that wasn't the case, so the reference
2815 // initialization fails.
2816 return ICS;
2817 }
2818
2819 // If at least one of the types is a class type, the types are not
2820 // related, and we aren't allowed any user conversions, the
2821 // reference binding fails. This case is important for breaking
2822 // recursion, since TryImplicitConversion below will attempt to
2823 // create a temporary through the use of a copy constructor.
2824 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2825 (T1->isRecordType() || T2->isRecordType()))
2826 return ICS;
2827
2828 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00002829 // When a parameter of reference type is not bound directly to
2830 // an argument expression, the conversion sequence is the one
2831 // required to convert the argument expression to the
2832 // underlying type of the reference according to
2833 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2834 // to copy-initializing a temporary of the underlying type with
2835 // the argument expression. Any difference in top-level
2836 // cv-qualification is subsumed by the initialization itself
2837 // and does not constitute a conversion.
2838 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2839 /*AllowExplicit=*/false,
Douglas Gregorabe183d2010-04-13 16:31:36 +00002840 /*InOverloadResolution=*/false);
2841
2842 // Of course, that's still a reference binding.
2843 if (ICS.isStandard()) {
2844 ICS.Standard.ReferenceBinding = true;
2845 ICS.Standard.RRefBinding = isRValRef;
2846 } else if (ICS.isUserDefined()) {
2847 ICS.UserDefined.After.ReferenceBinding = true;
2848 ICS.UserDefined.After.RRefBinding = isRValRef;
2849 }
2850 return ICS;
2851}
2852
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002853/// TryCopyInitialization - Try to copy-initialize a value of type
2854/// ToType from the expression From. Return the implicit conversion
2855/// sequence required to pass this argument, which may be a bad
2856/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00002857/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00002858/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00002859static ImplicitConversionSequence
2860TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregorb7f9e6a2010-04-16 17:53:55 +00002861 bool SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00002862 bool InOverloadResolution) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002863 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00002864 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00002865 /*FIXME:*/From->getLocStart(),
2866 SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00002867 /*AllowExplicit=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002868
Douglas Gregor74eb6582010-04-16 17:51:22 +00002869 return S.TryImplicitConversion(From, ToType,
2870 SuppressUserConversions,
2871 /*AllowExplicit=*/false,
Douglas Gregor74eb6582010-04-16 17:51:22 +00002872 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002873}
2874
Douglas Gregor96176b32008-11-18 23:14:02 +00002875/// TryObjectArgumentInitialization - Try to initialize the object
2876/// parameter of the given member function (@c Method) from the
2877/// expression @p From.
2878ImplicitConversionSequence
John McCall651f3ee2010-01-14 03:28:57 +00002879Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall701c89e2009-12-03 04:06:58 +00002880 CXXMethodDecl *Method,
2881 CXXRecordDecl *ActingContext) {
2882 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002883 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2884 // const volatile object.
2885 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2886 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2887 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00002888
2889 // Set up the conversion sequence as a "bad" conversion, to allow us
2890 // to exit early.
2891 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00002892
2893 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00002894 QualType FromType = OrigFromType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002895 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00002896 FromType = PT->getPointeeType();
2897
2898 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002899
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002900 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor96176b32008-11-18 23:14:02 +00002901 // where X is the class of which the function is a member
2902 // (C++ [over.match.funcs]p4). However, when finding an implicit
2903 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00002904 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00002905 // (C++ [over.match.funcs]p5). We perform a simplified version of
2906 // reference binding here, that allows class rvalues to bind to
2907 // non-constant references.
2908
2909 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2910 // with the implicit object parameter (C++ [over.match.funcs]p5).
2911 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00002912 if (ImplicitParamType.getCVRQualifiers()
2913 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00002914 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00002915 ICS.setBad(BadConversionSequence::bad_qualifiers,
2916 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002917 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00002918 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002919
2920 // Check that we have either the same type or a derived type. It
2921 // affects the conversion rank.
2922 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00002923 ImplicitConversionKind SecondKind;
2924 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2925 SecondKind = ICK_Identity;
2926 } else if (IsDerivedFrom(FromType, ClassType))
2927 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00002928 else {
John McCallb1bdc622010-02-25 01:37:24 +00002929 ICS.setBad(BadConversionSequence::unrelated_class,
2930 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002931 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00002932 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002933
2934 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00002935 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00002936 ICS.Standard.setAsIdentityConversion();
2937 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00002938 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00002939 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002940 ICS.Standard.ReferenceBinding = true;
2941 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00002942 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002943 return ICS;
2944}
2945
2946/// PerformObjectArgumentInitialization - Perform initialization of
2947/// the implicit object parameter for the given Method with the given
2948/// expression.
2949bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00002950Sema::PerformObjectArgumentInitialization(Expr *&From,
2951 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00002952 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002953 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002954 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00002955 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00002956 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002957
Ted Kremenek6217b802009-07-29 21:53:49 +00002958 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002959 FromRecordType = PT->getPointeeType();
2960 DestType = Method->getThisType(Context);
2961 } else {
2962 FromRecordType = From->getType();
2963 DestType = ImplicitParamRecordType;
2964 }
2965
John McCall701c89e2009-12-03 04:06:58 +00002966 // Note that we always use the true parent context when performing
2967 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002968 ImplicitConversionSequence ICS
John McCall701c89e2009-12-03 04:06:58 +00002969 = TryObjectArgumentInitialization(From->getType(), Method,
2970 Method->getParent());
John McCall1d318332010-01-12 00:44:57 +00002971 if (ICS.isBad())
Douglas Gregor96176b32008-11-18 23:14:02 +00002972 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002973 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00002974 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002975
Douglas Gregor5fccd362010-03-03 23:55:11 +00002976 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall6bb80172010-03-30 21:47:33 +00002977 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor96176b32008-11-18 23:14:02 +00002978
Douglas Gregor5fccd362010-03-03 23:55:11 +00002979 if (!Context.hasSameType(From->getType(), DestType))
Anders Carlssonf1b48b72010-04-24 16:57:13 +00002980 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
2981 /*isLvalue=*/!From->getType()->isPointerType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002982 return false;
2983}
2984
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002985/// TryContextuallyConvertToBool - Attempt to contextually convert the
2986/// expression From to bool (C++0x [conv]p3).
2987ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00002988 // FIXME: This is pretty broken.
Mike Stump1eb44332009-09-09 15:08:12 +00002989 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002990 // FIXME: Are these flags correct?
2991 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00002992 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00002993 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002994}
2995
2996/// PerformContextuallyConvertToBool - Perform a contextual conversion
2997/// of the expression From to bool (C++0x [conv]p3).
2998bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2999 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall1d318332010-01-12 00:44:57 +00003000 if (!ICS.isBad())
3001 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003002
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003003 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003004 return Diag(From->getSourceRange().getBegin(),
3005 diag::err_typecheck_bool_condition)
3006 << From->getType() << From->getSourceRange();
3007 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003008}
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003009
3010/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3011/// expression From to 'id'.
3012ImplicitConversionSequence Sema::TryContextuallyConvertToObjCId(Expr *From) {
John McCallc12c5bb2010-05-15 11:32:37 +00003013 QualType Ty = Context.getObjCIdType();
3014 return TryImplicitConversion(From, Ty,
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003015 // FIXME: Are these flags correct?
3016 /*SuppressUserConversions=*/false,
3017 /*AllowExplicit=*/true,
3018 /*InOverloadResolution=*/false);
3019}
3020
3021/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3022/// of the expression From to 'id'.
3023bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCallc12c5bb2010-05-15 11:32:37 +00003024 QualType Ty = Context.getObjCIdType();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003025 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(From);
3026 if (!ICS.isBad())
3027 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3028 return true;
3029}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003030
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003031/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00003032/// candidate functions, using the given function call arguments. If
3033/// @p SuppressUserConversions, then don't allow user-defined
3034/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003035///
3036/// \para PartialOverloading true if we are performing "partial" overloading
3037/// based on an incomplete set of function arguments. This feature is used by
3038/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00003039void
3040Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00003041 DeclAccessPair FoundDecl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003042 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00003043 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00003044 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003045 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00003046 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003047 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003048 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00003049 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00003050 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00003051
Douglas Gregor88a35142008-12-22 05:46:06 +00003052 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003053 if (!isa<CXXConstructorDecl>(Method)) {
3054 // If we get here, it's because we're calling a member function
3055 // that is named without a member access expression (e.g.,
3056 // "this->f") that was either written explicitly or created
3057 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00003058 // function, e.g., X::f(). We use an empty type for the implied
3059 // object argument (C++ [over.call.func]p3), and the acting context
3060 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00003061 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall701c89e2009-12-03 04:06:58 +00003062 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003063 SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003064 return;
3065 }
3066 // We treat a constructor like a non-member function, since its object
3067 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00003068 }
3069
Douglas Gregorfd476482009-11-13 23:59:09 +00003070 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00003071 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00003072
Douglas Gregor7edfb692009-11-23 12:27:39 +00003073 // Overload resolution is always an unevaluated context.
3074 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3075
Douglas Gregor66724ea2009-11-14 01:20:54 +00003076 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3077 // C++ [class.copy]p3:
3078 // A member function template is never instantiated to perform the copy
3079 // of a class object to an object of its class type.
3080 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3081 if (NumArgs == 1 &&
3082 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor12116062010-02-21 18:30:38 +00003083 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3084 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00003085 return;
3086 }
3087
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003088 // Add this candidate
3089 CandidateSet.push_back(OverloadCandidate());
3090 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003091 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003092 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00003093 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003094 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003095 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003096
3097 unsigned NumArgsInProto = Proto->getNumArgs();
3098
3099 // (C++ 13.3.2p2): A candidate function having fewer than m
3100 // parameters is viable only if it has an ellipsis in its parameter
3101 // list (8.3.5).
Douglas Gregor5bd1a112009-09-23 14:56:09 +00003102 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3103 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003104 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003105 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003106 return;
3107 }
3108
3109 // (C++ 13.3.2p2): A candidate function having more than m parameters
3110 // is viable only if the (m+1)st parameter has a default argument
3111 // (8.3.6). For the purposes of overload resolution, the
3112 // parameter list is truncated on the right, so that there are
3113 // exactly m parameters.
3114 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003115 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003116 // Not enough arguments.
3117 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003118 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003119 return;
3120 }
3121
3122 // Determine the implicit conversion sequences for each of the
3123 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003124 Candidate.Conversions.resize(NumArgs);
3125 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3126 if (ArgIdx < NumArgsInProto) {
3127 // (C++ 13.3.2p3): for F to be a viable function, there shall
3128 // exist for each argument an implicit conversion sequence
3129 // (13.3.3.1) that converts that argument to the corresponding
3130 // parameter of F.
3131 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003132 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003133 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003134 SuppressUserConversions,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003135 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003136 if (Candidate.Conversions[ArgIdx].isBad()) {
3137 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003138 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00003139 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00003140 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003141 } else {
3142 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3143 // argument for which there is no corresponding parameter is
3144 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003145 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003146 }
3147 }
3148}
3149
Douglas Gregor063daf62009-03-13 18:40:31 +00003150/// \brief Add all of the function declarations in the given function set to
3151/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00003152void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00003153 Expr **Args, unsigned NumArgs,
3154 OverloadCandidateSet& CandidateSet,
3155 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00003156 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00003157 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3158 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003159 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003160 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003161 cast<CXXMethodDecl>(FD)->getParent(),
3162 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003163 CandidateSet, SuppressUserConversions);
3164 else
John McCall9aa472c2010-03-19 07:35:19 +00003165 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00003166 SuppressUserConversions);
3167 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003168 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00003169 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3170 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003171 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003172 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00003173 /*FIXME: explicit args */ 0,
John McCall701c89e2009-12-03 04:06:58 +00003174 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003175 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00003176 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00003177 else
John McCall9aa472c2010-03-19 07:35:19 +00003178 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCalld5532b62009-11-23 01:53:49 +00003179 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00003180 Args, NumArgs, CandidateSet,
3181 SuppressUserConversions);
3182 }
Douglas Gregor364e0212009-06-27 21:05:07 +00003183 }
Douglas Gregor063daf62009-03-13 18:40:31 +00003184}
3185
John McCall314be4e2009-11-17 07:50:12 +00003186/// AddMethodCandidate - Adds a named decl (which is some kind of
3187/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00003188void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003189 QualType ObjectType,
John McCall314be4e2009-11-17 07:50:12 +00003190 Expr **Args, unsigned NumArgs,
3191 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003192 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00003193 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003194 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00003195
3196 if (isa<UsingShadowDecl>(Decl))
3197 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3198
3199 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3200 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3201 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00003202 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3203 /*ExplicitArgs*/ 0,
John McCall701c89e2009-12-03 04:06:58 +00003204 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00003205 CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003206 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003207 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003208 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall701c89e2009-12-03 04:06:58 +00003209 ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003210 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003211 }
3212}
3213
Douglas Gregor96176b32008-11-18 23:14:02 +00003214/// AddMethodCandidate - Adds the given C++ member function to the set
3215/// of candidate functions, using the given function call arguments
3216/// and the object argument (@c Object). For example, in a call
3217/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3218/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3219/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00003220/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00003221void
John McCall9aa472c2010-03-19 07:35:19 +00003222Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003223 CXXRecordDecl *ActingContext, QualType ObjectType,
3224 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00003225 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003226 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00003227 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003228 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00003229 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003230 assert(!isa<CXXConstructorDecl>(Method) &&
3231 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00003232
Douglas Gregor3f396022009-09-28 04:47:19 +00003233 if (!CandidateSet.isNewCandidate(Method))
3234 return;
3235
Douglas Gregor7edfb692009-11-23 12:27:39 +00003236 // Overload resolution is always an unevaluated context.
3237 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3238
Douglas Gregor96176b32008-11-18 23:14:02 +00003239 // Add this candidate
3240 CandidateSet.push_back(OverloadCandidate());
3241 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003242 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00003243 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003244 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003245 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003246
3247 unsigned NumArgsInProto = Proto->getNumArgs();
3248
3249 // (C++ 13.3.2p2): A candidate function having fewer than m
3250 // parameters is viable only if it has an ellipsis in its parameter
3251 // list (8.3.5).
3252 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3253 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003254 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003255 return;
3256 }
3257
3258 // (C++ 13.3.2p2): A candidate function having more than m parameters
3259 // is viable only if the (m+1)st parameter has a default argument
3260 // (8.3.6). For the purposes of overload resolution, the
3261 // parameter list is truncated on the right, so that there are
3262 // exactly m parameters.
3263 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3264 if (NumArgs < MinRequiredArgs) {
3265 // Not enough arguments.
3266 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003267 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003268 return;
3269 }
3270
3271 Candidate.Viable = true;
3272 Candidate.Conversions.resize(NumArgs + 1);
3273
John McCall701c89e2009-12-03 04:06:58 +00003274 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00003275 // The implicit object argument is ignored.
3276 Candidate.IgnoreObjectArgument = true;
3277 else {
3278 // Determine the implicit conversion sequence for the object
3279 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00003280 Candidate.Conversions[0]
3281 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00003282 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003283 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003284 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00003285 return;
3286 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003287 }
3288
3289 // Determine the implicit conversion sequences for each of the
3290 // arguments.
3291 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3292 if (ArgIdx < NumArgsInProto) {
3293 // (C++ 13.3.2p3): for F to be a viable function, there shall
3294 // exist for each argument an implicit conversion sequence
3295 // (13.3.3.1) that converts that argument to the corresponding
3296 // parameter of F.
3297 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003298 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003299 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003300 SuppressUserConversions,
Anders Carlsson08972922009-08-28 15:33:32 +00003301 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003302 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00003303 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003304 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00003305 break;
3306 }
3307 } else {
3308 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3309 // argument for which there is no corresponding parameter is
3310 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003311 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00003312 }
3313 }
3314}
Douglas Gregora9333192010-05-08 17:41:32 +00003315
Douglas Gregor6b906862009-08-21 00:16:32 +00003316/// \brief Add a C++ member function template as a candidate to the candidate
3317/// set, using template argument deduction to produce an appropriate member
3318/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003319void
Douglas Gregor6b906862009-08-21 00:16:32 +00003320Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00003321 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003322 CXXRecordDecl *ActingContext,
John McCalld5532b62009-11-23 01:53:49 +00003323 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00003324 QualType ObjectType,
3325 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003326 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003327 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003328 if (!CandidateSet.isNewCandidate(MethodTmpl))
3329 return;
3330
Douglas Gregor6b906862009-08-21 00:16:32 +00003331 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003332 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00003333 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003334 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00003335 // candidate functions in the usual way.113) A given name can refer to one
3336 // or more function templates and also to a set of overloaded non-template
3337 // functions. In such a case, the candidate functions generated from each
3338 // function template are combined with the set of non-template candidate
3339 // functions.
John McCall5769d612010-02-08 23:07:23 +00003340 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00003341 FunctionDecl *Specialization = 0;
3342 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003343 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003344 Args, NumArgs, Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003345 CandidateSet.push_back(OverloadCandidate());
3346 OverloadCandidate &Candidate = CandidateSet.back();
3347 Candidate.FoundDecl = FoundDecl;
3348 Candidate.Function = MethodTmpl->getTemplatedDecl();
3349 Candidate.Viable = false;
3350 Candidate.FailureKind = ovl_fail_bad_deduction;
3351 Candidate.IsSurrogate = false;
3352 Candidate.IgnoreObjectArgument = false;
3353 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3354 Info);
3355 return;
3356 }
Mike Stump1eb44332009-09-09 15:08:12 +00003357
Douglas Gregor6b906862009-08-21 00:16:32 +00003358 // Add the function template specialization produced by template argument
3359 // deduction as a candidate.
3360 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00003361 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00003362 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00003363 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003364 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003365 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00003366}
3367
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003368/// \brief Add a C++ function template specialization as a candidate
3369/// in the candidate set, using template argument deduction to produce
3370/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003371void
Douglas Gregore53060f2009-06-25 22:08:12 +00003372Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003373 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00003374 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00003375 Expr **Args, unsigned NumArgs,
3376 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003377 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003378 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3379 return;
3380
Douglas Gregore53060f2009-06-25 22:08:12 +00003381 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003382 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00003383 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003384 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00003385 // candidate functions in the usual way.113) A given name can refer to one
3386 // or more function templates and also to a set of overloaded non-template
3387 // functions. In such a case, the candidate functions generated from each
3388 // function template are combined with the set of non-template candidate
3389 // functions.
John McCall5769d612010-02-08 23:07:23 +00003390 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00003391 FunctionDecl *Specialization = 0;
3392 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003393 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003394 Args, NumArgs, Specialization, Info)) {
John McCall578b69b2009-12-16 08:11:27 +00003395 CandidateSet.push_back(OverloadCandidate());
3396 OverloadCandidate &Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003397 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00003398 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3399 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003400 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00003401 Candidate.IsSurrogate = false;
3402 Candidate.IgnoreObjectArgument = false;
Douglas Gregorff5adac2010-05-08 20:18:54 +00003403 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3404 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00003405 return;
3406 }
Mike Stump1eb44332009-09-09 15:08:12 +00003407
Douglas Gregore53060f2009-06-25 22:08:12 +00003408 // Add the function template specialization produced by template argument
3409 // deduction as a candidate.
3410 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003411 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003412 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00003413}
Mike Stump1eb44332009-09-09 15:08:12 +00003414
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003415/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00003416/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003417/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00003418/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003419/// (which may or may not be the same type as the type that the
3420/// conversion function produces).
3421void
3422Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003423 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003424 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003425 Expr *From, QualType ToType,
3426 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003427 assert(!Conversion->getDescribedFunctionTemplate() &&
3428 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003429 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00003430 if (!CandidateSet.isNewCandidate(Conversion))
3431 return;
3432
Douglas Gregor7edfb692009-11-23 12:27:39 +00003433 // Overload resolution is always an unevaluated context.
3434 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3435
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003436 // Add this candidate
3437 CandidateSet.push_back(OverloadCandidate());
3438 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003439 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003440 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003441 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003442 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003443 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003444 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003445 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003446
Douglas Gregor96176b32008-11-18 23:14:02 +00003447 // Determine the implicit conversion sequence for the implicit
3448 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003449 Candidate.Viable = true;
3450 Candidate.Conversions.resize(1);
John McCall701c89e2009-12-03 04:06:58 +00003451 Candidate.Conversions[0]
3452 = TryObjectArgumentInitialization(From->getType(), Conversion,
3453 ActingContext);
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00003454 // Conversion functions to a different type in the base class is visible in
3455 // the derived class. So, a derived to base conversion should not participate
3456 // in overload resolution.
3457 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
3458 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall1d318332010-01-12 00:44:57 +00003459 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003460 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003461 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003462 return;
3463 }
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003464
3465 // We won't go through a user-define type conversion function to convert a
3466 // derived to base as such conversions are given Conversion Rank. They only
3467 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3468 QualType FromCanon
3469 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3470 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3471 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3472 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003473 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003474 return;
3475 }
3476
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003477 // To determine what the conversion from the result of calling the
3478 // conversion function to the type we're eventually trying to
3479 // convert to (ToType), we need to synthesize a call to the
3480 // conversion function and attempt copy initialization from it. This
3481 // makes sure that we get the right semantics with respect to
3482 // lvalues/rvalues and the type. Fortunately, we can allocate this
3483 // call on the stack and we don't need its arguments to be
3484 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00003485 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003486 From->getLocStart());
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003487 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman73c39ab2009-10-20 08:27:19 +00003488 CastExpr::CK_FunctionToPointerDecay,
Anders Carlssonf1b48b72010-04-24 16:57:13 +00003489 &ConversionRef, CXXBaseSpecifierArray(), false);
Mike Stump1eb44332009-09-09 15:08:12 +00003490
3491 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00003492 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3493 // allocator).
Mike Stump1eb44332009-09-09 15:08:12 +00003494 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003495 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003496 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00003497 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00003498 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00003499 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003500 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00003501
John McCall1d318332010-01-12 00:44:57 +00003502 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003503 case ImplicitConversionSequence::StandardConversion:
3504 Candidate.FinalConversion = ICS.Standard;
Douglas Gregorc520c842010-04-12 23:42:09 +00003505
3506 // C++ [over.ics.user]p3:
3507 // If the user-defined conversion is specified by a specialization of a
3508 // conversion function template, the second standard conversion sequence
3509 // shall have exact match rank.
3510 if (Conversion->getPrimaryTemplate() &&
3511 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3512 Candidate.Viable = false;
3513 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3514 }
3515
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003516 break;
3517
3518 case ImplicitConversionSequence::BadConversion:
3519 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003520 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003521 break;
3522
3523 default:
Mike Stump1eb44332009-09-09 15:08:12 +00003524 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003525 "Can only end up with a standard conversion sequence or failure");
3526 }
3527}
3528
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003529/// \brief Adds a conversion function template specialization
3530/// candidate to the overload set, using template argument deduction
3531/// to deduce the template arguments of the conversion function
3532/// template from the type that we are converting to (C++
3533/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00003534void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003535Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003536 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003537 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003538 Expr *From, QualType ToType,
3539 OverloadCandidateSet &CandidateSet) {
3540 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3541 "Only conversion function templates permitted here");
3542
Douglas Gregor3f396022009-09-28 04:47:19 +00003543 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3544 return;
3545
John McCall5769d612010-02-08 23:07:23 +00003546 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003547 CXXConversionDecl *Specialization = 0;
3548 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00003549 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003550 Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003551 CandidateSet.push_back(OverloadCandidate());
3552 OverloadCandidate &Candidate = CandidateSet.back();
3553 Candidate.FoundDecl = FoundDecl;
3554 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3555 Candidate.Viable = false;
3556 Candidate.FailureKind = ovl_fail_bad_deduction;
3557 Candidate.IsSurrogate = false;
3558 Candidate.IgnoreObjectArgument = false;
3559 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3560 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003561 return;
3562 }
Mike Stump1eb44332009-09-09 15:08:12 +00003563
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003564 // Add the conversion function template specialization produced by
3565 // template argument deduction as a candidate.
3566 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003567 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00003568 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003569}
3570
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003571/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3572/// converts the given @c Object to a function pointer via the
3573/// conversion function @c Conversion, and then attempts to call it
3574/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3575/// the type of function that we'll eventually be calling.
3576void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003577 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003578 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00003579 const FunctionProtoType *Proto,
John McCall701c89e2009-12-03 04:06:58 +00003580 QualType ObjectType,
3581 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003582 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003583 if (!CandidateSet.isNewCandidate(Conversion))
3584 return;
3585
Douglas Gregor7edfb692009-11-23 12:27:39 +00003586 // Overload resolution is always an unevaluated context.
3587 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3588
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003589 CandidateSet.push_back(OverloadCandidate());
3590 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003591 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003592 Candidate.Function = 0;
3593 Candidate.Surrogate = Conversion;
3594 Candidate.Viable = true;
3595 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003596 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003597 Candidate.Conversions.resize(NumArgs + 1);
3598
3599 // Determine the implicit conversion sequence for the implicit
3600 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00003601 ImplicitConversionSequence ObjectInit
John McCall701c89e2009-12-03 04:06:58 +00003602 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00003603 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003604 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003605 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00003606 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003607 return;
3608 }
3609
3610 // The first conversion is actually a user-defined conversion whose
3611 // first conversion is ObjectInit's standard conversion (which is
3612 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00003613 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003614 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00003615 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003616 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00003617 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003618 = Candidate.Conversions[0].UserDefined.Before;
3619 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3620
Mike Stump1eb44332009-09-09 15:08:12 +00003621 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003622 unsigned NumArgsInProto = Proto->getNumArgs();
3623
3624 // (C++ 13.3.2p2): A candidate function having fewer than m
3625 // parameters is viable only if it has an ellipsis in its parameter
3626 // list (8.3.5).
3627 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3628 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003629 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003630 return;
3631 }
3632
3633 // Function types don't have any default arguments, so just check if
3634 // we have enough arguments.
3635 if (NumArgs < NumArgsInProto) {
3636 // Not enough arguments.
3637 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003638 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003639 return;
3640 }
3641
3642 // Determine the implicit conversion sequences for each of the
3643 // arguments.
3644 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3645 if (ArgIdx < NumArgsInProto) {
3646 // (C++ 13.3.2p3): for F to be a viable function, there shall
3647 // exist for each argument an implicit conversion sequence
3648 // (13.3.3.1) that converts that argument to the corresponding
3649 // parameter of F.
3650 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003651 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003652 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00003653 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003654 /*InOverloadResolution=*/false);
John McCall1d318332010-01-12 00:44:57 +00003655 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003656 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003657 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003658 break;
3659 }
3660 } else {
3661 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3662 // argument for which there is no corresponding parameter is
3663 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003664 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003665 }
3666 }
3667}
3668
Douglas Gregor063daf62009-03-13 18:40:31 +00003669/// \brief Add overload candidates for overloaded operators that are
3670/// member functions.
3671///
3672/// Add the overloaded operator candidates that are member functions
3673/// for the operator Op that was used in an operator expression such
3674/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3675/// CandidateSet will store the added overload candidates. (C++
3676/// [over.match.oper]).
3677void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3678 SourceLocation OpLoc,
3679 Expr **Args, unsigned NumArgs,
3680 OverloadCandidateSet& CandidateSet,
3681 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00003682 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3683
3684 // C++ [over.match.oper]p3:
3685 // For a unary operator @ with an operand of a type whose
3686 // cv-unqualified version is T1, and for a binary operator @ with
3687 // a left operand of a type whose cv-unqualified version is T1 and
3688 // a right operand of a type whose cv-unqualified version is T2,
3689 // three sets of candidate functions, designated member
3690 // candidates, non-member candidates and built-in candidates, are
3691 // constructed as follows:
3692 QualType T1 = Args[0]->getType();
3693 QualType T2;
3694 if (NumArgs > 1)
3695 T2 = Args[1]->getType();
3696
3697 // -- If T1 is a class type, the set of member candidates is the
3698 // result of the qualified lookup of T1::operator@
3699 // (13.3.1.1.1); otherwise, the set of member candidates is
3700 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00003701 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003702 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003703 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003704 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003705
John McCalla24dc2e2009-11-17 02:14:36 +00003706 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3707 LookupQualifiedName(Operators, T1Rec->getDecl());
3708 Operators.suppressDiagnostics();
3709
Mike Stump1eb44332009-09-09 15:08:12 +00003710 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003711 OperEnd = Operators.end();
3712 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00003713 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00003714 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall701c89e2009-12-03 04:06:58 +00003715 Args + 1, NumArgs - 1, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00003716 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00003717 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003718}
3719
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003720/// AddBuiltinCandidate - Add a candidate for a built-in
3721/// operator. ResultTy and ParamTys are the result and parameter types
3722/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003723/// arguments being passed to the candidate. IsAssignmentOperator
3724/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003725/// operator. NumContextualBoolArguments is the number of arguments
3726/// (at the beginning of the argument list) that will be contextually
3727/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00003728void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003729 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003730 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003731 bool IsAssignmentOperator,
3732 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00003733 // Overload resolution is always an unevaluated context.
3734 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3735
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003736 // Add this candidate
3737 CandidateSet.push_back(OverloadCandidate());
3738 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003739 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003740 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003741 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003742 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003743 Candidate.BuiltinTypes.ResultTy = ResultTy;
3744 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3745 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3746
3747 // Determine the implicit conversion sequences for each of the
3748 // arguments.
3749 Candidate.Viable = true;
3750 Candidate.Conversions.resize(NumArgs);
3751 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003752 // C++ [over.match.oper]p4:
3753 // For the built-in assignment operators, conversions of the
3754 // left operand are restricted as follows:
3755 // -- no temporaries are introduced to hold the left operand, and
3756 // -- no user-defined conversions are applied to the left
3757 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00003758 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003759 //
3760 // We block these conversions by turning off user-defined
3761 // conversions, since that is the only way that initialization of
3762 // a reference to a non-class type can occur from something that
3763 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003764 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00003765 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003766 "Contextual conversion to bool requires bool type");
3767 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3768 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003769 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003770 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00003771 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003772 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003773 }
John McCall1d318332010-01-12 00:44:57 +00003774 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003775 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003776 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00003777 break;
3778 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003779 }
3780}
3781
3782/// BuiltinCandidateTypeSet - A set of types that will be used for the
3783/// candidate operator functions for built-in operators (C++
3784/// [over.built]). The types are separated into pointer types and
3785/// enumeration types.
3786class BuiltinCandidateTypeSet {
3787 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003788 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003789
3790 /// PointerTypes - The set of pointer types that will be used in the
3791 /// built-in candidates.
3792 TypeSet PointerTypes;
3793
Sebastian Redl78eb8742009-04-19 21:53:20 +00003794 /// MemberPointerTypes - The set of member pointer types that will be
3795 /// used in the built-in candidates.
3796 TypeSet MemberPointerTypes;
3797
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003798 /// EnumerationTypes - The set of enumeration types that will be
3799 /// used in the built-in candidates.
3800 TypeSet EnumerationTypes;
3801
Douglas Gregor26bcf672010-05-19 03:21:00 +00003802 /// \brief The set of vector types that will be used in the built-in
3803 /// candidates.
3804 TypeSet VectorTypes;
3805
Douglas Gregor5842ba92009-08-24 15:23:48 +00003806 /// Sema - The semantic analysis instance where we are building the
3807 /// candidate type set.
3808 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00003809
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003810 /// Context - The AST context in which we will build the type sets.
3811 ASTContext &Context;
3812
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003813 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3814 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00003815 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003816
3817public:
3818 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003819 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003820
Mike Stump1eb44332009-09-09 15:08:12 +00003821 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor5842ba92009-08-24 15:23:48 +00003822 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003823
Douglas Gregor573d9c32009-10-21 23:19:44 +00003824 void AddTypesConvertedFrom(QualType Ty,
3825 SourceLocation Loc,
3826 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003827 bool AllowExplicitConversions,
3828 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003829
3830 /// pointer_begin - First pointer type found;
3831 iterator pointer_begin() { return PointerTypes.begin(); }
3832
Sebastian Redl78eb8742009-04-19 21:53:20 +00003833 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003834 iterator pointer_end() { return PointerTypes.end(); }
3835
Sebastian Redl78eb8742009-04-19 21:53:20 +00003836 /// member_pointer_begin - First member pointer type found;
3837 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3838
3839 /// member_pointer_end - Past the last member pointer type found;
3840 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3841
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003842 /// enumeration_begin - First enumeration type found;
3843 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3844
Sebastian Redl78eb8742009-04-19 21:53:20 +00003845 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003846 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregor26bcf672010-05-19 03:21:00 +00003847
3848 iterator vector_begin() { return VectorTypes.begin(); }
3849 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003850};
3851
Sebastian Redl78eb8742009-04-19 21:53:20 +00003852/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003853/// the set of pointer types along with any more-qualified variants of
3854/// that type. For example, if @p Ty is "int const *", this routine
3855/// will add "int const *", "int const volatile *", "int const
3856/// restrict *", and "int const volatile restrict *" to the set of
3857/// pointer types. Returns true if the add of @p Ty itself succeeded,
3858/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003859///
3860/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003861bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00003862BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3863 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00003864
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003865 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003866 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003867 return false;
3868
John McCall0953e762009-09-24 19:53:00 +00003869 const PointerType *PointerTy = Ty->getAs<PointerType>();
3870 assert(PointerTy && "type was not a pointer type!");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003871
John McCall0953e762009-09-24 19:53:00 +00003872 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003873 // Don't add qualified variants of arrays. For one, they're not allowed
3874 // (the qualifier would sink to the element type), and for another, the
3875 // only overload situation where it matters is subscript or pointer +- int,
3876 // and those shouldn't have qualifier variants anyway.
3877 if (PointeeTy->isArrayType())
3878 return true;
John McCall0953e762009-09-24 19:53:00 +00003879 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00003880 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00003881 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003882 bool hasVolatile = VisibleQuals.hasVolatile();
3883 bool hasRestrict = VisibleQuals.hasRestrict();
3884
John McCall0953e762009-09-24 19:53:00 +00003885 // Iterate through all strict supersets of BaseCVR.
3886 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3887 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003888 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3889 // in the types.
3890 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3891 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00003892 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3893 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003894 }
3895
3896 return true;
3897}
3898
Sebastian Redl78eb8742009-04-19 21:53:20 +00003899/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3900/// to the set of pointer types along with any more-qualified variants of
3901/// that type. For example, if @p Ty is "int const *", this routine
3902/// will add "int const *", "int const volatile *", "int const
3903/// restrict *", and "int const volatile restrict *" to the set of
3904/// pointer types. Returns true if the add of @p Ty itself succeeded,
3905/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003906///
3907/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003908bool
3909BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3910 QualType Ty) {
3911 // Insert this type.
3912 if (!MemberPointerTypes.insert(Ty))
3913 return false;
3914
John McCall0953e762009-09-24 19:53:00 +00003915 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3916 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00003917
John McCall0953e762009-09-24 19:53:00 +00003918 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003919 // Don't add qualified variants of arrays. For one, they're not allowed
3920 // (the qualifier would sink to the element type), and for another, the
3921 // only overload situation where it matters is subscript or pointer +- int,
3922 // and those shouldn't have qualifier variants anyway.
3923 if (PointeeTy->isArrayType())
3924 return true;
John McCall0953e762009-09-24 19:53:00 +00003925 const Type *ClassTy = PointerTy->getClass();
3926
3927 // Iterate through all strict supersets of the pointee type's CVR
3928 // qualifiers.
3929 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3930 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3931 if ((CVR | BaseCVR) != CVR) continue;
3932
3933 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3934 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00003935 }
3936
3937 return true;
3938}
3939
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003940/// AddTypesConvertedFrom - Add each of the types to which the type @p
3941/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00003942/// primarily interested in pointer types and enumeration types. We also
3943/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003944/// AllowUserConversions is true if we should look at the conversion
3945/// functions of a class type, and AllowExplicitConversions if we
3946/// should also include the explicit conversion functions of a class
3947/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003948void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003949BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00003950 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003951 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003952 bool AllowExplicitConversions,
3953 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003954 // Only deal with canonical types.
3955 Ty = Context.getCanonicalType(Ty);
3956
3957 // Look through reference types; they aren't part of the type of an
3958 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00003959 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003960 Ty = RefTy->getPointeeType();
3961
3962 // We don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003963 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003964
Sebastian Redla65b5512009-11-05 16:36:20 +00003965 // If we're dealing with an array type, decay to the pointer.
3966 if (Ty->isArrayType())
3967 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3968
Ted Kremenek6217b802009-07-29 21:53:49 +00003969 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003970 QualType PointeeTy = PointerTy->getPointeeType();
3971
3972 // Insert our type, and its more-qualified variants, into the set
3973 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003974 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003975 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00003976 } else if (Ty->isMemberPointerType()) {
3977 // Member pointers are far easier, since the pointee can't be converted.
3978 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3979 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003980 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00003981 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00003982 } else if (Ty->isVectorType()) {
3983 VectorTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003984 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003985 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003986 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003987 // No conversion functions in incomplete types.
3988 return;
3989 }
Mike Stump1eb44332009-09-09 15:08:12 +00003990
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003991 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00003992 const UnresolvedSetImpl *Conversions
Fariborz Jahanianca4fb042009-10-07 17:26:09 +00003993 = ClassDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003994 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00003995 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00003996 NamedDecl *D = I.getDecl();
3997 if (isa<UsingShadowDecl>(D))
3998 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003999
Mike Stump1eb44332009-09-09 15:08:12 +00004000 // Skip conversion function templates; they don't tell us anything
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004001 // about which builtin types we can convert to.
John McCall32daa422010-03-31 01:36:47 +00004002 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004003 continue;
4004
John McCall32daa422010-03-31 01:36:47 +00004005 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004006 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00004007 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004008 VisibleQuals);
4009 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004010 }
4011 }
4012 }
4013}
4014
Douglas Gregor19b7b152009-08-24 13:43:27 +00004015/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4016/// the volatile- and non-volatile-qualified assignment operators for the
4017/// given type to the candidate set.
4018static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4019 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00004020 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004021 unsigned NumArgs,
4022 OverloadCandidateSet &CandidateSet) {
4023 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00004024
Douglas Gregor19b7b152009-08-24 13:43:27 +00004025 // T& operator=(T&, T)
4026 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4027 ParamTypes[1] = T;
4028 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4029 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004030
Douglas Gregor19b7b152009-08-24 13:43:27 +00004031 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4032 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00004033 ParamTypes[0]
4034 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00004035 ParamTypes[1] = T;
4036 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00004037 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00004038 }
4039}
Mike Stump1eb44332009-09-09 15:08:12 +00004040
Sebastian Redl9994a342009-10-25 17:03:50 +00004041/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4042/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004043static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4044 Qualifiers VRQuals;
4045 const RecordType *TyRec;
4046 if (const MemberPointerType *RHSMPType =
4047 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004048 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004049 else
4050 TyRec = ArgExpr->getType()->getAs<RecordType>();
4051 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004052 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004053 VRQuals.addVolatile();
4054 VRQuals.addRestrict();
4055 return VRQuals;
4056 }
4057
4058 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00004059 if (!ClassDecl->hasDefinition())
4060 return VRQuals;
4061
John McCalleec51cf2010-01-20 00:46:10 +00004062 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00004063 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004064
John McCalleec51cf2010-01-20 00:46:10 +00004065 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004066 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00004067 NamedDecl *D = I.getDecl();
4068 if (isa<UsingShadowDecl>(D))
4069 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4070 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004071 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4072 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4073 CanTy = ResTypeRef->getPointeeType();
4074 // Need to go down the pointer/mempointer chain and add qualifiers
4075 // as see them.
4076 bool done = false;
4077 while (!done) {
4078 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4079 CanTy = ResTypePtr->getPointeeType();
4080 else if (const MemberPointerType *ResTypeMPtr =
4081 CanTy->getAs<MemberPointerType>())
4082 CanTy = ResTypeMPtr->getPointeeType();
4083 else
4084 done = true;
4085 if (CanTy.isVolatileQualified())
4086 VRQuals.addVolatile();
4087 if (CanTy.isRestrictQualified())
4088 VRQuals.addRestrict();
4089 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4090 return VRQuals;
4091 }
4092 }
4093 }
4094 return VRQuals;
4095}
4096
Douglas Gregor74253732008-11-19 15:42:04 +00004097/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4098/// operator overloads to the candidate set (C++ [over.built]), based
4099/// on the operator @p Op and the arguments given. For example, if the
4100/// operator is a binary '+', this routine might add "int
4101/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004102void
Mike Stump1eb44332009-09-09 15:08:12 +00004103Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004104 SourceLocation OpLoc,
Douglas Gregor74253732008-11-19 15:42:04 +00004105 Expr **Args, unsigned NumArgs,
4106 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004107 // The set of "promoted arithmetic types", which are the arithmetic
4108 // types are that preserved by promotion (C++ [over.built]p2). Note
4109 // that the first few of these types are the promoted integral
4110 // types; these types need to be first.
4111 // FIXME: What about complex?
4112 const unsigned FirstIntegralType = 0;
4113 const unsigned LastIntegralType = 13;
Mike Stump1eb44332009-09-09 15:08:12 +00004114 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004115 LastPromotedIntegralType = 13;
4116 const unsigned FirstPromotedArithmeticType = 7,
4117 LastPromotedArithmeticType = 16;
4118 const unsigned NumArithmeticTypes = 16;
4119 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump1eb44332009-09-09 15:08:12 +00004120 Context.BoolTy, Context.CharTy, Context.WCharTy,
4121// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004122 Context.SignedCharTy, Context.ShortTy,
4123 Context.UnsignedCharTy, Context.UnsignedShortTy,
4124 Context.IntTy, Context.LongTy, Context.LongLongTy,
4125 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
4126 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
4127 };
Douglas Gregor652371a2009-10-21 22:01:30 +00004128 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
4129 "Invalid first promoted integral type");
4130 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4131 == Context.UnsignedLongLongTy &&
4132 "Invalid last promoted integral type");
4133 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
4134 "Invalid first promoted arithmetic type");
4135 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4136 == Context.LongDoubleTy &&
4137 "Invalid last promoted arithmetic type");
4138
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004139 // Find all of the types that the arguments can convert to, but only
4140 // if the operator we're looking at has built-in operator candidates
4141 // that make use of these types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004142 Qualifiers VisibleTypeConversionsQuals;
4143 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004144 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4145 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4146
Douglas Gregor5842ba92009-08-24 15:23:48 +00004147 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004148 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4149 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4150 OpLoc,
4151 true,
4152 (Op == OO_Exclaim ||
4153 Op == OO_AmpAmp ||
4154 Op == OO_PipePipe),
4155 VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004156
4157 bool isComparison = false;
4158 switch (Op) {
4159 case OO_None:
4160 case NUM_OVERLOADED_OPERATORS:
4161 assert(false && "Expected an overloaded operator");
4162 break;
4163
Douglas Gregor74253732008-11-19 15:42:04 +00004164 case OO_Star: // '*' is either unary or binary
Mike Stump1eb44332009-09-09 15:08:12 +00004165 if (NumArgs == 1)
Douglas Gregor74253732008-11-19 15:42:04 +00004166 goto UnaryStar;
4167 else
4168 goto BinaryStar;
4169 break;
4170
4171 case OO_Plus: // '+' is either unary or binary
4172 if (NumArgs == 1)
4173 goto UnaryPlus;
4174 else
4175 goto BinaryPlus;
4176 break;
4177
4178 case OO_Minus: // '-' is either unary or binary
4179 if (NumArgs == 1)
4180 goto UnaryMinus;
4181 else
4182 goto BinaryMinus;
4183 break;
4184
4185 case OO_Amp: // '&' is either unary or binary
4186 if (NumArgs == 1)
4187 goto UnaryAmp;
4188 else
4189 goto BinaryAmp;
4190
4191 case OO_PlusPlus:
4192 case OO_MinusMinus:
4193 // C++ [over.built]p3:
4194 //
4195 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4196 // is either volatile or empty, there exist candidate operator
4197 // functions of the form
4198 //
4199 // VQ T& operator++(VQ T&);
4200 // T operator++(VQ T&, int);
4201 //
4202 // C++ [over.built]p4:
4203 //
4204 // For every pair (T, VQ), where T is an arithmetic type other
4205 // than bool, and VQ is either volatile or empty, there exist
4206 // candidate operator functions of the form
4207 //
4208 // VQ T& operator--(VQ T&);
4209 // T operator--(VQ T&, int);
Mike Stump1eb44332009-09-09 15:08:12 +00004210 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor74253732008-11-19 15:42:04 +00004211 Arith < NumArithmeticTypes; ++Arith) {
4212 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump1eb44332009-09-09 15:08:12 +00004213 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004214 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00004215
4216 // Non-volatile version.
4217 if (NumArgs == 1)
4218 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4219 else
4220 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004221 // heuristic to reduce number of builtin candidates in the set.
4222 // Add volatile version only if there are conversions to a volatile type.
4223 if (VisibleTypeConversionsQuals.hasVolatile()) {
4224 // Volatile version
4225 ParamTypes[0]
4226 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4227 if (NumArgs == 1)
4228 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4229 else
4230 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4231 }
Douglas Gregor74253732008-11-19 15:42:04 +00004232 }
4233
4234 // C++ [over.built]p5:
4235 //
4236 // For every pair (T, VQ), where T is a cv-qualified or
4237 // cv-unqualified object type, and VQ is either volatile or
4238 // empty, there exist candidate operator functions of the form
4239 //
4240 // T*VQ& operator++(T*VQ&);
4241 // T*VQ& operator--(T*VQ&);
4242 // T* operator++(T*VQ&, int);
4243 // T* operator--(T*VQ&, int);
4244 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4245 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4246 // Skip pointer types that aren't pointers to object types.
Ted Kremenek6217b802009-07-29 21:53:49 +00004247 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00004248 continue;
4249
Mike Stump1eb44332009-09-09 15:08:12 +00004250 QualType ParamTypes[2] = {
4251 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00004252 };
Mike Stump1eb44332009-09-09 15:08:12 +00004253
Douglas Gregor74253732008-11-19 15:42:04 +00004254 // Without volatile
4255 if (NumArgs == 1)
4256 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4257 else
4258 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4259
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004260 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4261 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00004262 // With volatile
John McCall0953e762009-09-24 19:53:00 +00004263 ParamTypes[0]
4264 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor74253732008-11-19 15:42:04 +00004265 if (NumArgs == 1)
4266 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4267 else
4268 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4269 }
4270 }
4271 break;
4272
4273 UnaryStar:
4274 // C++ [over.built]p6:
4275 // For every cv-qualified or cv-unqualified object type T, there
4276 // exist candidate operator functions of the form
4277 //
4278 // T& operator*(T*);
4279 //
4280 // C++ [over.built]p7:
4281 // For every function type T, there exist candidate operator
4282 // functions of the form
4283 // T& operator*(T*);
4284 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4285 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4286 QualType ParamTy = *Ptr;
Ted Kremenek6217b802009-07-29 21:53:49 +00004287 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004288 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00004289 &ParamTy, Args, 1, CandidateSet);
4290 }
4291 break;
4292
4293 UnaryPlus:
4294 // C++ [over.built]p8:
4295 // For every type T, there exist candidate operator functions of
4296 // the form
4297 //
4298 // T* operator+(T*);
4299 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4300 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4301 QualType ParamTy = *Ptr;
4302 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4303 }
Mike Stump1eb44332009-09-09 15:08:12 +00004304
Douglas Gregor74253732008-11-19 15:42:04 +00004305 // Fall through
4306
4307 UnaryMinus:
4308 // C++ [over.built]p9:
4309 // For every promoted arithmetic type T, there exist candidate
4310 // operator functions of the form
4311 //
4312 // T operator+(T);
4313 // T operator-(T);
Mike Stump1eb44332009-09-09 15:08:12 +00004314 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor74253732008-11-19 15:42:04 +00004315 Arith < LastPromotedArithmeticType; ++Arith) {
4316 QualType ArithTy = ArithmeticTypes[Arith];
4317 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4318 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004319
4320 // Extension: We also add these operators for vector types.
4321 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4322 VecEnd = CandidateTypes.vector_end();
4323 Vec != VecEnd; ++Vec) {
4324 QualType VecTy = *Vec;
4325 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4326 }
Douglas Gregor74253732008-11-19 15:42:04 +00004327 break;
4328
4329 case OO_Tilde:
4330 // C++ [over.built]p10:
4331 // For every promoted integral type T, there exist candidate
4332 // operator functions of the form
4333 //
4334 // T operator~(T);
Mike Stump1eb44332009-09-09 15:08:12 +00004335 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor74253732008-11-19 15:42:04 +00004336 Int < LastPromotedIntegralType; ++Int) {
4337 QualType IntTy = ArithmeticTypes[Int];
4338 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4339 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004340
4341 // Extension: We also add this operator for vector types.
4342 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4343 VecEnd = CandidateTypes.vector_end();
4344 Vec != VecEnd; ++Vec) {
4345 QualType VecTy = *Vec;
4346 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4347 }
Douglas Gregor74253732008-11-19 15:42:04 +00004348 break;
4349
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004350 case OO_New:
4351 case OO_Delete:
4352 case OO_Array_New:
4353 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004354 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00004355 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004356 break;
4357
4358 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00004359 UnaryAmp:
4360 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004361 // C++ [over.match.oper]p3:
4362 // -- For the operator ',', the unary operator '&', or the
4363 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004364 break;
4365
Douglas Gregor19b7b152009-08-24 13:43:27 +00004366 case OO_EqualEqual:
4367 case OO_ExclaimEqual:
4368 // C++ [over.match.oper]p16:
Mike Stump1eb44332009-09-09 15:08:12 +00004369 // For every pointer to member type T, there exist candidate operator
4370 // functions of the form
Douglas Gregor19b7b152009-08-24 13:43:27 +00004371 //
4372 // bool operator==(T,T);
4373 // bool operator!=(T,T);
Mike Stump1eb44332009-09-09 15:08:12 +00004374 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor19b7b152009-08-24 13:43:27 +00004375 MemPtr = CandidateTypes.member_pointer_begin(),
4376 MemPtrEnd = CandidateTypes.member_pointer_end();
4377 MemPtr != MemPtrEnd;
4378 ++MemPtr) {
4379 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4380 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4381 }
Mike Stump1eb44332009-09-09 15:08:12 +00004382
Douglas Gregor19b7b152009-08-24 13:43:27 +00004383 // Fall through
Mike Stump1eb44332009-09-09 15:08:12 +00004384
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004385 case OO_Less:
4386 case OO_Greater:
4387 case OO_LessEqual:
4388 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004389 // C++ [over.built]p15:
4390 //
4391 // For every pointer or enumeration type T, there exist
4392 // candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004393 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004394 // bool operator<(T, T);
4395 // bool operator>(T, T);
4396 // bool operator<=(T, T);
4397 // bool operator>=(T, T);
4398 // bool operator==(T, T);
4399 // bool operator!=(T, T);
4400 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4401 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4402 QualType ParamTypes[2] = { *Ptr, *Ptr };
4403 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4404 }
Mike Stump1eb44332009-09-09 15:08:12 +00004405 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004406 = CandidateTypes.enumeration_begin();
4407 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4408 QualType ParamTypes[2] = { *Enum, *Enum };
4409 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4410 }
4411
4412 // Fall through.
4413 isComparison = true;
4414
Douglas Gregor74253732008-11-19 15:42:04 +00004415 BinaryPlus:
4416 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004417 if (!isComparison) {
4418 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4419
4420 // C++ [over.built]p13:
4421 //
4422 // For every cv-qualified or cv-unqualified object type T
4423 // there exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004424 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004425 // T* operator+(T*, ptrdiff_t);
4426 // T& operator[](T*, ptrdiff_t); [BELOW]
4427 // T* operator-(T*, ptrdiff_t);
4428 // T* operator+(ptrdiff_t, T*);
4429 // T& operator[](ptrdiff_t, T*); [BELOW]
4430 //
4431 // C++ [over.built]p14:
4432 //
4433 // For every T, where T is a pointer to object type, there
4434 // exist candidate operator functions of the form
4435 //
4436 // ptrdiff_t operator-(T, T);
Mike Stump1eb44332009-09-09 15:08:12 +00004437 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004438 = CandidateTypes.pointer_begin();
4439 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4440 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4441
4442 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4443 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4444
4445 if (Op == OO_Plus) {
4446 // T* operator+(ptrdiff_t, T*);
4447 ParamTypes[0] = ParamTypes[1];
4448 ParamTypes[1] = *Ptr;
4449 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4450 } else {
4451 // ptrdiff_t operator-(T, T);
4452 ParamTypes[1] = *Ptr;
4453 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4454 Args, 2, CandidateSet);
4455 }
4456 }
4457 }
4458 // Fall through
4459
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004460 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00004461 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004462 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004463 // C++ [over.built]p12:
4464 //
4465 // For every pair of promoted arithmetic types L and R, there
4466 // exist candidate operator functions of the form
4467 //
4468 // LR operator*(L, R);
4469 // LR operator/(L, R);
4470 // LR operator+(L, R);
4471 // LR operator-(L, R);
4472 // bool operator<(L, R);
4473 // bool operator>(L, R);
4474 // bool operator<=(L, R);
4475 // bool operator>=(L, R);
4476 // bool operator==(L, R);
4477 // bool operator!=(L, R);
4478 //
4479 // where LR is the result of the usual arithmetic conversions
4480 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004481 //
4482 // C++ [over.built]p24:
4483 //
4484 // For every pair of promoted arithmetic types L and R, there exist
4485 // candidate operator functions of the form
4486 //
4487 // LR operator?(bool, L, R);
4488 //
4489 // where LR is the result of the usual arithmetic conversions
4490 // between types L and R.
4491 // Our candidates ignore the first parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00004492 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004493 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004494 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004495 Right < LastPromotedArithmeticType; ++Right) {
4496 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00004497 QualType Result
4498 = isComparison
4499 ? Context.BoolTy
4500 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004501 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4502 }
4503 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004504
4505 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
4506 // conditional operator for vector types.
4507 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4508 Vec1End = CandidateTypes.vector_end();
4509 Vec1 != Vec1End; ++Vec1)
4510 for (BuiltinCandidateTypeSet::iterator
4511 Vec2 = CandidateTypes.vector_begin(),
4512 Vec2End = CandidateTypes.vector_end();
4513 Vec2 != Vec2End; ++Vec2) {
4514 QualType LandR[2] = { *Vec1, *Vec2 };
4515 QualType Result;
4516 if (isComparison)
4517 Result = Context.BoolTy;
4518 else {
4519 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
4520 Result = *Vec1;
4521 else
4522 Result = *Vec2;
4523 }
4524
4525 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4526 }
4527
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004528 break;
4529
4530 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00004531 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004532 case OO_Caret:
4533 case OO_Pipe:
4534 case OO_LessLess:
4535 case OO_GreaterGreater:
4536 // C++ [over.built]p17:
4537 //
4538 // For every pair of promoted integral types L and R, there
4539 // exist candidate operator functions of the form
4540 //
4541 // LR operator%(L, R);
4542 // LR operator&(L, R);
4543 // LR operator^(L, R);
4544 // LR operator|(L, R);
4545 // L operator<<(L, R);
4546 // L operator>>(L, R);
4547 //
4548 // where LR is the result of the usual arithmetic conversions
4549 // between types L and R.
Mike Stump1eb44332009-09-09 15:08:12 +00004550 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004551 Left < LastPromotedIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004552 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004553 Right < LastPromotedIntegralType; ++Right) {
4554 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4555 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4556 ? LandR[0]
Eli Friedmana95d7572009-08-19 07:44:53 +00004557 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004558 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4559 }
4560 }
4561 break;
4562
4563 case OO_Equal:
4564 // C++ [over.built]p20:
4565 //
4566 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00004567 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004568 // empty, there exist candidate operator functions of the form
4569 //
4570 // VQ T& operator=(VQ T&, T);
Douglas Gregor19b7b152009-08-24 13:43:27 +00004571 for (BuiltinCandidateTypeSet::iterator
4572 Enum = CandidateTypes.enumeration_begin(),
4573 EnumEnd = CandidateTypes.enumeration_end();
4574 Enum != EnumEnd; ++Enum)
Mike Stump1eb44332009-09-09 15:08:12 +00004575 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004576 CandidateSet);
4577 for (BuiltinCandidateTypeSet::iterator
4578 MemPtr = CandidateTypes.member_pointer_begin(),
4579 MemPtrEnd = CandidateTypes.member_pointer_end();
4580 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump1eb44332009-09-09 15:08:12 +00004581 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004582 CandidateSet);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004583
4584 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004585
4586 case OO_PlusEqual:
4587 case OO_MinusEqual:
4588 // C++ [over.built]p19:
4589 //
4590 // For every pair (T, VQ), where T is any type and VQ is either
4591 // volatile or empty, there exist candidate operator functions
4592 // of the form
4593 //
4594 // T*VQ& operator=(T*VQ&, T*);
4595 //
4596 // C++ [over.built]p21:
4597 //
4598 // For every pair (T, VQ), where T is a cv-qualified or
4599 // cv-unqualified object type and VQ is either volatile or
4600 // empty, there exist candidate operator functions of the form
4601 //
4602 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4603 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4604 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4605 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4606 QualType ParamTypes[2];
4607 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4608
4609 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004610 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004611 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4612 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004613
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004614 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4615 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00004616 // volatile version
John McCall0953e762009-09-24 19:53:00 +00004617 ParamTypes[0]
4618 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004619 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4620 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00004621 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004622 }
4623 // Fall through.
4624
4625 case OO_StarEqual:
4626 case OO_SlashEqual:
4627 // C++ [over.built]p18:
4628 //
4629 // For every triple (L, VQ, R), where L is an arithmetic type,
4630 // VQ is either volatile or empty, and R is a promoted
4631 // arithmetic type, there exist candidate operator functions of
4632 // the form
4633 //
4634 // VQ L& operator=(VQ L&, R);
4635 // VQ L& operator*=(VQ L&, R);
4636 // VQ L& operator/=(VQ L&, R);
4637 // VQ L& operator+=(VQ L&, R);
4638 // VQ L& operator-=(VQ L&, R);
4639 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004640 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004641 Right < LastPromotedArithmeticType; ++Right) {
4642 QualType ParamTypes[2];
4643 ParamTypes[1] = ArithmeticTypes[Right];
4644
4645 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004646 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004647 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4648 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004649
4650 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004651 if (VisibleTypeConversionsQuals.hasVolatile()) {
4652 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4653 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4654 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4655 /*IsAssigmentOperator=*/Op == OO_Equal);
4656 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004657 }
4658 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004659
4660 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
4661 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4662 Vec1End = CandidateTypes.vector_end();
4663 Vec1 != Vec1End; ++Vec1)
4664 for (BuiltinCandidateTypeSet::iterator
4665 Vec2 = CandidateTypes.vector_begin(),
4666 Vec2End = CandidateTypes.vector_end();
4667 Vec2 != Vec2End; ++Vec2) {
4668 QualType ParamTypes[2];
4669 ParamTypes[1] = *Vec2;
4670 // Add this built-in operator as a candidate (VQ is empty).
4671 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
4672 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4673 /*IsAssigmentOperator=*/Op == OO_Equal);
4674
4675 // Add this built-in operator as a candidate (VQ is 'volatile').
4676 if (VisibleTypeConversionsQuals.hasVolatile()) {
4677 ParamTypes[0] = Context.getVolatileType(*Vec1);
4678 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4679 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4680 /*IsAssigmentOperator=*/Op == OO_Equal);
4681 }
4682 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004683 break;
4684
4685 case OO_PercentEqual:
4686 case OO_LessLessEqual:
4687 case OO_GreaterGreaterEqual:
4688 case OO_AmpEqual:
4689 case OO_CaretEqual:
4690 case OO_PipeEqual:
4691 // C++ [over.built]p22:
4692 //
4693 // For every triple (L, VQ, R), where L is an integral type, VQ
4694 // is either volatile or empty, and R is a promoted integral
4695 // type, there exist candidate operator functions of the form
4696 //
4697 // VQ L& operator%=(VQ L&, R);
4698 // VQ L& operator<<=(VQ L&, R);
4699 // VQ L& operator>>=(VQ L&, R);
4700 // VQ L& operator&=(VQ L&, R);
4701 // VQ L& operator^=(VQ L&, R);
4702 // VQ L& operator|=(VQ L&, R);
4703 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004704 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004705 Right < LastPromotedIntegralType; ++Right) {
4706 QualType ParamTypes[2];
4707 ParamTypes[1] = ArithmeticTypes[Right];
4708
4709 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004710 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004711 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian035c46f2009-10-20 00:04:40 +00004712 if (VisibleTypeConversionsQuals.hasVolatile()) {
4713 // Add this built-in operator as a candidate (VQ is 'volatile').
4714 ParamTypes[0] = ArithmeticTypes[Left];
4715 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4716 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4717 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4718 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004719 }
4720 }
4721 break;
4722
Douglas Gregor74253732008-11-19 15:42:04 +00004723 case OO_Exclaim: {
4724 // C++ [over.operator]p23:
4725 //
4726 // There also exist candidate operator functions of the form
4727 //
Mike Stump1eb44332009-09-09 15:08:12 +00004728 // bool operator!(bool);
Douglas Gregor74253732008-11-19 15:42:04 +00004729 // bool operator&&(bool, bool); [BELOW]
4730 // bool operator||(bool, bool); [BELOW]
4731 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004732 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4733 /*IsAssignmentOperator=*/false,
4734 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00004735 break;
4736 }
4737
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004738 case OO_AmpAmp:
4739 case OO_PipePipe: {
4740 // C++ [over.operator]p23:
4741 //
4742 // There also exist candidate operator functions of the form
4743 //
Douglas Gregor74253732008-11-19 15:42:04 +00004744 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004745 // bool operator&&(bool, bool);
4746 // bool operator||(bool, bool);
4747 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004748 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4749 /*IsAssignmentOperator=*/false,
4750 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004751 break;
4752 }
4753
4754 case OO_Subscript:
4755 // C++ [over.built]p13:
4756 //
4757 // For every cv-qualified or cv-unqualified object type T there
4758 // exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004759 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004760 // T* operator+(T*, ptrdiff_t); [ABOVE]
4761 // T& operator[](T*, ptrdiff_t);
4762 // T* operator-(T*, ptrdiff_t); [ABOVE]
4763 // T* operator+(ptrdiff_t, T*); [ABOVE]
4764 // T& operator[](ptrdiff_t, T*);
4765 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4766 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4767 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenek6217b802009-07-29 21:53:49 +00004768 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004769 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004770
4771 // T& operator[](T*, ptrdiff_t)
4772 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4773
4774 // T& operator[](ptrdiff_t, T*);
4775 ParamTypes[0] = ParamTypes[1];
4776 ParamTypes[1] = *Ptr;
4777 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004778 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004779 break;
4780
4781 case OO_ArrowStar:
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004782 // C++ [over.built]p11:
4783 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4784 // C1 is the same type as C2 or is a derived class of C2, T is an object
4785 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4786 // there exist candidate operator functions of the form
4787 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4788 // where CV12 is the union of CV1 and CV2.
4789 {
4790 for (BuiltinCandidateTypeSet::iterator Ptr =
4791 CandidateTypes.pointer_begin();
4792 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4793 QualType C1Ty = (*Ptr);
4794 QualType C1;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004795 QualifierCollector Q1;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004796 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004797 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004798 if (!isa<RecordType>(C1))
4799 continue;
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004800 // heuristic to reduce number of builtin candidates in the set.
4801 // Add volatile/restrict version only if there are conversions to a
4802 // volatile/restrict type.
4803 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4804 continue;
4805 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4806 continue;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004807 }
4808 for (BuiltinCandidateTypeSet::iterator
4809 MemPtr = CandidateTypes.member_pointer_begin(),
4810 MemPtrEnd = CandidateTypes.member_pointer_end();
4811 MemPtr != MemPtrEnd; ++MemPtr) {
4812 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4813 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian43036972009-10-07 16:56:50 +00004814 C2 = C2.getUnqualifiedType();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004815 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4816 break;
4817 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4818 // build CV12 T&
4819 QualType T = mptr->getPointeeType();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004820 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4821 T.isVolatileQualified())
4822 continue;
4823 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4824 T.isRestrictQualified())
4825 continue;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004826 T = Q1.apply(T);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004827 QualType ResultTy = Context.getLValueReferenceType(T);
4828 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4829 }
4830 }
4831 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004832 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004833
4834 case OO_Conditional:
4835 // Note that we don't consider the first argument, since it has been
4836 // contextually converted to bool long ago. The candidates below are
4837 // therefore added as binary.
4838 //
4839 // C++ [over.built]p24:
4840 // For every type T, where T is a pointer or pointer-to-member type,
4841 // there exist candidate operator functions of the form
4842 //
4843 // T operator?(bool, T, T);
4844 //
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004845 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4846 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4847 QualType ParamTypes[2] = { *Ptr, *Ptr };
4848 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4849 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00004850 for (BuiltinCandidateTypeSet::iterator Ptr =
4851 CandidateTypes.member_pointer_begin(),
4852 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4853 QualType ParamTypes[2] = { *Ptr, *Ptr };
4854 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4855 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004856 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004857 }
4858}
4859
Douglas Gregorfa047642009-02-04 00:32:51 +00004860/// \brief Add function candidates found via argument-dependent lookup
4861/// to the set of overloading candidates.
4862///
4863/// This routine performs argument-dependent name lookup based on the
4864/// given function name (which may also be an operator name) and adds
4865/// all of the overload candidates found by ADL to the overload
4866/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00004867void
Douglas Gregorfa047642009-02-04 00:32:51 +00004868Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00004869 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00004870 Expr **Args, unsigned NumArgs,
John McCalld5532b62009-11-23 01:53:49 +00004871 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004872 OverloadCandidateSet& CandidateSet,
4873 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00004874 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00004875
John McCalla113e722010-01-26 06:04:06 +00004876 // FIXME: This approach for uniquing ADL results (and removing
4877 // redundant candidates from the set) relies on pointer-equality,
4878 // which means we need to key off the canonical decl. However,
4879 // always going back to the canonical decl might not get us the
4880 // right set of default arguments. What default arguments are
4881 // we supposed to consider on ADL candidates, anyway?
4882
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004883 // FIXME: Pass in the explicit template arguments?
John McCall7edb5fd2010-01-26 07:16:45 +00004884 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00004885
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004886 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004887 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4888 CandEnd = CandidateSet.end();
4889 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00004890 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00004891 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00004892 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00004893 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00004894 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004895
4896 // For each of the ADL candidates we found, add it to the overload
4897 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00004898 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00004899 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00004900 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00004901 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004902 continue;
4903
John McCall9aa472c2010-03-19 07:35:19 +00004904 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00004905 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004906 } else
John McCall6e266892010-01-26 03:27:55 +00004907 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00004908 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004909 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00004910 }
Douglas Gregorfa047642009-02-04 00:32:51 +00004911}
4912
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004913/// isBetterOverloadCandidate - Determines whether the first overload
4914/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00004915bool
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004916Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCall5769d612010-02-08 23:07:23 +00004917 const OverloadCandidate& Cand2,
4918 SourceLocation Loc) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004919 // Define viable functions to be better candidates than non-viable
4920 // functions.
4921 if (!Cand2.Viable)
4922 return Cand1.Viable;
4923 else if (!Cand1.Viable)
4924 return false;
4925
Douglas Gregor88a35142008-12-22 05:46:06 +00004926 // C++ [over.match.best]p1:
4927 //
4928 // -- if F is a static member function, ICS1(F) is defined such
4929 // that ICS1(F) is neither better nor worse than ICS1(G) for
4930 // any function G, and, symmetrically, ICS1(G) is neither
4931 // better nor worse than ICS1(F).
4932 unsigned StartArg = 0;
4933 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4934 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004935
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004936 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00004937 // A viable function F1 is defined to be a better function than another
4938 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004939 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004940 unsigned NumArgs = Cand1.Conversions.size();
4941 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4942 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004943 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004944 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4945 Cand2.Conversions[ArgIdx])) {
4946 case ImplicitConversionSequence::Better:
4947 // Cand1 has a better conversion sequence.
4948 HasBetterConversion = true;
4949 break;
4950
4951 case ImplicitConversionSequence::Worse:
4952 // Cand1 can't be better than Cand2.
4953 return false;
4954
4955 case ImplicitConversionSequence::Indistinguishable:
4956 // Do nothing.
4957 break;
4958 }
4959 }
4960
Mike Stump1eb44332009-09-09 15:08:12 +00004961 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004962 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004963 if (HasBetterConversion)
4964 return true;
4965
Mike Stump1eb44332009-09-09 15:08:12 +00004966 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004967 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00004968 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004969 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4970 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004971
4972 // -- F1 and F2 are function template specializations, and the function
4973 // template for F1 is more specialized than the template for F2
4974 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004975 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00004976 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4977 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004978 if (FunctionTemplateDecl *BetterTemplate
4979 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4980 Cand2.Function->getPrimaryTemplate(),
John McCall5769d612010-02-08 23:07:23 +00004981 Loc,
Douglas Gregor5d7d3752009-09-14 23:02:14 +00004982 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4983 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004984 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004985
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004986 // -- the context is an initialization by user-defined conversion
4987 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4988 // from the return type of F1 to the destination type (i.e.,
4989 // the type of the entity being initialized) is a better
4990 // conversion sequence than the standard conversion sequence
4991 // from the return type of F2 to the destination type.
Mike Stump1eb44332009-09-09 15:08:12 +00004992 if (Cand1.Function && Cand2.Function &&
4993 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004994 isa<CXXConversionDecl>(Cand2.Function)) {
4995 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4996 Cand2.FinalConversion)) {
4997 case ImplicitConversionSequence::Better:
4998 // Cand1 has a better conversion sequence.
4999 return true;
5000
5001 case ImplicitConversionSequence::Worse:
5002 // Cand1 can't be better than Cand2.
5003 return false;
5004
5005 case ImplicitConversionSequence::Indistinguishable:
5006 // Do nothing
5007 break;
5008 }
5009 }
5010
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005011 return false;
5012}
5013
Mike Stump1eb44332009-09-09 15:08:12 +00005014/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00005015/// within an overload candidate set.
5016///
5017/// \param CandidateSet the set of candidate functions.
5018///
5019/// \param Loc the location of the function name (or operator symbol) for
5020/// which overload resolution occurs.
5021///
Mike Stump1eb44332009-09-09 15:08:12 +00005022/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00005023/// function, Best points to the candidate function found.
5024///
5025/// \returns The result of overload resolution.
Douglas Gregor20093b42009-12-09 23:02:17 +00005026OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
5027 SourceLocation Loc,
5028 OverloadCandidateSet::iterator& Best) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005029 // Find the best viable function.
5030 Best = CandidateSet.end();
5031 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5032 Cand != CandidateSet.end(); ++Cand) {
5033 if (Cand->Viable) {
John McCall5769d612010-02-08 23:07:23 +00005034 if (Best == CandidateSet.end() ||
5035 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005036 Best = Cand;
5037 }
5038 }
5039
5040 // If we didn't find any viable functions, abort.
5041 if (Best == CandidateSet.end())
5042 return OR_No_Viable_Function;
5043
5044 // Make sure that this function is better than every other viable
5045 // function. If not, we have an ambiguity.
5046 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5047 Cand != CandidateSet.end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00005048 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005049 Cand != Best &&
John McCall5769d612010-02-08 23:07:23 +00005050 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005051 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005052 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005053 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005054 }
Mike Stump1eb44332009-09-09 15:08:12 +00005055
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005056 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005057 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00005058 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005059 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005060 return OR_Deleted;
5061
Douglas Gregore0762c92009-06-19 23:52:42 +00005062 // C++ [basic.def.odr]p2:
5063 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00005064 // when referred to from a potentially-evaluated expression. [Note: this
5065 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00005066 // (clause 13), user-defined conversions (12.3.2), allocation function for
5067 // placement new (5.3.4), as well as non-default initialization (8.5).
5068 if (Best->Function)
5069 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005070 return OR_Success;
5071}
5072
John McCall3c80f572010-01-12 02:15:36 +00005073namespace {
5074
5075enum OverloadCandidateKind {
5076 oc_function,
5077 oc_method,
5078 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00005079 oc_function_template,
5080 oc_method_template,
5081 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00005082 oc_implicit_default_constructor,
5083 oc_implicit_copy_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00005084 oc_implicit_copy_assignment
John McCall3c80f572010-01-12 02:15:36 +00005085};
5086
John McCall220ccbf2010-01-13 00:25:19 +00005087OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5088 FunctionDecl *Fn,
5089 std::string &Description) {
5090 bool isTemplate = false;
5091
5092 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5093 isTemplate = true;
5094 Description = S.getTemplateArgumentBindingsText(
5095 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5096 }
John McCallb1622a12010-01-06 09:43:14 +00005097
5098 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00005099 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00005100 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00005101
John McCall3c80f572010-01-12 02:15:36 +00005102 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5103 : oc_implicit_default_constructor;
John McCallb1622a12010-01-06 09:43:14 +00005104 }
5105
5106 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5107 // This actually gets spelled 'candidate function' for now, but
5108 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00005109 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00005110 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00005111
5112 assert(Meth->isCopyAssignment()
5113 && "implicit method is not copy assignment operator?");
John McCall3c80f572010-01-12 02:15:36 +00005114 return oc_implicit_copy_assignment;
5115 }
5116
John McCall220ccbf2010-01-13 00:25:19 +00005117 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00005118}
5119
5120} // end anonymous namespace
5121
5122// Notes the location of an overload candidate.
5123void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCall220ccbf2010-01-13 00:25:19 +00005124 std::string FnDesc;
5125 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5126 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5127 << (unsigned) K << FnDesc;
John McCallb1622a12010-01-06 09:43:14 +00005128}
5129
John McCall1d318332010-01-12 00:44:57 +00005130/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5131/// "lead" diagnostic; it will be given two arguments, the source and
5132/// target types of the conversion.
5133void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
5134 SourceLocation CaretLoc,
5135 const PartialDiagnostic &PDiag) {
5136 Diag(CaretLoc, PDiag)
5137 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
5138 for (AmbiguousConversionSequence::const_iterator
5139 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
5140 NoteOverloadCandidate(*I);
5141 }
John McCall81201622010-01-08 04:41:39 +00005142}
5143
John McCall1d318332010-01-12 00:44:57 +00005144namespace {
5145
John McCalladbb8f82010-01-13 09:16:55 +00005146void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5147 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5148 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00005149 assert(Cand->Function && "for now, candidate must be a function");
5150 FunctionDecl *Fn = Cand->Function;
5151
5152 // There's a conversion slot for the object argument if this is a
5153 // non-constructor method. Note that 'I' corresponds the
5154 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00005155 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00005156 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00005157 if (I == 0)
5158 isObjectArgument = true;
5159 else
5160 I--;
John McCall220ccbf2010-01-13 00:25:19 +00005161 }
5162
John McCall220ccbf2010-01-13 00:25:19 +00005163 std::string FnDesc;
5164 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5165
John McCalladbb8f82010-01-13 09:16:55 +00005166 Expr *FromExpr = Conv.Bad.FromExpr;
5167 QualType FromTy = Conv.Bad.getFromType();
5168 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00005169
John McCall5920dbb2010-02-02 02:42:52 +00005170 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00005171 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00005172 Expr *E = FromExpr->IgnoreParens();
5173 if (isa<UnaryOperator>(E))
5174 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00005175 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00005176
5177 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5178 << (unsigned) FnKind << FnDesc
5179 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5180 << ToTy << Name << I+1;
5181 return;
5182 }
5183
John McCall258b2032010-01-23 08:10:49 +00005184 // Do some hand-waving analysis to see if the non-viability is due
5185 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00005186 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5187 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5188 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5189 CToTy = RT->getPointeeType();
5190 else {
5191 // TODO: detect and diagnose the full richness of const mismatches.
5192 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5193 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5194 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5195 }
5196
5197 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5198 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5199 // It is dumb that we have to do this here.
5200 while (isa<ArrayType>(CFromTy))
5201 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5202 while (isa<ArrayType>(CToTy))
5203 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5204
5205 Qualifiers FromQs = CFromTy.getQualifiers();
5206 Qualifiers ToQs = CToTy.getQualifiers();
5207
5208 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5209 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5210 << (unsigned) FnKind << FnDesc
5211 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5212 << FromTy
5213 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5214 << (unsigned) isObjectArgument << I+1;
5215 return;
5216 }
5217
5218 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5219 assert(CVR && "unexpected qualifiers mismatch");
5220
5221 if (isObjectArgument) {
5222 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5223 << (unsigned) FnKind << FnDesc
5224 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5225 << FromTy << (CVR - 1);
5226 } else {
5227 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5228 << (unsigned) FnKind << FnDesc
5229 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5230 << FromTy << (CVR - 1) << I+1;
5231 }
5232 return;
5233 }
5234
John McCall258b2032010-01-23 08:10:49 +00005235 // Diagnose references or pointers to incomplete types differently,
5236 // since it's far from impossible that the incompleteness triggered
5237 // the failure.
5238 QualType TempFromTy = FromTy.getNonReferenceType();
5239 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5240 TempFromTy = PTy->getPointeeType();
5241 if (TempFromTy->isIncompleteType()) {
5242 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5243 << (unsigned) FnKind << FnDesc
5244 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5245 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5246 return;
5247 }
5248
John McCall651f3ee2010-01-14 03:28:57 +00005249 // TODO: specialize more based on the kind of mismatch
John McCall220ccbf2010-01-13 00:25:19 +00005250 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5251 << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00005252 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalle81e15e2010-01-14 00:56:20 +00005253 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCalladbb8f82010-01-13 09:16:55 +00005254}
5255
5256void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5257 unsigned NumFormalArgs) {
5258 // TODO: treat calls to a missing default constructor as a special case
5259
5260 FunctionDecl *Fn = Cand->Function;
5261 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5262
5263 unsigned MinParams = Fn->getMinRequiredArguments();
5264
5265 // at least / at most / exactly
Douglas Gregora18592e2010-05-08 18:13:28 +00005266 // FIXME: variadic templates "at most" should account for parameter packs
John McCalladbb8f82010-01-13 09:16:55 +00005267 unsigned mode, modeCount;
5268 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00005269 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5270 (Cand->FailureKind == ovl_fail_bad_deduction &&
5271 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCalladbb8f82010-01-13 09:16:55 +00005272 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5273 mode = 0; // "at least"
5274 else
5275 mode = 2; // "exactly"
5276 modeCount = MinParams;
5277 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00005278 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5279 (Cand->FailureKind == ovl_fail_bad_deduction &&
5280 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00005281 if (MinParams != FnTy->getNumArgs())
5282 mode = 1; // "at most"
5283 else
5284 mode = 2; // "exactly"
5285 modeCount = FnTy->getNumArgs();
5286 }
5287
5288 std::string Description;
5289 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5290
5291 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregora18592e2010-05-08 18:13:28 +00005292 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5293 << modeCount << NumFormalArgs;
John McCall220ccbf2010-01-13 00:25:19 +00005294}
5295
John McCall342fec42010-02-01 18:53:26 +00005296/// Diagnose a failed template-argument deduction.
5297void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5298 Expr **Args, unsigned NumArgs) {
5299 FunctionDecl *Fn = Cand->Function; // pattern
5300
Douglas Gregora9333192010-05-08 17:41:32 +00005301 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00005302 NamedDecl *ParamD;
5303 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5304 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5305 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00005306 switch (Cand->DeductionFailure.Result) {
5307 case Sema::TDK_Success:
5308 llvm_unreachable("TDK_success while diagnosing bad deduction");
5309
5310 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00005311 assert(ParamD && "no parameter found for incomplete deduction result");
5312 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5313 << ParamD->getDeclName();
5314 return;
5315 }
5316
Douglas Gregora9333192010-05-08 17:41:32 +00005317 case Sema::TDK_Inconsistent:
5318 case Sema::TDK_InconsistentQuals: {
Douglas Gregorf1a84452010-05-08 19:15:54 +00005319 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00005320 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00005321 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00005322 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00005323 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00005324 which = 1;
5325 else {
Douglas Gregora9333192010-05-08 17:41:32 +00005326 which = 2;
5327 }
5328
5329 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5330 << which << ParamD->getDeclName()
5331 << *Cand->DeductionFailure.getFirstArg()
5332 << *Cand->DeductionFailure.getSecondArg();
5333 return;
5334 }
Douglas Gregora18592e2010-05-08 18:13:28 +00005335
Douglas Gregorf1a84452010-05-08 19:15:54 +00005336 case Sema::TDK_InvalidExplicitArguments:
5337 assert(ParamD && "no parameter found for invalid explicit arguments");
5338 if (ParamD->getDeclName())
5339 S.Diag(Fn->getLocation(),
5340 diag::note_ovl_candidate_explicit_arg_mismatch_named)
5341 << ParamD->getDeclName();
5342 else {
5343 int index = 0;
5344 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5345 index = TTP->getIndex();
5346 else if (NonTypeTemplateParmDecl *NTTP
5347 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5348 index = NTTP->getIndex();
5349 else
5350 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
5351 S.Diag(Fn->getLocation(),
5352 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
5353 << (index + 1);
5354 }
5355 return;
5356
Douglas Gregora18592e2010-05-08 18:13:28 +00005357 case Sema::TDK_TooManyArguments:
5358 case Sema::TDK_TooFewArguments:
5359 DiagnoseArityMismatch(S, Cand, NumArgs);
5360 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00005361
5362 case Sema::TDK_InstantiationDepth:
5363 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
5364 return;
5365
5366 case Sema::TDK_SubstitutionFailure: {
5367 std::string ArgString;
5368 if (TemplateArgumentList *Args
5369 = Cand->DeductionFailure.getTemplateArgumentList())
5370 ArgString = S.getTemplateArgumentBindingsText(
5371 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
5372 *Args);
5373 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
5374 << ArgString;
5375 return;
5376 }
Douglas Gregora9333192010-05-08 17:41:32 +00005377
John McCall342fec42010-02-01 18:53:26 +00005378 // TODO: diagnose these individually, then kill off
5379 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00005380 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00005381 case Sema::TDK_FailedOverloadResolution:
5382 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
5383 return;
5384 }
5385}
5386
5387/// Generates a 'note' diagnostic for an overload candidate. We've
5388/// already generated a primary error at the call site.
5389///
5390/// It really does need to be a single diagnostic with its caret
5391/// pointed at the candidate declaration. Yes, this creates some
5392/// major challenges of technical writing. Yes, this makes pointing
5393/// out problems with specific arguments quite awkward. It's still
5394/// better than generating twenty screens of text for every failed
5395/// overload.
5396///
5397/// It would be great to be able to express per-candidate problems
5398/// more richly for those diagnostic clients that cared, but we'd
5399/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00005400void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
5401 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00005402 FunctionDecl *Fn = Cand->Function;
5403
John McCall81201622010-01-08 04:41:39 +00005404 // Note deleted candidates, but only if they're viable.
John McCall3c80f572010-01-12 02:15:36 +00005405 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCall220ccbf2010-01-13 00:25:19 +00005406 std::string FnDesc;
5407 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00005408
5409 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00005410 << FnKind << FnDesc << Fn->isDeleted();
John McCalla1d7d622010-01-08 00:58:21 +00005411 return;
John McCall81201622010-01-08 04:41:39 +00005412 }
5413
John McCall220ccbf2010-01-13 00:25:19 +00005414 // We don't really have anything else to say about viable candidates.
5415 if (Cand->Viable) {
5416 S.NoteOverloadCandidate(Fn);
5417 return;
5418 }
John McCall1d318332010-01-12 00:44:57 +00005419
John McCalladbb8f82010-01-13 09:16:55 +00005420 switch (Cand->FailureKind) {
5421 case ovl_fail_too_many_arguments:
5422 case ovl_fail_too_few_arguments:
5423 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00005424
John McCalladbb8f82010-01-13 09:16:55 +00005425 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00005426 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5427
John McCall717e8912010-01-23 05:17:32 +00005428 case ovl_fail_trivial_conversion:
5429 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00005430 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00005431 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00005432
John McCallb1bdc622010-02-25 01:37:24 +00005433 case ovl_fail_bad_conversion: {
5434 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5435 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00005436 if (Cand->Conversions[I].isBad())
5437 return DiagnoseBadConversion(S, Cand, I);
5438
5439 // FIXME: this currently happens when we're called from SemaInit
5440 // when user-conversion overload fails. Figure out how to handle
5441 // those conditions and diagnose them well.
5442 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00005443 }
John McCallb1bdc622010-02-25 01:37:24 +00005444 }
John McCalla1d7d622010-01-08 00:58:21 +00005445}
5446
5447void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5448 // Desugar the type of the surrogate down to a function type,
5449 // retaining as many typedefs as possible while still showing
5450 // the function type (and, therefore, its parameter types).
5451 QualType FnType = Cand->Surrogate->getConversionType();
5452 bool isLValueReference = false;
5453 bool isRValueReference = false;
5454 bool isPointer = false;
5455 if (const LValueReferenceType *FnTypeRef =
5456 FnType->getAs<LValueReferenceType>()) {
5457 FnType = FnTypeRef->getPointeeType();
5458 isLValueReference = true;
5459 } else if (const RValueReferenceType *FnTypeRef =
5460 FnType->getAs<RValueReferenceType>()) {
5461 FnType = FnTypeRef->getPointeeType();
5462 isRValueReference = true;
5463 }
5464 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5465 FnType = FnTypePtr->getPointeeType();
5466 isPointer = true;
5467 }
5468 // Desugar down to a function type.
5469 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5470 // Reconstruct the pointer/reference as appropriate.
5471 if (isPointer) FnType = S.Context.getPointerType(FnType);
5472 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5473 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5474
5475 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5476 << FnType;
5477}
5478
5479void NoteBuiltinOperatorCandidate(Sema &S,
5480 const char *Opc,
5481 SourceLocation OpLoc,
5482 OverloadCandidate *Cand) {
5483 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5484 std::string TypeStr("operator");
5485 TypeStr += Opc;
5486 TypeStr += "(";
5487 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5488 if (Cand->Conversions.size() == 1) {
5489 TypeStr += ")";
5490 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5491 } else {
5492 TypeStr += ", ";
5493 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5494 TypeStr += ")";
5495 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5496 }
5497}
5498
5499void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5500 OverloadCandidate *Cand) {
5501 unsigned NoOperands = Cand->Conversions.size();
5502 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5503 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00005504 if (ICS.isBad()) break; // all meaningless after first invalid
5505 if (!ICS.isAmbiguous()) continue;
5506
5507 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005508 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00005509 }
5510}
5511
John McCall1b77e732010-01-15 23:32:50 +00005512SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5513 if (Cand->Function)
5514 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00005515 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00005516 return Cand->Surrogate->getLocation();
5517 return SourceLocation();
5518}
5519
John McCallbf65c0b2010-01-12 00:48:53 +00005520struct CompareOverloadCandidatesForDisplay {
5521 Sema &S;
5522 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00005523
5524 bool operator()(const OverloadCandidate *L,
5525 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00005526 // Fast-path this check.
5527 if (L == R) return false;
5528
John McCall81201622010-01-08 04:41:39 +00005529 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00005530 if (L->Viable) {
5531 if (!R->Viable) return true;
5532
5533 // TODO: introduce a tri-valued comparison for overload
5534 // candidates. Would be more worthwhile if we had a sort
5535 // that could exploit it.
John McCall5769d612010-02-08 23:07:23 +00005536 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5537 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00005538 } else if (R->Viable)
5539 return false;
John McCall81201622010-01-08 04:41:39 +00005540
John McCall1b77e732010-01-15 23:32:50 +00005541 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00005542
John McCall1b77e732010-01-15 23:32:50 +00005543 // Criteria by which we can sort non-viable candidates:
5544 if (!L->Viable) {
5545 // 1. Arity mismatches come after other candidates.
5546 if (L->FailureKind == ovl_fail_too_many_arguments ||
5547 L->FailureKind == ovl_fail_too_few_arguments)
5548 return false;
5549 if (R->FailureKind == ovl_fail_too_many_arguments ||
5550 R->FailureKind == ovl_fail_too_few_arguments)
5551 return true;
John McCall81201622010-01-08 04:41:39 +00005552
John McCall717e8912010-01-23 05:17:32 +00005553 // 2. Bad conversions come first and are ordered by the number
5554 // of bad conversions and quality of good conversions.
5555 if (L->FailureKind == ovl_fail_bad_conversion) {
5556 if (R->FailureKind != ovl_fail_bad_conversion)
5557 return true;
5558
5559 // If there's any ordering between the defined conversions...
5560 // FIXME: this might not be transitive.
5561 assert(L->Conversions.size() == R->Conversions.size());
5562
5563 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00005564 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5565 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall717e8912010-01-23 05:17:32 +00005566 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5567 R->Conversions[I])) {
5568 case ImplicitConversionSequence::Better:
5569 leftBetter++;
5570 break;
5571
5572 case ImplicitConversionSequence::Worse:
5573 leftBetter--;
5574 break;
5575
5576 case ImplicitConversionSequence::Indistinguishable:
5577 break;
5578 }
5579 }
5580 if (leftBetter > 0) return true;
5581 if (leftBetter < 0) return false;
5582
5583 } else if (R->FailureKind == ovl_fail_bad_conversion)
5584 return false;
5585
John McCall1b77e732010-01-15 23:32:50 +00005586 // TODO: others?
5587 }
5588
5589 // Sort everything else by location.
5590 SourceLocation LLoc = GetLocationForCandidate(L);
5591 SourceLocation RLoc = GetLocationForCandidate(R);
5592
5593 // Put candidates without locations (e.g. builtins) at the end.
5594 if (LLoc.isInvalid()) return false;
5595 if (RLoc.isInvalid()) return true;
5596
5597 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00005598 }
5599};
5600
John McCall717e8912010-01-23 05:17:32 +00005601/// CompleteNonViableCandidate - Normally, overload resolution only
5602/// computes up to the first
5603void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5604 Expr **Args, unsigned NumArgs) {
5605 assert(!Cand->Viable);
5606
5607 // Don't do anything on failures other than bad conversion.
5608 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5609
5610 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00005611 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCall717e8912010-01-23 05:17:32 +00005612 unsigned ConvCount = Cand->Conversions.size();
5613 while (true) {
5614 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5615 ConvIdx++;
5616 if (Cand->Conversions[ConvIdx - 1].isBad())
5617 break;
5618 }
5619
5620 if (ConvIdx == ConvCount)
5621 return;
5622
John McCallb1bdc622010-02-25 01:37:24 +00005623 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
5624 "remaining conversion is initialized?");
5625
Douglas Gregor23ef6c02010-04-16 17:45:54 +00005626 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00005627 // operation somehow.
5628 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00005629
5630 const FunctionProtoType* Proto;
5631 unsigned ArgIdx = ConvIdx;
5632
5633 if (Cand->IsSurrogate) {
5634 QualType ConvType
5635 = Cand->Surrogate->getConversionType().getNonReferenceType();
5636 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5637 ConvType = ConvPtrType->getPointeeType();
5638 Proto = ConvType->getAs<FunctionProtoType>();
5639 ArgIdx--;
5640 } else if (Cand->Function) {
5641 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
5642 if (isa<CXXMethodDecl>(Cand->Function) &&
5643 !isa<CXXConstructorDecl>(Cand->Function))
5644 ArgIdx--;
5645 } else {
5646 // Builtin binary operator with a bad first conversion.
5647 assert(ConvCount <= 3);
5648 for (; ConvIdx != ConvCount; ++ConvIdx)
5649 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005650 = TryCopyInitialization(S, Args[ConvIdx],
5651 Cand->BuiltinTypes.ParamTypes[ConvIdx],
5652 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00005653 /*InOverloadResolution*/ true);
John McCall717e8912010-01-23 05:17:32 +00005654 return;
5655 }
5656
5657 // Fill in the rest of the conversions.
5658 unsigned NumArgsInProto = Proto->getNumArgs();
5659 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
5660 if (ArgIdx < NumArgsInProto)
5661 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005662 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
5663 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00005664 /*InOverloadResolution=*/true);
John McCall717e8912010-01-23 05:17:32 +00005665 else
5666 Cand->Conversions[ConvIdx].setEllipsis();
5667 }
5668}
5669
John McCalla1d7d622010-01-08 00:58:21 +00005670} // end anonymous namespace
5671
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005672/// PrintOverloadCandidates - When overload resolution fails, prints
5673/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00005674/// set.
Mike Stump1eb44332009-09-09 15:08:12 +00005675void
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005676Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall81201622010-01-08 04:41:39 +00005677 OverloadCandidateDisplayKind OCD,
John McCallcbce6062010-01-12 07:18:19 +00005678 Expr **Args, unsigned NumArgs,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005679 const char *Opc,
Fariborz Jahanian16a5eac2009-10-09 00:13:15 +00005680 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00005681 // Sort the candidates by viability and position. Sorting directly would
5682 // be prohibitive, so we make a set of pointers and sort those.
5683 llvm::SmallVector<OverloadCandidate*, 32> Cands;
5684 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
5685 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5686 LastCand = CandidateSet.end();
John McCall717e8912010-01-23 05:17:32 +00005687 Cand != LastCand; ++Cand) {
5688 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00005689 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00005690 else if (OCD == OCD_AllCandidates) {
5691 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00005692 if (Cand->Function || Cand->IsSurrogate)
5693 Cands.push_back(Cand);
5694 // Otherwise, this a non-viable builtin candidate. We do not, in general,
5695 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00005696 }
5697 }
5698
John McCallbf65c0b2010-01-12 00:48:53 +00005699 std::sort(Cands.begin(), Cands.end(),
5700 CompareOverloadCandidatesForDisplay(*this));
John McCall81201622010-01-08 04:41:39 +00005701
John McCall1d318332010-01-12 00:44:57 +00005702 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00005703
John McCall81201622010-01-08 04:41:39 +00005704 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00005705 const Diagnostic::OverloadsShown ShowOverloads = Diags.getShowOverloads();
5706 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00005707 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
5708 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00005709
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00005710 // Set an arbitrary limit on the number of candidate functions we'll spam
5711 // the user with. FIXME: This limit should depend on details of the
5712 // candidate list.
5713 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
5714 break;
5715 }
5716 ++CandsShown;
5717
John McCalla1d7d622010-01-08 00:58:21 +00005718 if (Cand->Function)
John McCall220ccbf2010-01-13 00:25:19 +00005719 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00005720 else if (Cand->IsSurrogate)
5721 NoteSurrogateCandidate(*this, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00005722 else {
5723 assert(Cand->Viable &&
5724 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00005725 // Generally we only see ambiguities including viable builtin
5726 // operators if overload resolution got screwed up by an
5727 // ambiguous user-defined conversion.
5728 //
5729 // FIXME: It's quite possible for different conversions to see
5730 // different ambiguities, though.
5731 if (!ReportedAmbiguousConversions) {
5732 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
5733 ReportedAmbiguousConversions = true;
5734 }
John McCalla1d7d622010-01-08 00:58:21 +00005735
John McCall1d318332010-01-12 00:44:57 +00005736 // If this is a viable builtin, print it.
John McCalla1d7d622010-01-08 00:58:21 +00005737 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005738 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005739 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00005740
5741 if (I != E)
Jeffrey Yasskin258de302010-06-11 06:58:43 +00005742 Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005743}
5744
John McCall9aa472c2010-03-19 07:35:19 +00005745static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCallc373d482010-01-27 01:50:18 +00005746 if (isa<UnresolvedLookupExpr>(E))
John McCall9aa472c2010-03-19 07:35:19 +00005747 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00005748
John McCall9aa472c2010-03-19 07:35:19 +00005749 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00005750}
5751
Douglas Gregor904eed32008-11-10 20:40:00 +00005752/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
5753/// an overloaded function (C++ [over.over]), where @p From is an
5754/// expression with overloaded function type and @p ToType is the type
5755/// we're trying to resolve to. For example:
5756///
5757/// @code
5758/// int f(double);
5759/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00005760///
Douglas Gregor904eed32008-11-10 20:40:00 +00005761/// int (*pfd)(double) = f; // selects f(double)
5762/// @endcode
5763///
5764/// This routine returns the resulting FunctionDecl if it could be
5765/// resolved, and NULL otherwise. When @p Complain is true, this
5766/// routine will emit diagnostics if there is an error.
5767FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00005768Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall6bb80172010-03-30 21:47:33 +00005769 bool Complain,
5770 DeclAccessPair &FoundResult) {
Douglas Gregor904eed32008-11-10 20:40:00 +00005771 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00005772 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00005773 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00005774 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00005775 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00005776 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00005777 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00005778 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00005779 FunctionType = MemTypePtr->getPointeeType();
5780 IsMember = true;
5781 }
Douglas Gregor904eed32008-11-10 20:40:00 +00005782
Douglas Gregor904eed32008-11-10 20:40:00 +00005783 // C++ [over.over]p1:
5784 // [...] [Note: any redundant set of parentheses surrounding the
5785 // overloaded function name is ignored (5.1). ]
Douglas Gregor904eed32008-11-10 20:40:00 +00005786 // C++ [over.over]p1:
5787 // [...] The overloaded function name can be preceded by the &
5788 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00005789 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5790 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
5791 if (OvlExpr->hasExplicitTemplateArgs()) {
5792 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5793 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregor904eed32008-11-10 20:40:00 +00005794 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00005795
5796 // We expect a pointer or reference to function, or a function pointer.
5797 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
5798 if (!FunctionType->isFunctionType()) {
5799 if (Complain)
5800 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
5801 << OvlExpr->getName() << ToType;
5802
5803 return 0;
5804 }
5805
5806 assert(From->getType() == Context.OverloadTy);
Douglas Gregor904eed32008-11-10 20:40:00 +00005807
Douglas Gregor904eed32008-11-10 20:40:00 +00005808 // Look through all of the overloaded functions, searching for one
5809 // whose type matches exactly.
John McCall9aa472c2010-03-19 07:35:19 +00005810 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb7a09262010-04-01 18:32:35 +00005811 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
5812
Douglas Gregor00aeb522009-07-08 23:33:52 +00005813 bool FoundNonTemplateFunction = false;
John McCall7bb12da2010-02-02 06:20:04 +00005814 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5815 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00005816 // Look through any using declarations to find the underlying function.
5817 NamedDecl *Fn = (*I)->getUnderlyingDecl();
5818
Douglas Gregor904eed32008-11-10 20:40:00 +00005819 // C++ [over.over]p3:
5820 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00005821 // targets of type "pointer-to-function" or "reference-to-function."
5822 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00005823 // type "pointer-to-member-function."
5824 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00005825
Mike Stump1eb44332009-09-09 15:08:12 +00005826 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthbd647292009-12-29 06:17:27 +00005827 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump1eb44332009-09-09 15:08:12 +00005828 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00005829 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00005830 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00005831 // static when converting to member pointer.
5832 if (Method->isStatic() == IsMember)
5833 continue;
5834 } else if (IsMember)
5835 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00005836
Douglas Gregor00aeb522009-07-08 23:33:52 +00005837 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00005838 // If the name is a function template, template argument deduction is
5839 // done (14.8.2.2), and if the argument deduction succeeds, the
5840 // resulting template argument list is used to generate a single
5841 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00005842 // overloaded functions considered.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005843 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor83314aa2009-07-08 20:55:45 +00005844 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00005845 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor83314aa2009-07-08 20:55:45 +00005846 if (TemplateDeductionResult Result
John McCall7bb12da2010-02-02 06:20:04 +00005847 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00005848 FunctionType, Specialization, Info)) {
5849 // FIXME: make a note of the failed deduction for diagnostics.
5850 (void)Result;
5851 } else {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005852 // FIXME: If the match isn't exact, shouldn't we just drop this as
5853 // a candidate? Find a testcase before changing the code.
Mike Stump1eb44332009-09-09 15:08:12 +00005854 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00005855 == Context.getCanonicalType(Specialization->getType()));
John McCall9aa472c2010-03-19 07:35:19 +00005856 Matches.push_back(std::make_pair(I.getPair(),
5857 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor83314aa2009-07-08 20:55:45 +00005858 }
John McCallba135432009-11-21 08:51:07 +00005859
5860 continue;
Douglas Gregor83314aa2009-07-08 20:55:45 +00005861 }
Mike Stump1eb44332009-09-09 15:08:12 +00005862
Chandler Carruthbd647292009-12-29 06:17:27 +00005863 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00005864 // Skip non-static functions when converting to pointer, and static
5865 // when converting to member pointer.
5866 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00005867 continue;
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005868
5869 // If we have explicit template arguments, skip non-templates.
John McCall7bb12da2010-02-02 06:20:04 +00005870 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005871 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00005872 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00005873 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00005874
Chandler Carruthbd647292009-12-29 06:17:27 +00005875 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00005876 QualType ResultTy;
5877 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5878 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5879 ResultTy)) {
John McCall9aa472c2010-03-19 07:35:19 +00005880 Matches.push_back(std::make_pair(I.getPair(),
5881 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00005882 FoundNonTemplateFunction = true;
5883 }
Mike Stump1eb44332009-09-09 15:08:12 +00005884 }
Douglas Gregor904eed32008-11-10 20:40:00 +00005885 }
5886
Douglas Gregor00aeb522009-07-08 23:33:52 +00005887 // If there were 0 or 1 matches, we're done.
Douglas Gregor1a8cf732010-04-14 23:11:21 +00005888 if (Matches.empty()) {
5889 if (Complain) {
5890 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
5891 << OvlExpr->getName() << FunctionType;
5892 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5893 E = OvlExpr->decls_end();
5894 I != E; ++I)
5895 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
5896 NoteOverloadCandidate(F);
5897 }
5898
Douglas Gregor00aeb522009-07-08 23:33:52 +00005899 return 0;
Douglas Gregor1a8cf732010-04-14 23:11:21 +00005900 } else if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00005901 FunctionDecl *Result = Matches[0].second;
John McCall6bb80172010-03-30 21:47:33 +00005902 FoundResult = Matches[0].first;
Sebastian Redl07ab2022009-10-17 21:12:09 +00005903 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCallc373d482010-01-27 01:50:18 +00005904 if (Complain)
John McCall6bb80172010-03-30 21:47:33 +00005905 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redl07ab2022009-10-17 21:12:09 +00005906 return Result;
5907 }
Douglas Gregor00aeb522009-07-08 23:33:52 +00005908
5909 // C++ [over.over]p4:
5910 // If more than one function is selected, [...]
Douglas Gregor312a2022009-09-26 03:56:17 +00005911 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005912 // [...] and any given function template specialization F1 is
5913 // eliminated if the set contains a second function template
5914 // specialization whose function template is more specialized
5915 // than the function template of F1 according to the partial
5916 // ordering rules of 14.5.5.2.
5917
5918 // The algorithm specified above is quadratic. We instead use a
5919 // two-pass algorithm (similar to the one used to identify the
5920 // best viable function in an overload set) that identifies the
5921 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00005922
5923 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
5924 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5925 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCallc373d482010-01-27 01:50:18 +00005926
5927 UnresolvedSetIterator Result =
John McCall9aa472c2010-03-19 07:35:19 +00005928 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redl07ab2022009-10-17 21:12:09 +00005929 TPOC_Other, From->getLocStart(),
5930 PDiag(),
5931 PDiag(diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00005932 << Matches[0].second->getDeclName(),
John McCall220ccbf2010-01-13 00:25:19 +00005933 PDiag(diag::note_ovl_candidate)
5934 << (unsigned) oc_function_template);
John McCall9aa472c2010-03-19 07:35:19 +00005935 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCallc373d482010-01-27 01:50:18 +00005936 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall6bb80172010-03-30 21:47:33 +00005937 FoundResult = Matches[Result - MatchesCopy.begin()].first;
John McCallb697e082010-05-06 18:15:07 +00005938 if (Complain) {
John McCall6bb80172010-03-30 21:47:33 +00005939 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCallb697e082010-05-06 18:15:07 +00005940 DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc());
5941 }
John McCallc373d482010-01-27 01:50:18 +00005942 return cast<FunctionDecl>(*Result);
Douglas Gregor00aeb522009-07-08 23:33:52 +00005943 }
Mike Stump1eb44332009-09-09 15:08:12 +00005944
Douglas Gregor312a2022009-09-26 03:56:17 +00005945 // [...] any function template specializations in the set are
5946 // eliminated if the set also contains a non-template function, [...]
John McCallc373d482010-01-27 01:50:18 +00005947 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCall9aa472c2010-03-19 07:35:19 +00005948 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCallc373d482010-01-27 01:50:18 +00005949 ++I;
5950 else {
John McCall9aa472c2010-03-19 07:35:19 +00005951 Matches[I] = Matches[--N];
5952 Matches.set_size(N);
John McCallc373d482010-01-27 01:50:18 +00005953 }
5954 }
Douglas Gregor312a2022009-09-26 03:56:17 +00005955
Mike Stump1eb44332009-09-09 15:08:12 +00005956 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00005957 // selected function.
John McCallc373d482010-01-27 01:50:18 +00005958 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00005959 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall6bb80172010-03-30 21:47:33 +00005960 FoundResult = Matches[0].first;
John McCallb697e082010-05-06 18:15:07 +00005961 if (Complain) {
John McCall9aa472c2010-03-19 07:35:19 +00005962 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
John McCallb697e082010-05-06 18:15:07 +00005963 DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc());
5964 }
John McCall9aa472c2010-03-19 07:35:19 +00005965 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redl07ab2022009-10-17 21:12:09 +00005966 }
Mike Stump1eb44332009-09-09 15:08:12 +00005967
Douglas Gregor00aeb522009-07-08 23:33:52 +00005968 // FIXME: We should probably return the same thing that BestViableFunction
5969 // returns (even if we issue the diagnostics here).
5970 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00005971 << Matches[0].second->getDeclName();
5972 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5973 NoteOverloadCandidate(Matches[I].second);
Douglas Gregor904eed32008-11-10 20:40:00 +00005974 return 0;
5975}
5976
Douglas Gregor4b52e252009-12-21 23:17:24 +00005977/// \brief Given an expression that refers to an overloaded function, try to
5978/// resolve that overloaded function expression down to a single function.
5979///
5980/// This routine can only resolve template-ids that refer to a single function
5981/// template, where that template-id refers to a single template whose template
5982/// arguments are either provided by the template-id or have defaults,
5983/// as described in C++0x [temp.arg.explicit]p3.
5984FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5985 // C++ [over.over]p1:
5986 // [...] [Note: any redundant set of parentheses surrounding the
5987 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00005988 // C++ [over.over]p1:
5989 // [...] The overloaded function name can be preceded by the &
5990 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00005991
5992 if (From->getType() != Context.OverloadTy)
5993 return 0;
5994
5995 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor4b52e252009-12-21 23:17:24 +00005996
5997 // If we didn't actually find any template-ids, we're done.
John McCall7bb12da2010-02-02 06:20:04 +00005998 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00005999 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00006000
6001 TemplateArgumentListInfo ExplicitTemplateArgs;
6002 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor4b52e252009-12-21 23:17:24 +00006003
6004 // Look through all of the overloaded functions, searching for one
6005 // whose type matches exactly.
6006 FunctionDecl *Matched = 0;
John McCall7bb12da2010-02-02 06:20:04 +00006007 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6008 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00006009 // C++0x [temp.arg.explicit]p3:
6010 // [...] In contexts where deduction is done and fails, or in contexts
6011 // where deduction is not done, if a template argument list is
6012 // specified and it, along with any default template arguments,
6013 // identifies a single function template specialization, then the
6014 // template-id is an lvalue for the function template specialization.
6015 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
6016
6017 // C++ [over.over]p2:
6018 // If the name is a function template, template argument deduction is
6019 // done (14.8.2.2), and if the argument deduction succeeds, the
6020 // resulting template argument list is used to generate a single
6021 // function template specialization, which is added to the set of
6022 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00006023 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00006024 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00006025 if (TemplateDeductionResult Result
6026 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6027 Specialization, Info)) {
6028 // FIXME: make a note of the failed deduction for diagnostics.
6029 (void)Result;
6030 continue;
6031 }
6032
6033 // Multiple matches; we can't resolve to a single declaration.
6034 if (Matched)
6035 return 0;
6036
6037 Matched = Specialization;
6038 }
6039
6040 return Matched;
6041}
6042
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006043/// \brief Add a single candidate to the overload set.
6044static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00006045 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00006046 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006047 Expr **Args, unsigned NumArgs,
6048 OverloadCandidateSet &CandidateSet,
6049 bool PartialOverloading) {
John McCall9aa472c2010-03-19 07:35:19 +00006050 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00006051 if (isa<UsingShadowDecl>(Callee))
6052 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6053
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006054 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00006055 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCall9aa472c2010-03-19 07:35:19 +00006056 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00006057 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006058 return;
John McCallba135432009-11-21 08:51:07 +00006059 }
6060
6061 if (FunctionTemplateDecl *FuncTemplate
6062 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00006063 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6064 ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00006065 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00006066 return;
6067 }
6068
6069 assert(false && "unhandled case in overloaded call candidate");
6070
6071 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006072}
6073
6074/// \brief Add the overload candidates named by callee and/or found by argument
6075/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00006076void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006077 Expr **Args, unsigned NumArgs,
6078 OverloadCandidateSet &CandidateSet,
6079 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00006080
6081#ifndef NDEBUG
6082 // Verify that ArgumentDependentLookup is consistent with the rules
6083 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006084 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006085 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6086 // and let Y be the lookup set produced by argument dependent
6087 // lookup (defined as follows). If X contains
6088 //
6089 // -- a declaration of a class member, or
6090 //
6091 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00006092 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006093 //
6094 // -- a declaration that is neither a function or a function
6095 // template
6096 //
6097 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00006098
John McCall3b4294e2009-12-16 12:17:52 +00006099 if (ULE->requiresADL()) {
6100 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6101 E = ULE->decls_end(); I != E; ++I) {
6102 assert(!(*I)->getDeclContext()->isRecord());
6103 assert(isa<UsingShadowDecl>(*I) ||
6104 !(*I)->getDeclContext()->isFunctionOrMethod());
6105 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00006106 }
6107 }
6108#endif
6109
John McCall3b4294e2009-12-16 12:17:52 +00006110 // It would be nice to avoid this copy.
6111 TemplateArgumentListInfo TABuffer;
6112 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6113 if (ULE->hasExplicitTemplateArgs()) {
6114 ULE->copyTemplateArgumentsInto(TABuffer);
6115 ExplicitTemplateArgs = &TABuffer;
6116 }
6117
6118 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6119 E = ULE->decls_end(); I != E; ++I)
John McCall9aa472c2010-03-19 07:35:19 +00006120 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00006121 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006122 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00006123
John McCall3b4294e2009-12-16 12:17:52 +00006124 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00006125 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6126 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006127 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006128 CandidateSet,
6129 PartialOverloading);
6130}
John McCall578b69b2009-12-16 08:11:27 +00006131
John McCall3b4294e2009-12-16 12:17:52 +00006132static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
6133 Expr **Args, unsigned NumArgs) {
6134 Fn->Destroy(SemaRef.Context);
6135 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
6136 Args[Arg]->Destroy(SemaRef.Context);
6137 return SemaRef.ExprError();
6138}
6139
John McCall578b69b2009-12-16 08:11:27 +00006140/// Attempts to recover from a call where no functions were found.
6141///
6142/// Returns true if new candidates were found.
John McCall3b4294e2009-12-16 12:17:52 +00006143static Sema::OwningExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006144BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00006145 UnresolvedLookupExpr *ULE,
6146 SourceLocation LParenLoc,
6147 Expr **Args, unsigned NumArgs,
6148 SourceLocation *CommaLocs,
6149 SourceLocation RParenLoc) {
John McCall578b69b2009-12-16 08:11:27 +00006150
6151 CXXScopeSpec SS;
6152 if (ULE->getQualifier()) {
6153 SS.setScopeRep(ULE->getQualifier());
6154 SS.setRange(ULE->getQualifierRange());
6155 }
6156
John McCall3b4294e2009-12-16 12:17:52 +00006157 TemplateArgumentListInfo TABuffer;
6158 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6159 if (ULE->hasExplicitTemplateArgs()) {
6160 ULE->copyTemplateArgumentsInto(TABuffer);
6161 ExplicitTemplateArgs = &TABuffer;
6162 }
6163
John McCall578b69b2009-12-16 08:11:27 +00006164 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6165 Sema::LookupOrdinaryName);
Douglas Gregor91f7ac72010-05-18 16:14:23 +00006166 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCall3b4294e2009-12-16 12:17:52 +00006167 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCall578b69b2009-12-16 08:11:27 +00006168
John McCall3b4294e2009-12-16 12:17:52 +00006169 assert(!R.empty() && "lookup results empty despite recovery");
6170
6171 // Build an implicit member call if appropriate. Just drop the
6172 // casts and such from the call, we don't really care.
6173 Sema::OwningExprResult NewFn = SemaRef.ExprError();
6174 if ((*R.begin())->isCXXClassMember())
6175 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6176 else if (ExplicitTemplateArgs)
6177 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6178 else
6179 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6180
6181 if (NewFn.isInvalid())
6182 return Destroy(SemaRef, Fn, Args, NumArgs);
6183
6184 Fn->Destroy(SemaRef.Context);
6185
6186 // This shouldn't cause an infinite loop because we're giving it
6187 // an expression with non-empty lookup results, which should never
6188 // end up here.
6189 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
6190 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
6191 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00006192}
Douglas Gregord7a95972010-06-08 17:35:15 +00006193
Douglas Gregorf6b89692008-11-26 05:54:23 +00006194/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00006195/// (which eventually refers to the declaration Func) and the call
6196/// arguments Args/NumArgs, attempt to resolve the function call down
6197/// to a specific function. If overload resolution succeeds, returns
6198/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00006199/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00006200/// arguments and Fn, and returns NULL.
John McCall3b4294e2009-12-16 12:17:52 +00006201Sema::OwningExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006202Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00006203 SourceLocation LParenLoc,
6204 Expr **Args, unsigned NumArgs,
6205 SourceLocation *CommaLocs,
6206 SourceLocation RParenLoc) {
6207#ifndef NDEBUG
6208 if (ULE->requiresADL()) {
6209 // To do ADL, we must have found an unqualified name.
6210 assert(!ULE->getQualifier() && "qualified name with ADL");
6211
6212 // We don't perform ADL for implicit declarations of builtins.
6213 // Verify that this was correctly set up.
6214 FunctionDecl *F;
6215 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6216 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6217 F->getBuiltinID() && F->isImplicit())
6218 assert(0 && "performing ADL for builtin");
6219
6220 // We don't perform ADL in C.
6221 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6222 }
6223#endif
6224
John McCall5769d612010-02-08 23:07:23 +00006225 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00006226
John McCall3b4294e2009-12-16 12:17:52 +00006227 // Add the functions denoted by the callee to the set of candidate
6228 // functions, including those from argument-dependent lookup.
6229 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00006230
6231 // If we found nothing, try to recover.
6232 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6233 // bailout out if it fails.
John McCall3b4294e2009-12-16 12:17:52 +00006234 if (CandidateSet.empty())
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006235 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00006236 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00006237
Douglas Gregorf6b89692008-11-26 05:54:23 +00006238 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006239 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00006240 case OR_Success: {
6241 FunctionDecl *FDecl = Best->Function;
John McCall9aa472c2010-03-19 07:35:19 +00006242 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00006243 DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00006244 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall3b4294e2009-12-16 12:17:52 +00006245 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6246 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00006247
6248 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00006249 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00006250 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00006251 << ULE->getName() << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006252 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00006253 break;
6254
6255 case OR_Ambiguous:
6256 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00006257 << ULE->getName() << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006258 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00006259 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006260
6261 case OR_Deleted:
6262 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6263 << Best->Function->isDeleted()
John McCall3b4294e2009-12-16 12:17:52 +00006264 << ULE->getName()
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006265 << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006266 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006267 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00006268 }
6269
6270 // Overload resolution failed. Destroy all of the subexpressions and
6271 // return NULL.
6272 Fn->Destroy(Context);
6273 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
6274 Args[Arg]->Destroy(Context);
John McCall3b4294e2009-12-16 12:17:52 +00006275 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00006276}
6277
John McCall6e266892010-01-26 03:27:55 +00006278static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00006279 return Functions.size() > 1 ||
6280 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6281}
6282
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006283/// \brief Create a unary operation that may resolve to an overloaded
6284/// operator.
6285///
6286/// \param OpLoc The location of the operator itself (e.g., '*').
6287///
6288/// \param OpcIn The UnaryOperator::Opcode that describes this
6289/// operator.
6290///
6291/// \param Functions The set of non-member functions that will be
6292/// considered by overload resolution. The caller needs to build this
6293/// set based on the context using, e.g.,
6294/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6295/// set should not contain any member functions; those will be added
6296/// by CreateOverloadedUnaryOp().
6297///
6298/// \param input The input argument.
John McCall6e266892010-01-26 03:27:55 +00006299Sema::OwningExprResult
6300Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6301 const UnresolvedSetImpl &Fns,
6302 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006303 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
6304 Expr *Input = (Expr *)input.get();
6305
6306 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6307 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6308 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6309
6310 Expr *Args[2] = { Input, 0 };
6311 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00006312
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006313 // For post-increment and post-decrement, add the implicit '0' as
6314 // the second argument, so that we know this is a post-increment or
6315 // post-decrement.
6316 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
6317 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump1eb44332009-09-09 15:08:12 +00006318 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006319 SourceLocation());
6320 NumArgs = 2;
6321 }
6322
6323 if (Input->isTypeDependent()) {
John McCallc373d482010-01-27 01:50:18 +00006324 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00006325 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00006326 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00006327 0, SourceRange(), OpName, OpLoc,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00006328 /*ADL*/ true, IsOverloaded(Fns),
6329 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006330 input.release();
6331 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6332 &Args[0], NumArgs,
6333 Context.DependentTy,
6334 OpLoc));
6335 }
6336
6337 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00006338 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006339
6340 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00006341 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006342
6343 // Add operator candidates that are member functions.
6344 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6345
John McCall6e266892010-01-26 03:27:55 +00006346 // Add candidates from ADL.
6347 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregordc81c882010-02-05 05:15:43 +00006348 Args, NumArgs,
John McCall6e266892010-01-26 03:27:55 +00006349 /*ExplicitTemplateArgs*/ 0,
6350 CandidateSet);
6351
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006352 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00006353 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006354
6355 // Perform overload resolution.
6356 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006357 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006358 case OR_Success: {
6359 // We found a built-in operator or an overloaded operator.
6360 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00006361
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006362 if (FnDecl) {
6363 // We matched an overloaded operator. Build a call to that
6364 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00006365
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006366 // Convert the arguments.
6367 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00006368 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00006369
John McCall6bb80172010-03-30 21:47:33 +00006370 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6371 Best->FoundDecl, Method))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006372 return ExprError();
6373 } else {
6374 // Convert the arguments.
Douglas Gregore1a5c172009-12-23 17:40:29 +00006375 OwningExprResult InputInit
6376 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregorbaecfed2009-12-23 00:02:00 +00006377 FnDecl->getParamDecl(0)),
Douglas Gregore1a5c172009-12-23 17:40:29 +00006378 SourceLocation(),
6379 move(input));
6380 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006381 return ExprError();
Douglas Gregorbaecfed2009-12-23 00:02:00 +00006382
Douglas Gregore1a5c172009-12-23 17:40:29 +00006383 input = move(InputInit);
Douglas Gregorbaecfed2009-12-23 00:02:00 +00006384 Input = (Expr *)input.get();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006385 }
6386
John McCallb697e082010-05-06 18:15:07 +00006387 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6388
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006389 // Determine the result type
Anders Carlsson26a2a072009-10-13 21:19:37 +00006390 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00006391
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006392 // Build the actual expression node.
6393 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6394 SourceLocation());
6395 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00006396
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006397 input.release();
Eli Friedman4c3b8962009-11-18 03:58:17 +00006398 Args[0] = Input;
Anders Carlsson26a2a072009-10-13 21:19:37 +00006399 ExprOwningPtr<CallExpr> TheCall(this,
6400 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman4c3b8962009-11-18 03:58:17 +00006401 Args, NumArgs, ResultTy, OpLoc));
John McCallb697e082010-05-06 18:15:07 +00006402
Anders Carlsson26a2a072009-10-13 21:19:37 +00006403 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6404 FnDecl))
6405 return ExprError();
6406
6407 return MaybeBindToTemporary(TheCall.release());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006408 } else {
6409 // We matched a built-in operator. Convert the arguments, then
6410 // break out so that we will build the appropriate built-in
6411 // operator node.
6412 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00006413 Best->Conversions[0], AA_Passing))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006414 return ExprError();
6415
6416 break;
6417 }
6418 }
6419
6420 case OR_No_Viable_Function:
6421 // No viable function; fall through to handling this as a
6422 // built-in operator, which will produce an error message for us.
6423 break;
6424
6425 case OR_Ambiguous:
6426 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6427 << UnaryOperator::getOpcodeStr(Opc)
6428 << Input->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006429 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00006430 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006431 return ExprError();
6432
6433 case OR_Deleted:
6434 Diag(OpLoc, diag::err_ovl_deleted_oper)
6435 << Best->Function->isDeleted()
6436 << UnaryOperator::getOpcodeStr(Opc)
6437 << Input->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006438 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006439 return ExprError();
6440 }
6441
6442 // Either we found no viable overloaded operator or we matched a
6443 // built-in operator. In either case, fall through to trying to
6444 // build a built-in operation.
6445 input.release();
6446 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
6447}
6448
Douglas Gregor063daf62009-03-13 18:40:31 +00006449/// \brief Create a binary operation that may resolve to an overloaded
6450/// operator.
6451///
6452/// \param OpLoc The location of the operator itself (e.g., '+').
6453///
6454/// \param OpcIn The BinaryOperator::Opcode that describes this
6455/// operator.
6456///
6457/// \param Functions The set of non-member functions that will be
6458/// considered by overload resolution. The caller needs to build this
6459/// set based on the context using, e.g.,
6460/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6461/// set should not contain any member functions; those will be added
6462/// by CreateOverloadedBinOp().
6463///
6464/// \param LHS Left-hand argument.
6465/// \param RHS Right-hand argument.
Mike Stump1eb44332009-09-09 15:08:12 +00006466Sema::OwningExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00006467Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006468 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00006469 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00006470 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00006471 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006472 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00006473
6474 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6475 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6476 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6477
6478 // If either side is type-dependent, create an appropriate dependent
6479 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006480 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00006481 if (Fns.empty()) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006482 // If there are no functions to store, just build a dependent
6483 // BinaryOperator or CompoundAssignment.
6484 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
6485 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6486 Context.DependentTy, OpLoc));
6487
6488 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6489 Context.DependentTy,
6490 Context.DependentTy,
6491 Context.DependentTy,
6492 OpLoc));
6493 }
John McCall6e266892010-01-26 03:27:55 +00006494
6495 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00006496 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00006497 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00006498 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00006499 0, SourceRange(), OpName, OpLoc,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00006500 /*ADL*/ true, IsOverloaded(Fns),
6501 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00006502 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00006503 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00006504 Context.DependentTy,
6505 OpLoc));
6506 }
6507
6508 // If this is the .* operator, which is not overloadable, just
6509 // create a built-in binary operator.
6510 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006511 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00006512
Sebastian Redl275c2b42009-11-18 23:10:33 +00006513 // If this is the assignment operator, we only perform overload resolution
6514 // if the left-hand side is a class or enumeration type. This is actually
6515 // a hack. The standard requires that we do overload resolution between the
6516 // various built-in candidates, but as DR507 points out, this can lead to
6517 // problems. So we do it this way, which pretty much follows what GCC does.
6518 // Note that we go the traditional code path for compound assignment forms.
6519 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006520 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00006521
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006522 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00006523 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00006524
6525 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00006526 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00006527
6528 // Add operator candidates that are member functions.
6529 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6530
John McCall6e266892010-01-26 03:27:55 +00006531 // Add candidates from ADL.
6532 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6533 Args, 2,
6534 /*ExplicitTemplateArgs*/ 0,
6535 CandidateSet);
6536
Douglas Gregor063daf62009-03-13 18:40:31 +00006537 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00006538 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00006539
6540 // Perform overload resolution.
6541 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006542 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00006543 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00006544 // We found a built-in operator or an overloaded operator.
6545 FunctionDecl *FnDecl = Best->Function;
6546
6547 if (FnDecl) {
6548 // We matched an overloaded operator. Build a call to that
6549 // operator.
6550
6551 // Convert the arguments.
6552 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00006553 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +00006554 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00006555
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006556 OwningExprResult Arg1
6557 = PerformCopyInitialization(
6558 InitializedEntity::InitializeParameter(
6559 FnDecl->getParamDecl(0)),
6560 SourceLocation(),
6561 Owned(Args[1]));
6562 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00006563 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006564
Douglas Gregor5fccd362010-03-03 23:55:11 +00006565 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00006566 Best->FoundDecl, Method))
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006567 return ExprError();
6568
6569 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00006570 } else {
6571 // Convert the arguments.
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006572 OwningExprResult Arg0
6573 = PerformCopyInitialization(
6574 InitializedEntity::InitializeParameter(
6575 FnDecl->getParamDecl(0)),
6576 SourceLocation(),
6577 Owned(Args[0]));
6578 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00006579 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006580
6581 OwningExprResult Arg1
6582 = PerformCopyInitialization(
6583 InitializedEntity::InitializeParameter(
6584 FnDecl->getParamDecl(1)),
6585 SourceLocation(),
6586 Owned(Args[1]));
6587 if (Arg1.isInvalid())
6588 return ExprError();
6589 Args[0] = LHS = Arg0.takeAs<Expr>();
6590 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00006591 }
6592
John McCallb697e082010-05-06 18:15:07 +00006593 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6594
Douglas Gregor063daf62009-03-13 18:40:31 +00006595 // Determine the result type
6596 QualType ResultTy
John McCall183700f2009-09-21 23:43:11 +00006597 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor063daf62009-03-13 18:40:31 +00006598 ResultTy = ResultTy.getNonReferenceType();
6599
6600 // Build the actual expression node.
6601 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00006602 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00006603 UsualUnaryConversions(FnExpr);
6604
Anders Carlsson15ea3782009-10-13 22:43:21 +00006605 ExprOwningPtr<CXXOperatorCallExpr>
6606 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6607 Args, 2, ResultTy,
6608 OpLoc));
6609
6610 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6611 FnDecl))
6612 return ExprError();
6613
6614 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor063daf62009-03-13 18:40:31 +00006615 } else {
6616 // We matched a built-in operator. Convert the arguments, then
6617 // break out so that we will build the appropriate built-in
6618 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006619 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00006620 Best->Conversions[0], AA_Passing) ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006621 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00006622 Best->Conversions[1], AA_Passing))
Douglas Gregor063daf62009-03-13 18:40:31 +00006623 return ExprError();
6624
6625 break;
6626 }
6627 }
6628
Douglas Gregor33074752009-09-30 21:46:01 +00006629 case OR_No_Viable_Function: {
6630 // C++ [over.match.oper]p9:
6631 // If the operator is the operator , [...] and there are no
6632 // viable functions, then the operator is assumed to be the
6633 // built-in operator and interpreted according to clause 5.
6634 if (Opc == BinaryOperator::Comma)
6635 break;
6636
Sebastian Redl8593c782009-05-21 11:50:50 +00006637 // For class as left operand for assignment or compound assigment operator
6638 // do not fall through to handling in built-in, but report that no overloaded
6639 // assignment operator found
Douglas Gregor33074752009-09-30 21:46:01 +00006640 OwningExprResult Result = ExprError();
6641 if (Args[0]->getType()->isRecordType() &&
6642 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00006643 Diag(OpLoc, diag::err_ovl_no_viable_oper)
6644 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006645 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00006646 } else {
6647 // No viable function; try to create a built-in operation, which will
6648 // produce an error. Then, show the non-viable candidates.
6649 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00006650 }
Douglas Gregor33074752009-09-30 21:46:01 +00006651 assert(Result.isInvalid() &&
6652 "C++ binary operator overloading is missing candidates!");
6653 if (Result.isInvalid())
John McCallcbce6062010-01-12 07:18:19 +00006654 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00006655 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00006656 return move(Result);
6657 }
Douglas Gregor063daf62009-03-13 18:40:31 +00006658
6659 case OR_Ambiguous:
6660 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6661 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006662 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006663 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00006664 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00006665 return ExprError();
6666
6667 case OR_Deleted:
6668 Diag(OpLoc, diag::err_ovl_deleted_oper)
6669 << Best->Function->isDeleted()
6670 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006671 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006672 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor063daf62009-03-13 18:40:31 +00006673 return ExprError();
John McCall1d318332010-01-12 00:44:57 +00006674 }
Douglas Gregor063daf62009-03-13 18:40:31 +00006675
Douglas Gregor33074752009-09-30 21:46:01 +00006676 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006677 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00006678}
6679
Sebastian Redlf322ed62009-10-29 20:17:01 +00006680Action::OwningExprResult
6681Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
6682 SourceLocation RLoc,
6683 ExprArg Base, ExprArg Idx) {
6684 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
6685 static_cast<Expr*>(Idx.get()) };
6686 DeclarationName OpName =
6687 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
6688
6689 // If either side is type-dependent, create an appropriate dependent
6690 // expression.
6691 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
6692
John McCallc373d482010-01-27 01:50:18 +00006693 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00006694 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00006695 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00006696 0, SourceRange(), OpName, LLoc,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00006697 /*ADL*/ true, /*Overloaded*/ false,
6698 UnresolvedSetIterator(),
6699 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +00006700 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00006701
6702 Base.release();
6703 Idx.release();
6704 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
6705 Args, 2,
6706 Context.DependentTy,
6707 RLoc));
6708 }
6709
6710 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00006711 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00006712
6713 // Subscript can only be overloaded as a member function.
6714
6715 // Add operator candidates that are member functions.
6716 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6717
6718 // Add builtin operator candidates.
6719 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6720
6721 // Perform overload resolution.
6722 OverloadCandidateSet::iterator Best;
6723 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
6724 case OR_Success: {
6725 // We found a built-in operator or an overloaded operator.
6726 FunctionDecl *FnDecl = Best->Function;
6727
6728 if (FnDecl) {
6729 // We matched an overloaded operator. Build a call to that
6730 // operator.
6731
John McCall9aa472c2010-03-19 07:35:19 +00006732 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00006733 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +00006734
Sebastian Redlf322ed62009-10-29 20:17:01 +00006735 // Convert the arguments.
6736 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregor5fccd362010-03-03 23:55:11 +00006737 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00006738 Best->FoundDecl, Method))
Sebastian Redlf322ed62009-10-29 20:17:01 +00006739 return ExprError();
6740
Anders Carlsson38f88ab2010-01-29 18:37:50 +00006741 // Convert the arguments.
6742 OwningExprResult InputInit
6743 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6744 FnDecl->getParamDecl(0)),
6745 SourceLocation(),
6746 Owned(Args[1]));
6747 if (InputInit.isInvalid())
6748 return ExprError();
6749
6750 Args[1] = InputInit.takeAs<Expr>();
6751
Sebastian Redlf322ed62009-10-29 20:17:01 +00006752 // Determine the result type
6753 QualType ResultTy
6754 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
6755 ResultTy = ResultTy.getNonReferenceType();
6756
6757 // Build the actual expression node.
6758 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6759 LLoc);
6760 UsualUnaryConversions(FnExpr);
6761
6762 Base.release();
6763 Idx.release();
6764 ExprOwningPtr<CXXOperatorCallExpr>
6765 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
6766 FnExpr, Args, 2,
6767 ResultTy, RLoc));
6768
6769 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
6770 FnDecl))
6771 return ExprError();
6772
6773 return MaybeBindToTemporary(TheCall.release());
6774 } else {
6775 // We matched a built-in operator. Convert the arguments, then
6776 // break out so that we will build the appropriate built-in
6777 // operator node.
6778 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00006779 Best->Conversions[0], AA_Passing) ||
Sebastian Redlf322ed62009-10-29 20:17:01 +00006780 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00006781 Best->Conversions[1], AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00006782 return ExprError();
6783
6784 break;
6785 }
6786 }
6787
6788 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00006789 if (CandidateSet.empty())
6790 Diag(LLoc, diag::err_ovl_no_oper)
6791 << Args[0]->getType() << /*subscript*/ 0
6792 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6793 else
6794 Diag(LLoc, diag::err_ovl_no_viable_subscript)
6795 << Args[0]->getType()
6796 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006797 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall1eb3e102010-01-07 02:04:15 +00006798 "[]", LLoc);
6799 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00006800 }
6801
6802 case OR_Ambiguous:
6803 Diag(LLoc, diag::err_ovl_ambiguous_oper)
6804 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006805 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redlf322ed62009-10-29 20:17:01 +00006806 "[]", LLoc);
6807 return ExprError();
6808
6809 case OR_Deleted:
6810 Diag(LLoc, diag::err_ovl_deleted_oper)
6811 << Best->Function->isDeleted() << "[]"
6812 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006813 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall81201622010-01-08 04:41:39 +00006814 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00006815 return ExprError();
6816 }
6817
6818 // We matched a built-in operator; build it.
6819 Base.release();
6820 Idx.release();
6821 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
6822 Owned(Args[1]), RLoc);
6823}
6824
Douglas Gregor88a35142008-12-22 05:46:06 +00006825/// BuildCallToMemberFunction - Build a call to a member
6826/// function. MemExpr is the expression that refers to the member
6827/// function (and includes the object parameter), Args/NumArgs are the
6828/// arguments to the function call (not including the object
6829/// parameter). The caller needs to validate that the member
6830/// expression refers to a member function or an overloaded member
6831/// function.
John McCallaa81e162009-12-01 22:10:20 +00006832Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00006833Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
6834 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor88a35142008-12-22 05:46:06 +00006835 unsigned NumArgs, SourceLocation *CommaLocs,
6836 SourceLocation RParenLoc) {
6837 // Dig out the member expression. This holds both the object
6838 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00006839 Expr *NakedMemExpr = MemExprE->IgnoreParens();
6840
John McCall129e2df2009-11-30 22:42:35 +00006841 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00006842 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +00006843 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +00006844 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +00006845 if (isa<MemberExpr>(NakedMemExpr)) {
6846 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00006847 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +00006848 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +00006849 Qualifier = MemExpr->getQualifier();
John McCall129e2df2009-11-30 22:42:35 +00006850 } else {
6851 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +00006852 Qualifier = UnresExpr->getQualifier();
6853
John McCall701c89e2009-12-03 04:06:58 +00006854 QualType ObjectType = UnresExpr->getBaseType();
John McCall129e2df2009-11-30 22:42:35 +00006855
Douglas Gregor88a35142008-12-22 05:46:06 +00006856 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +00006857 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00006858
John McCallaa81e162009-12-01 22:10:20 +00006859 // FIXME: avoid copy.
6860 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6861 if (UnresExpr->hasExplicitTemplateArgs()) {
6862 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6863 TemplateArgs = &TemplateArgsBuffer;
6864 }
6865
John McCall129e2df2009-11-30 22:42:35 +00006866 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6867 E = UnresExpr->decls_end(); I != E; ++I) {
6868
John McCall701c89e2009-12-03 04:06:58 +00006869 NamedDecl *Func = *I;
6870 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6871 if (isa<UsingShadowDecl>(Func))
6872 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6873
John McCall129e2df2009-11-30 22:42:35 +00006874 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006875 // If explicit template arguments were provided, we can't call a
6876 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00006877 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006878 continue;
6879
John McCall9aa472c2010-03-19 07:35:19 +00006880 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCall86820f52010-01-26 01:37:31 +00006881 Args, NumArgs,
John McCall701c89e2009-12-03 04:06:58 +00006882 CandidateSet, /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00006883 } else {
John McCall129e2df2009-11-30 22:42:35 +00006884 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +00006885 I.getPair(), ActingDC, TemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00006886 ObjectType, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00006887 CandidateSet,
6888 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00006889 }
Douglas Gregordec06662009-08-21 18:42:58 +00006890 }
Mike Stump1eb44332009-09-09 15:08:12 +00006891
John McCall129e2df2009-11-30 22:42:35 +00006892 DeclarationName DeclName = UnresExpr->getMemberName();
6893
Douglas Gregor88a35142008-12-22 05:46:06 +00006894 OverloadCandidateSet::iterator Best;
John McCall129e2df2009-11-30 22:42:35 +00006895 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00006896 case OR_Success:
6897 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00006898 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +00006899 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00006900 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +00006901 break;
6902
6903 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00006904 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00006905 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00006906 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006907 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00006908 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00006909 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006910
6911 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00006912 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00006913 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006914 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00006915 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00006916 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006917
6918 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00006919 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006920 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00006921 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006922 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006923 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00006924 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006925 }
6926
John McCall6bb80172010-03-30 21:47:33 +00006927 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +00006928
John McCallaa81e162009-12-01 22:10:20 +00006929 // If overload resolution picked a static member, build a
6930 // non-member call based on that function.
6931 if (Method->isStatic()) {
6932 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6933 Args, NumArgs, RParenLoc);
6934 }
6935
John McCall129e2df2009-11-30 22:42:35 +00006936 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00006937 }
6938
6939 assert(Method && "Member call to something that isn't a method?");
Mike Stump1eb44332009-09-09 15:08:12 +00006940 ExprOwningPtr<CXXMemberCallExpr>
John McCallaa81e162009-12-01 22:10:20 +00006941 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump1eb44332009-09-09 15:08:12 +00006942 NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00006943 Method->getResultType().getNonReferenceType(),
6944 RParenLoc));
6945
Anders Carlssoneed3e692009-10-10 00:06:20 +00006946 // Check for a valid return type.
6947 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6948 TheCall.get(), Method))
John McCallaa81e162009-12-01 22:10:20 +00006949 return ExprError();
Anders Carlssoneed3e692009-10-10 00:06:20 +00006950
Douglas Gregor88a35142008-12-22 05:46:06 +00006951 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +00006952 // We only need to do this if there was actually an overload; otherwise
6953 // it was done at lookup.
John McCallaa81e162009-12-01 22:10:20 +00006954 Expr *ObjectArg = MemExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00006955 if (!Method->isStatic() &&
John McCall6bb80172010-03-30 21:47:33 +00006956 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
6957 FoundDecl, Method))
John McCallaa81e162009-12-01 22:10:20 +00006958 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006959 MemExpr->setBase(ObjectArg);
6960
6961 // Convert the rest of the arguments
Douglas Gregor5f970ee2010-05-04 18:18:31 +00006962 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006963 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00006964 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00006965 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006966
Anders Carlssond406bf02009-08-16 01:56:34 +00006967 if (CheckFunctionCall(Method, TheCall.get()))
John McCallaa81e162009-12-01 22:10:20 +00006968 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00006969
John McCallaa81e162009-12-01 22:10:20 +00006970 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor88a35142008-12-22 05:46:06 +00006971}
6972
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006973/// BuildCallToObjectOfClassType - Build a call to an object of class
6974/// type (C++ [over.call.object]), which can end up invoking an
6975/// overloaded function call operator (@c operator()) or performing a
6976/// user-defined conversion on the object argument.
Mike Stump1eb44332009-09-09 15:08:12 +00006977Sema::ExprResult
6978Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00006979 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006980 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00006981 SourceLocation *CommaLocs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006982 SourceLocation RParenLoc) {
6983 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00006984 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006985
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006986 // C++ [over.call.object]p1:
6987 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00006988 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006989 // candidate functions includes at least the function call
6990 // operators of T. The function call operators of T are obtained by
6991 // ordinary lookup of the name operator() in the context of
6992 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +00006993 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00006994 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00006995
6996 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006997 PDiag(diag::err_incomplete_object_call)
Douglas Gregor593564b2009-11-15 07:48:03 +00006998 << Object->getSourceRange()))
6999 return true;
7000
John McCalla24dc2e2009-11-17 02:14:36 +00007001 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7002 LookupQualifiedName(R, Record->getDecl());
7003 R.suppressDiagnostics();
7004
Douglas Gregor593564b2009-11-15 07:48:03 +00007005 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00007006 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00007007 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCall86820f52010-01-26 01:37:31 +00007008 Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00007009 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00007010 }
Douglas Gregor4a27d702009-10-21 06:18:39 +00007011
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007012 // C++ [over.call.object]p2:
7013 // In addition, for each conversion function declared in T of the
7014 // form
7015 //
7016 // operator conversion-type-id () cv-qualifier;
7017 //
7018 // where cv-qualifier is the same cv-qualification as, or a
7019 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00007020 // denotes the type "pointer to function of (P1,...,Pn) returning
7021 // R", or the type "reference to pointer to function of
7022 // (P1,...,Pn) returning R", or the type "reference to function
7023 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007024 // is also considered as a candidate function. Similarly,
7025 // surrogate call functions are added to the set of candidate
7026 // functions for each conversion function declared in an
7027 // accessible base class provided the function is not hidden
7028 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +00007029 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00007030 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00007031 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00007032 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00007033 NamedDecl *D = *I;
7034 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7035 if (isa<UsingShadowDecl>(D))
7036 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7037
Douglas Gregor4a27d702009-10-21 06:18:39 +00007038 // Skip over templated conversion functions; they aren't
7039 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00007040 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00007041 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007042
John McCall701c89e2009-12-03 04:06:58 +00007043 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCallba135432009-11-21 08:51:07 +00007044
Douglas Gregor4a27d702009-10-21 06:18:39 +00007045 // Strip the reference type (if any) and then the pointer type (if
7046 // any) to get down to what might be a function type.
7047 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7048 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7049 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007050
Douglas Gregor4a27d702009-10-21 06:18:39 +00007051 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall9aa472c2010-03-19 07:35:19 +00007052 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall701c89e2009-12-03 04:06:58 +00007053 Object->getType(), Args, NumArgs,
7054 CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007055 }
Mike Stump1eb44332009-09-09 15:08:12 +00007056
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007057 // Perform overload resolution.
7058 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00007059 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007060 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007061 // Overload resolution succeeded; we'll build the appropriate call
7062 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007063 break;
7064
7065 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00007066 if (CandidateSet.empty())
7067 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7068 << Object->getType() << /*call*/ 1
7069 << Object->getSourceRange();
7070 else
7071 Diag(Object->getSourceRange().getBegin(),
7072 diag::err_ovl_no_viable_object_call)
7073 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007074 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007075 break;
7076
7077 case OR_Ambiguous:
7078 Diag(Object->getSourceRange().getBegin(),
7079 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00007080 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007081 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007082 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007083
7084 case OR_Deleted:
7085 Diag(Object->getSourceRange().getBegin(),
7086 diag::err_ovl_deleted_object_call)
7087 << Best->Function->isDeleted()
7088 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007089 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007090 break;
Mike Stump1eb44332009-09-09 15:08:12 +00007091 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007092
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007093 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007094 // We had an error; delete all of the subexpressions and return
7095 // the error.
Ted Kremenek8189cde2009-02-07 01:47:29 +00007096 Object->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007097 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek8189cde2009-02-07 01:47:29 +00007098 Args[ArgIdx]->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007099 return true;
7100 }
7101
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007102 if (Best->Function == 0) {
7103 // Since there is no function declaration, this is one of the
7104 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00007105 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007106 = cast<CXXConversionDecl>(
7107 Best->Conversions[0].UserDefined.ConversionFunction);
7108
John McCall9aa472c2010-03-19 07:35:19 +00007109 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007110 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00007111
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007112 // We selected one of the surrogate functions that converts the
7113 // object parameter to a function pointer. Perform the conversion
7114 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00007115
7116 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00007117 // and then call it.
John McCall6bb80172010-03-30 21:47:33 +00007118 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7119 Conv);
Fariborz Jahanianb7400232009-09-28 23:23:40 +00007120
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00007121 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00007122 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
Douglas Gregoraa0be172010-04-13 15:50:39 +00007123 CommaLocs, RParenLoc).result();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007124 }
7125
John McCall9aa472c2010-03-19 07:35:19 +00007126 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007127 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00007128
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007129 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7130 // that calls this method, using Object for the implicit object
7131 // parameter and passing along the remaining arguments.
7132 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall183700f2009-09-21 23:43:11 +00007133 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007134
7135 unsigned NumArgsInProto = Proto->getNumArgs();
7136 unsigned NumArgsToCheck = NumArgs;
7137
7138 // Build the full argument list for the method call (the
7139 // implicit object parameter is placed at the beginning of the
7140 // list).
7141 Expr **MethodArgs;
7142 if (NumArgs < NumArgsInProto) {
7143 NumArgsToCheck = NumArgsInProto;
7144 MethodArgs = new Expr*[NumArgsInProto + 1];
7145 } else {
7146 MethodArgs = new Expr*[NumArgs + 1];
7147 }
7148 MethodArgs[0] = Object;
7149 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7150 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00007151
7152 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00007153 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007154 UsualUnaryConversions(NewFn);
7155
7156 // Once we've built TheCall, all of the expressions are properly
7157 // owned.
7158 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00007159 ExprOwningPtr<CXXOperatorCallExpr>
7160 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor063daf62009-03-13 18:40:31 +00007161 MethodArgs, NumArgs + 1,
Ted Kremenek8189cde2009-02-07 01:47:29 +00007162 ResultTy, RParenLoc));
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007163 delete [] MethodArgs;
7164
Anders Carlsson07d68f12009-10-13 21:49:31 +00007165 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
7166 Method))
7167 return true;
7168
Douglas Gregor518fda12009-01-13 05:10:00 +00007169 // We may have default arguments. If so, we need to allocate more
7170 // slots in the call for them.
7171 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00007172 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00007173 else if (NumArgs > NumArgsInProto)
7174 NumArgsToCheck = NumArgsInProto;
7175
Chris Lattner312531a2009-04-12 08:11:20 +00007176 bool IsError = false;
7177
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007178 // Initialize the implicit object parameter.
Douglas Gregor5fccd362010-03-03 23:55:11 +00007179 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007180 Best->FoundDecl, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007181 TheCall->setArg(0, Object);
7182
Chris Lattner312531a2009-04-12 08:11:20 +00007183
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007184 // Check the argument types.
7185 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007186 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00007187 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007188 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00007189
Douglas Gregor518fda12009-01-13 05:10:00 +00007190 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +00007191
7192 OwningExprResult InputInit
7193 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7194 Method->getParamDecl(i)),
7195 SourceLocation(), Owned(Arg));
7196
7197 IsError |= InputInit.isInvalid();
7198 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00007199 } else {
Douglas Gregord47c47d2009-11-09 19:27:57 +00007200 OwningExprResult DefArg
7201 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7202 if (DefArg.isInvalid()) {
7203 IsError = true;
7204 break;
7205 }
7206
7207 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00007208 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007209
7210 TheCall->setArg(i + 1, Arg);
7211 }
7212
7213 // If this is a variadic call, handle args passed through "...".
7214 if (Proto->isVariadic()) {
7215 // Promote the arguments (C99 6.5.2.2p7).
7216 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7217 Expr *Arg = Args[i];
Chris Lattner40378332010-05-16 04:01:30 +00007218 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007219 TheCall->setArg(i + 1, Arg);
7220 }
7221 }
7222
Chris Lattner312531a2009-04-12 08:11:20 +00007223 if (IsError) return true;
7224
Anders Carlssond406bf02009-08-16 01:56:34 +00007225 if (CheckFunctionCall(Method, TheCall.get()))
7226 return true;
7227
Douglas Gregoraa0be172010-04-13 15:50:39 +00007228 return MaybeBindToTemporary(TheCall.release()).result();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007229}
7230
Douglas Gregor8ba10742008-11-20 16:27:02 +00007231/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00007232/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00007233/// @c Member is the name of the member we're trying to find.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007234Sema::OwningExprResult
7235Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
7236 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor8ba10742008-11-20 16:27:02 +00007237 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00007238
John McCall5769d612010-02-08 23:07:23 +00007239 SourceLocation Loc = Base->getExprLoc();
7240
Douglas Gregor8ba10742008-11-20 16:27:02 +00007241 // C++ [over.ref]p1:
7242 //
7243 // [...] An expression x->m is interpreted as (x.operator->())->m
7244 // for a class object x of type T if T::operator->() exists and if
7245 // the operator is selected as the best match function by the
7246 // overload resolution mechanism (13.3).
Douglas Gregor8ba10742008-11-20 16:27:02 +00007247 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +00007248 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +00007249 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007250
John McCall5769d612010-02-08 23:07:23 +00007251 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +00007252 PDiag(diag::err_typecheck_incomplete_tag)
7253 << Base->getSourceRange()))
7254 return ExprError();
7255
John McCalla24dc2e2009-11-17 02:14:36 +00007256 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7257 LookupQualifiedName(R, BaseRecord->getDecl());
7258 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00007259
7260 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00007261 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00007262 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00007263 /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00007264 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00007265
7266 // Perform overload resolution.
7267 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00007268 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00007269 case OR_Success:
7270 // Overload resolution succeeded; we'll build the call below.
7271 break;
7272
7273 case OR_No_Viable_Function:
7274 if (CandidateSet.empty())
7275 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007276 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007277 else
7278 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007279 << "operator->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007280 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007281 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007282
7283 case OR_Ambiguous:
7284 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlssone30572a2009-09-10 23:18:36 +00007285 << "->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007286 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007287 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007288
7289 case OR_Deleted:
7290 Diag(OpLoc, diag::err_ovl_deleted_oper)
7291 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00007292 << "->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007293 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007294 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007295 }
7296
John McCall9aa472c2010-03-19 07:35:19 +00007297 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007298 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +00007299
Douglas Gregor8ba10742008-11-20 16:27:02 +00007300 // Convert the object parameter.
7301 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00007302 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7303 Best->FoundDecl, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007304 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00007305
7306 // No concerns about early exits now.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007307 BaseIn.release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007308
7309 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00007310 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7311 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00007312 UsualUnaryConversions(FnExpr);
Anders Carlsson15ea3782009-10-13 22:43:21 +00007313
7314 QualType ResultTy = Method->getResultType().getNonReferenceType();
7315 ExprOwningPtr<CXXOperatorCallExpr>
7316 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7317 &Base, 1, ResultTy, OpLoc));
7318
7319 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
7320 Method))
7321 return ExprError();
7322 return move(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00007323}
7324
Douglas Gregor904eed32008-11-10 20:40:00 +00007325/// FixOverloadedFunctionReference - E is an expression that refers to
7326/// a C++ overloaded function (possibly with some parentheses and
7327/// perhaps a '&' around it). We have resolved the overloaded function
7328/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00007329/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +00007330Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +00007331 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00007332 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00007333 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7334 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00007335 if (SubExpr == PE->getSubExpr())
7336 return PE->Retain();
7337
7338 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7339 }
7340
7341 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00007342 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7343 Found, Fn);
Douglas Gregor097bfb12009-10-23 22:18:25 +00007344 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00007345 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00007346 "Implicit cast type cannot be determined from overload");
Douglas Gregor699ee522009-11-20 19:42:02 +00007347 if (SubExpr == ICE->getSubExpr())
7348 return ICE->Retain();
7349
7350 return new (Context) ImplicitCastExpr(ICE->getType(),
7351 ICE->getCastKind(),
Anders Carlssonf1b48b72010-04-24 16:57:13 +00007352 SubExpr, CXXBaseSpecifierArray(),
Douglas Gregor699ee522009-11-20 19:42:02 +00007353 ICE->isLvalueCast());
7354 }
7355
7356 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007357 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00007358 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00007359 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7360 if (Method->isStatic()) {
7361 // Do nothing: static member functions aren't any different
7362 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00007363 } else {
John McCallf7a1a742009-11-24 19:00:30 +00007364 // Fix the sub expression, which really has to be an
7365 // UnresolvedLookupExpr holding an overloaded member function
7366 // or template.
John McCall6bb80172010-03-30 21:47:33 +00007367 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7368 Found, Fn);
John McCallba135432009-11-21 08:51:07 +00007369 if (SubExpr == UnOp->getSubExpr())
7370 return UnOp->Retain();
Douglas Gregor699ee522009-11-20 19:42:02 +00007371
John McCallba135432009-11-21 08:51:07 +00007372 assert(isa<DeclRefExpr>(SubExpr)
7373 && "fixed to something other than a decl ref");
7374 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7375 && "fixed to a member ref with no nested name qualifier");
7376
7377 // We have taken the address of a pointer to member
7378 // function. Perform the computation here so that we get the
7379 // appropriate pointer to member type.
7380 QualType ClassType
7381 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7382 QualType MemPtrType
7383 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7384
7385 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7386 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00007387 }
7388 }
John McCall6bb80172010-03-30 21:47:33 +00007389 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7390 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00007391 if (SubExpr == UnOp->getSubExpr())
7392 return UnOp->Retain();
Anders Carlsson96ad5332009-10-21 17:16:23 +00007393
Douglas Gregor699ee522009-11-20 19:42:02 +00007394 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7395 Context.getPointerType(SubExpr->getType()),
7396 UnOp->getOperatorLoc());
Douglas Gregor699ee522009-11-20 19:42:02 +00007397 }
John McCallba135432009-11-21 08:51:07 +00007398
7399 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00007400 // FIXME: avoid copy.
7401 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00007402 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00007403 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7404 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00007405 }
7406
John McCallba135432009-11-21 08:51:07 +00007407 return DeclRefExpr::Create(Context,
7408 ULE->getQualifier(),
7409 ULE->getQualifierRange(),
7410 Fn,
7411 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00007412 Fn->getType(),
7413 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00007414 }
7415
John McCall129e2df2009-11-30 22:42:35 +00007416 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00007417 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00007418 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7419 if (MemExpr->hasExplicitTemplateArgs()) {
7420 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7421 TemplateArgs = &TemplateArgsBuffer;
7422 }
John McCalld5532b62009-11-23 01:53:49 +00007423
John McCallaa81e162009-12-01 22:10:20 +00007424 Expr *Base;
7425
7426 // If we're filling in
7427 if (MemExpr->isImplicitAccess()) {
7428 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7429 return DeclRefExpr::Create(Context,
7430 MemExpr->getQualifier(),
7431 MemExpr->getQualifierRange(),
7432 Fn,
7433 MemExpr->getMemberLoc(),
7434 Fn->getType(),
7435 TemplateArgs);
Douglas Gregor828a1972010-01-07 23:12:05 +00007436 } else {
7437 SourceLocation Loc = MemExpr->getMemberLoc();
7438 if (MemExpr->getQualifier())
7439 Loc = MemExpr->getQualifierRange().getBegin();
7440 Base = new (Context) CXXThisExpr(Loc,
7441 MemExpr->getBaseType(),
7442 /*isImplicit=*/true);
7443 }
John McCallaa81e162009-12-01 22:10:20 +00007444 } else
7445 Base = MemExpr->getBase()->Retain();
7446
7447 return MemberExpr::Create(Context, Base,
Douglas Gregor699ee522009-11-20 19:42:02 +00007448 MemExpr->isArrow(),
7449 MemExpr->getQualifier(),
7450 MemExpr->getQualifierRange(),
7451 Fn,
John McCall6bb80172010-03-30 21:47:33 +00007452 Found,
John McCalld5532b62009-11-23 01:53:49 +00007453 MemExpr->getMemberLoc(),
John McCallaa81e162009-12-01 22:10:20 +00007454 TemplateArgs,
Douglas Gregor699ee522009-11-20 19:42:02 +00007455 Fn->getType());
7456 }
7457
Douglas Gregor699ee522009-11-20 19:42:02 +00007458 assert(false && "Invalid reference to overloaded function");
7459 return E->Retain();
Douglas Gregor904eed32008-11-10 20:40:00 +00007460}
7461
Douglas Gregor20093b42009-12-09 23:02:17 +00007462Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCall161755a2010-04-06 21:38:20 +00007463 DeclAccessPair Found,
Douglas Gregor20093b42009-12-09 23:02:17 +00007464 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +00007465 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +00007466}
7467
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007468} // end namespace clang