blob: abbf3933486cb6f736d591dbc3d39a78a49dc5e4 [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 Gregorcb7de522008-11-26 23:31:11 +00001236 return ToType;
1237
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
Ted Kremenek6217b802009-07-29 21:53:49 +00001625 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1626 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001627 QualType FromPointeeType = FromPtrType->getPointeeType(),
1628 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001629
Douglas Gregor5fccd362010-03-03 23:55:11 +00001630 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1631 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001632 // We must have a derived-to-base conversion. Check an
1633 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001634 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1635 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001636 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001637 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001638 return true;
1639
1640 // The conversion was successful.
1641 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001642 }
1643 }
Mike Stump1eb44332009-09-09 15:08:12 +00001644 if (const ObjCObjectPointerType *FromPtrType =
John McCall183700f2009-09-21 23:43:11 +00001645 FromType->getAs<ObjCObjectPointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001646 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00001647 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001648 // Objective-C++ conversions are always okay.
1649 // FIXME: We should have a different class of conversions for the
1650 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001651 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001652 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001653
Steve Naroff14108da2009-07-10 23:34:53 +00001654 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001655 return false;
1656}
1657
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001658/// IsMemberPointerConversion - Determines whether the conversion of the
1659/// expression From, which has the (possibly adjusted) type FromType, can be
1660/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1661/// If so, returns true and places the converted type (that might differ from
1662/// ToType in its cv-qualifiers at some level) into ConvertedType.
1663bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregorce940492009-09-25 04:25:58 +00001664 QualType ToType,
1665 bool InOverloadResolution,
1666 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001667 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001668 if (!ToTypePtr)
1669 return false;
1670
1671 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00001672 if (From->isNullPointerConstant(Context,
1673 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1674 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001675 ConvertedType = ToType;
1676 return true;
1677 }
1678
1679 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001680 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001681 if (!FromTypePtr)
1682 return false;
1683
1684 // A pointer to member of B can be converted to a pointer to member of D,
1685 // where D is derived from B (C++ 4.11p2).
1686 QualType FromClass(FromTypePtr->getClass(), 0);
1687 QualType ToClass(ToTypePtr->getClass(), 0);
1688 // FIXME: What happens when these are dependent? Is this function even called?
1689
1690 if (IsDerivedFrom(ToClass, FromClass)) {
1691 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1692 ToClass.getTypePtr());
1693 return true;
1694 }
1695
1696 return false;
1697}
Douglas Gregor43c79c22009-12-09 00:47:37 +00001698
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001699/// CheckMemberPointerConversion - Check the member pointer conversion from the
1700/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00001701/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001702/// for which IsMemberPointerConversion has already returned true. It returns
1703/// true and produces a diagnostic if there was an error, or returns false
1704/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001705bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001706 CastExpr::CastKind &Kind,
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001707 CXXBaseSpecifierArray &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001708 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001709 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001710 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001711 if (!FromPtrType) {
1712 // This must be a null pointer to member pointer conversion
Douglas Gregorce940492009-09-25 04:25:58 +00001713 assert(From->isNullPointerConstant(Context,
1714 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001715 "Expr must be null pointer constant!");
1716 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001717 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001718 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001719
Ted Kremenek6217b802009-07-29 21:53:49 +00001720 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001721 assert(ToPtrType && "No member pointer cast has a target type "
1722 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001723
Sebastian Redl21593ac2009-01-28 18:33:18 +00001724 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1725 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001726
Sebastian Redl21593ac2009-01-28 18:33:18 +00001727 // FIXME: What about dependent types?
1728 assert(FromClass->isRecordType() && "Pointer into non-class.");
1729 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001730
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001731 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001732 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00001733 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1734 assert(DerivationOkay &&
1735 "Should not have been called if derivation isn't OK.");
1736 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001737
Sebastian Redl21593ac2009-01-28 18:33:18 +00001738 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1739 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001740 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1741 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1742 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1743 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001744 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001745
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001746 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001747 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1748 << FromClass << ToClass << QualType(VBase, 0)
1749 << From->getSourceRange();
1750 return true;
1751 }
1752
John McCall6b2accb2010-02-10 09:31:12 +00001753 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00001754 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1755 Paths.front(),
1756 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00001757
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001758 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001759 BuildBasePathArray(Paths, BasePath);
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001760 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001761 return false;
1762}
1763
Douglas Gregor98cd5992008-10-21 23:43:52 +00001764/// IsQualificationConversion - Determines whether the conversion from
1765/// an rvalue of type FromType to ToType is a qualification conversion
1766/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001767bool
1768Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001769 FromType = Context.getCanonicalType(FromType);
1770 ToType = Context.getCanonicalType(ToType);
1771
1772 // If FromType and ToType are the same type, this is not a
1773 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00001774 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00001775 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001776
Douglas Gregor98cd5992008-10-21 23:43:52 +00001777 // (C++ 4.4p4):
1778 // A conversion can add cv-qualifiers at levels other than the first
1779 // in multi-level pointers, subject to the following rules: [...]
1780 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001781 bool UnwrappedAnyPointer = false;
Douglas Gregor57373262008-10-22 14:17:15 +00001782 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001783 // Within each iteration of the loop, we check the qualifiers to
1784 // determine if this still looks like a qualification
1785 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001786 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001787 // until there are no more pointers or pointers-to-members left to
1788 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001789 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001790
1791 // -- for every j > 0, if const is in cv 1,j then const is in cv
1792 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001793 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001794 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001795
Douglas Gregor98cd5992008-10-21 23:43:52 +00001796 // -- if the cv 1,j and cv 2,j are different, then const is in
1797 // every cv for 0 < k < j.
1798 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001799 && !PreviousToQualsIncludeConst)
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 // Keep track of whether all prior cv-qualifiers in the "to" type
1803 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00001804 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00001805 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001806 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001807
1808 // We are left with FromType and ToType being the pointee types
1809 // after unwrapping the original FromType and ToType the same number
1810 // of types. If we unwrapped any pointers, and if FromType and
1811 // ToType have the same unqualified type (since we checked
1812 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001813 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00001814}
1815
Douglas Gregor734d9862009-01-30 23:27:23 +00001816/// Determines whether there is a user-defined conversion sequence
1817/// (C++ [over.ics.user]) that converts expression From to the type
1818/// ToType. If such a conversion exists, User will contain the
1819/// user-defined conversion sequence that performs such a conversion
1820/// and this routine will return true. Otherwise, this routine returns
1821/// false and User is unspecified.
1822///
Douglas Gregor734d9862009-01-30 23:27:23 +00001823/// \param AllowExplicit true if the conversion should consider C++0x
1824/// "explicit" conversion functions as well as non-explicit conversion
1825/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor20093b42009-12-09 23:02:17 +00001826OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1827 UserDefinedConversionSequence& User,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001828 OverloadCandidateSet& CandidateSet,
1829 bool AllowExplicit) {
1830 // Whether we will only visit constructors.
1831 bool ConstructorsOnly = false;
1832
1833 // If the type we are conversion to is a class type, enumerate its
1834 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00001835 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001836 // C++ [over.match.ctor]p1:
1837 // When objects of class type are direct-initialized (8.5), or
1838 // copy-initialized from an expression of the same or a
1839 // derived class type (8.5), overload resolution selects the
1840 // constructor. [...] For copy-initialization, the candidate
1841 // functions are all the converting constructors (12.3.1) of
1842 // that class. The argument list is the expression-list within
1843 // the parentheses of the initializer.
1844 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1845 (From->getType()->getAs<RecordType>() &&
1846 IsDerivedFrom(From->getType(), ToType)))
1847 ConstructorsOnly = true;
1848
Douglas Gregor393896f2009-11-05 13:06:35 +00001849 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1850 // We're not going to find any constructors.
1851 } else if (CXXRecordDecl *ToRecordDecl
1852 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00001853 DeclarationName ConstructorName
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001854 = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001855 Context.getCanonicalType(ToType).getUnqualifiedType());
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001856 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump1eb44332009-09-09 15:08:12 +00001857 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001858 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001859 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00001860 NamedDecl *D = *Con;
1861 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1862
Douglas Gregordec06662009-08-21 18:42:58 +00001863 // Find the constructor (which may be a template).
1864 CXXConstructorDecl *Constructor = 0;
1865 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00001866 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00001867 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00001868 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00001869 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1870 else
John McCall9aa472c2010-03-19 07:35:19 +00001871 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001872
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00001873 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00001874 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001875 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00001876 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001877 /*ExplicitArgs*/ 0,
John McCalld5532b62009-11-23 01:53:49 +00001878 &From, 1, CandidateSet,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001879 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00001880 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001881 // Allow one user-defined conversion when user specifies a
1882 // From->ToType conversion via an static cast (c-style, etc).
John McCall9aa472c2010-03-19 07:35:19 +00001883 AddOverloadCandidate(Constructor, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001884 &From, 1, CandidateSet,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001885 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00001886 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001887 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001888 }
1889 }
1890
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001891 // Enumerate conversion functions, if we're allowed to.
1892 if (ConstructorsOnly) {
Mike Stump1eb44332009-09-09 15:08:12 +00001893 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001894 PDiag(0) << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00001895 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00001896 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001897 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001898 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001899 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1900 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00001901 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00001902 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001903 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001904 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00001905 DeclAccessPair FoundDecl = I.getPair();
1906 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00001907 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1908 if (isa<UsingShadowDecl>(D))
1909 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1910
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001911 CXXConversionDecl *Conv;
1912 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00001913 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1914 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001915 else
John McCall32daa422010-03-31 01:36:47 +00001916 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001917
1918 if (AllowExplicit || !Conv->isExplicit()) {
1919 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00001920 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001921 ActingContext, From, ToType,
1922 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001923 else
John McCall9aa472c2010-03-19 07:35:19 +00001924 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCall86820f52010-01-26 01:37:31 +00001925 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001926 }
1927 }
1928 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001929 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001930
1931 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001932 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001933 case OR_Success:
1934 // Record the standard conversion we used and the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00001935 if (CXXConstructorDecl *Constructor
Douglas Gregor60d62c22008-10-31 16:23:19 +00001936 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1937 // C++ [over.ics.user]p1:
1938 // If the user-defined conversion is specified by a
1939 // constructor (12.3.1), the initial standard conversion
1940 // sequence converts the source type to the type required by
1941 // the argument of the constructor.
1942 //
Douglas Gregor60d62c22008-10-31 16:23:19 +00001943 QualType ThisType = Constructor->getThisType(Context);
John McCall1d318332010-01-12 00:44:57 +00001944 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001945 User.EllipsisConversion = true;
1946 else {
1947 User.Before = Best->Conversions[0].Standard;
1948 User.EllipsisConversion = false;
1949 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001950 User.ConversionFunction = Constructor;
1951 User.After.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +00001952 User.After.setFromType(
1953 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregorad323a82010-01-27 03:51:04 +00001954 User.After.setAllToTypes(ToType);
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001955 return OR_Success;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001956 } else if (CXXConversionDecl *Conversion
1957 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1958 // C++ [over.ics.user]p1:
1959 //
1960 // [...] If the user-defined conversion is specified by a
1961 // conversion function (12.3.2), the initial standard
1962 // conversion sequence converts the source type to the
1963 // implicit object parameter of the conversion function.
1964 User.Before = Best->Conversions[0].Standard;
1965 User.ConversionFunction = Conversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001966 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00001967
1968 // C++ [over.ics.user]p2:
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001969 // The second standard conversion sequence converts the
1970 // result of the user-defined conversion to the target type
1971 // for the sequence. Since an implicit conversion sequence
1972 // is an initialization, the special rules for
1973 // initialization by user-defined conversion apply when
1974 // selecting the best user-defined conversion for a
1975 // user-defined conversion sequence (see 13.3.3 and
1976 // 13.3.3.1).
1977 User.After = Best->FinalConversion;
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001978 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001979 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001980 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001981 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001982 }
Mike Stump1eb44332009-09-09 15:08:12 +00001983
Douglas Gregor60d62c22008-10-31 16:23:19 +00001984 case OR_No_Viable_Function:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001985 return OR_No_Viable_Function;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00001986 case OR_Deleted:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001987 // No conversion here! We're done.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001988 return OR_Deleted;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001989
1990 case OR_Ambiguous:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001991 return OR_Ambiguous;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001992 }
1993
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001994 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00001995}
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001996
1997bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00001998Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00001999 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00002000 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002001 OverloadingResult OvResult =
2002 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002003 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002004 if (OvResult == OR_Ambiguous)
2005 Diag(From->getSourceRange().getBegin(),
2006 diag::err_typecheck_ambiguous_condition)
2007 << From->getType() << ToType << From->getSourceRange();
2008 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2009 Diag(From->getSourceRange().getBegin(),
2010 diag::err_typecheck_nonviable_condition)
2011 << From->getType() << ToType << From->getSourceRange();
2012 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002013 return false;
John McCallcbce6062010-01-12 07:18:19 +00002014 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002015 return true;
2016}
Douglas Gregor60d62c22008-10-31 16:23:19 +00002017
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002018/// CompareImplicitConversionSequences - Compare two implicit
2019/// conversion sequences to determine whether one is better than the
2020/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump1eb44332009-09-09 15:08:12 +00002021ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002022Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
2023 const ImplicitConversionSequence& ICS2)
2024{
2025 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2026 // conversion sequences (as defined in 13.3.3.1)
2027 // -- a standard conversion sequence (13.3.3.1.1) is a better
2028 // conversion sequence than a user-defined conversion sequence or
2029 // an ellipsis conversion sequence, and
2030 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2031 // conversion sequence than an ellipsis conversion sequence
2032 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002033 //
John McCall1d318332010-01-12 00:44:57 +00002034 // C++0x [over.best.ics]p10:
2035 // For the purpose of ranking implicit conversion sequences as
2036 // described in 13.3.3.2, the ambiguous conversion sequence is
2037 // treated as a user-defined sequence that is indistinguishable
2038 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002039 if (ICS1.getKindRank() < ICS2.getKindRank())
2040 return ImplicitConversionSequence::Better;
2041 else if (ICS2.getKindRank() < ICS1.getKindRank())
2042 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002043
Benjamin Kramerb6eee072010-04-18 12:05:54 +00002044 // The following checks require both conversion sequences to be of
2045 // the same kind.
2046 if (ICS1.getKind() != ICS2.getKind())
2047 return ImplicitConversionSequence::Indistinguishable;
2048
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002049 // Two implicit conversion sequences of the same form are
2050 // indistinguishable conversion sequences unless one of the
2051 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00002052 if (ICS1.isStandard())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002053 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00002054 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002055 // User-defined conversion sequence U1 is a better conversion
2056 // sequence than another user-defined conversion sequence U2 if
2057 // they contain the same user-defined conversion function or
2058 // constructor and if the second standard conversion sequence of
2059 // U1 is better than the second standard conversion sequence of
2060 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002061 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002062 ICS2.UserDefined.ConversionFunction)
2063 return CompareStandardConversionSequences(ICS1.UserDefined.After,
2064 ICS2.UserDefined.After);
2065 }
2066
2067 return ImplicitConversionSequence::Indistinguishable;
2068}
2069
Douglas Gregorad323a82010-01-27 03:51:04 +00002070// Per 13.3.3.2p3, compare the given standard conversion sequences to
2071// determine if one is a proper subset of the other.
2072static ImplicitConversionSequence::CompareKind
2073compareStandardConversionSubsets(ASTContext &Context,
2074 const StandardConversionSequence& SCS1,
2075 const StandardConversionSequence& SCS2) {
2076 ImplicitConversionSequence::CompareKind Result
2077 = ImplicitConversionSequence::Indistinguishable;
2078
2079 if (SCS1.Second != SCS2.Second) {
2080 if (SCS1.Second == ICK_Identity)
2081 Result = ImplicitConversionSequence::Better;
2082 else if (SCS2.Second == ICK_Identity)
2083 Result = ImplicitConversionSequence::Worse;
2084 else
2085 return ImplicitConversionSequence::Indistinguishable;
2086 } else if (!Context.hasSameType(SCS1.getToType(1), SCS2.getToType(1)))
2087 return ImplicitConversionSequence::Indistinguishable;
2088
2089 if (SCS1.Third == SCS2.Third) {
2090 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2091 : ImplicitConversionSequence::Indistinguishable;
2092 }
2093
2094 if (SCS1.Third == ICK_Identity)
2095 return Result == ImplicitConversionSequence::Worse
2096 ? ImplicitConversionSequence::Indistinguishable
2097 : ImplicitConversionSequence::Better;
2098
2099 if (SCS2.Third == ICK_Identity)
2100 return Result == ImplicitConversionSequence::Better
2101 ? ImplicitConversionSequence::Indistinguishable
2102 : ImplicitConversionSequence::Worse;
2103
2104 return ImplicitConversionSequence::Indistinguishable;
2105}
2106
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002107/// CompareStandardConversionSequences - Compare two standard
2108/// conversion sequences to determine whether one is better than the
2109/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002110ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002111Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
2112 const StandardConversionSequence& SCS2)
2113{
2114 // Standard conversion sequence S1 is a better conversion sequence
2115 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2116
2117 // -- S1 is a proper subsequence of S2 (comparing the conversion
2118 // sequences in the canonical form defined by 13.3.3.1.1,
2119 // excluding any Lvalue Transformation; the identity conversion
2120 // sequence is considered to be a subsequence of any
2121 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00002122 if (ImplicitConversionSequence::CompareKind CK
2123 = compareStandardConversionSubsets(Context, SCS1, SCS2))
2124 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002125
2126 // -- the rank of S1 is better than the rank of S2 (by the rules
2127 // defined below), or, if not that,
2128 ImplicitConversionRank Rank1 = SCS1.getRank();
2129 ImplicitConversionRank Rank2 = SCS2.getRank();
2130 if (Rank1 < Rank2)
2131 return ImplicitConversionSequence::Better;
2132 else if (Rank2 < Rank1)
2133 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002134
Douglas Gregor57373262008-10-22 14:17:15 +00002135 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2136 // are indistinguishable unless one of the following rules
2137 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00002138
Douglas Gregor57373262008-10-22 14:17:15 +00002139 // A conversion that is not a conversion of a pointer, or
2140 // pointer to member, to bool is better than another conversion
2141 // that is such a conversion.
2142 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2143 return SCS2.isPointerConversionToBool()
2144 ? ImplicitConversionSequence::Better
2145 : ImplicitConversionSequence::Worse;
2146
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002147 // C++ [over.ics.rank]p4b2:
2148 //
2149 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002150 // conversion of B* to A* is better than conversion of B* to
2151 // void*, and conversion of A* to void* is better than conversion
2152 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00002153 bool SCS1ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002154 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002155 bool SCS2ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002156 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002157 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2158 // Exactly one of the conversion sequences is a conversion to
2159 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002160 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2161 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002162 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2163 // Neither conversion sequence converts to a void pointer; compare
2164 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002165 if (ImplicitConversionSequence::CompareKind DerivedCK
2166 = CompareDerivedToBaseConversions(SCS1, SCS2))
2167 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002168 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2169 // Both conversion sequences are conversions to void
2170 // pointers. Compare the source types to determine if there's an
2171 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00002172 QualType FromType1 = SCS1.getFromType();
2173 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002174
2175 // Adjust the types we're converting from via the array-to-pointer
2176 // conversion, if we need to.
2177 if (SCS1.First == ICK_Array_To_Pointer)
2178 FromType1 = Context.getArrayDecayedType(FromType1);
2179 if (SCS2.First == ICK_Array_To_Pointer)
2180 FromType2 = Context.getArrayDecayedType(FromType2);
2181
Douglas Gregor01919692009-12-13 21:37:05 +00002182 QualType FromPointee1
2183 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2184 QualType FromPointee2
2185 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002186
Douglas Gregor01919692009-12-13 21:37:05 +00002187 if (IsDerivedFrom(FromPointee2, FromPointee1))
2188 return ImplicitConversionSequence::Better;
2189 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2190 return ImplicitConversionSequence::Worse;
2191
2192 // Objective-C++: If one interface is more specific than the
2193 // other, it is the better one.
John McCallc12c5bb2010-05-15 11:32:37 +00002194 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2195 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor01919692009-12-13 21:37:05 +00002196 if (FromIface1 && FromIface1) {
2197 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2198 return ImplicitConversionSequence::Better;
2199 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2200 return ImplicitConversionSequence::Worse;
2201 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002202 }
Douglas Gregor57373262008-10-22 14:17:15 +00002203
2204 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2205 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00002206 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00002207 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002208 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00002209
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002210 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002211 // C++0x [over.ics.rank]p3b4:
2212 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2213 // implicit object parameter of a non-static member function declared
2214 // without a ref-qualifier, and S1 binds an rvalue reference to an
2215 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00002216 // FIXME: We don't know if we're dealing with the implicit object parameter,
2217 // or if the member function in this case has a ref qualifier.
2218 // (Of course, we don't have ref qualifiers yet.)
2219 if (SCS1.RRefBinding != SCS2.RRefBinding)
2220 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2221 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002222
2223 // C++ [over.ics.rank]p3b4:
2224 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2225 // which the references refer are the same type except for
2226 // top-level cv-qualifiers, and the type to which the reference
2227 // initialized by S2 refers is more cv-qualified than the type
2228 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00002229 QualType T1 = SCS1.getToType(2);
2230 QualType T2 = SCS2.getToType(2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002231 T1 = Context.getCanonicalType(T1);
2232 T2 = Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002233 Qualifiers T1Quals, T2Quals;
2234 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2235 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2236 if (UnqualT1 == UnqualT2) {
2237 // If the type is an array type, promote the element qualifiers to the type
2238 // for comparison.
2239 if (isa<ArrayType>(T1) && T1Quals)
2240 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2241 if (isa<ArrayType>(T2) && T2Quals)
2242 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002243 if (T2.isMoreQualifiedThan(T1))
2244 return ImplicitConversionSequence::Better;
2245 else if (T1.isMoreQualifiedThan(T2))
2246 return ImplicitConversionSequence::Worse;
2247 }
2248 }
Douglas Gregor57373262008-10-22 14:17:15 +00002249
2250 return ImplicitConversionSequence::Indistinguishable;
2251}
2252
2253/// CompareQualificationConversions - Compares two standard conversion
2254/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00002255/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2256ImplicitConversionSequence::CompareKind
Douglas Gregor57373262008-10-22 14:17:15 +00002257Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump1eb44332009-09-09 15:08:12 +00002258 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00002259 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00002260 // -- S1 and S2 differ only in their qualification conversion and
2261 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2262 // cv-qualification signature of type T1 is a proper subset of
2263 // the cv-qualification signature of type T2, and S1 is not the
2264 // deprecated string literal array-to-pointer conversion (4.2).
2265 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2266 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2267 return ImplicitConversionSequence::Indistinguishable;
2268
2269 // FIXME: the example in the standard doesn't use a qualification
2270 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00002271 QualType T1 = SCS1.getToType(2);
2272 QualType T2 = SCS2.getToType(2);
Douglas Gregor57373262008-10-22 14:17:15 +00002273 T1 = Context.getCanonicalType(T1);
2274 T2 = Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002275 Qualifiers T1Quals, T2Quals;
2276 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2277 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00002278
2279 // If the types are the same, we won't learn anything by unwrapped
2280 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00002281 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00002282 return ImplicitConversionSequence::Indistinguishable;
2283
Chandler Carruth28e318c2009-12-29 07:16:59 +00002284 // If the type is an array type, promote the element qualifiers to the type
2285 // for comparison.
2286 if (isa<ArrayType>(T1) && T1Quals)
2287 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2288 if (isa<ArrayType>(T2) && T2Quals)
2289 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2290
Mike Stump1eb44332009-09-09 15:08:12 +00002291 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00002292 = ImplicitConversionSequence::Indistinguishable;
2293 while (UnwrapSimilarPointerTypes(T1, T2)) {
2294 // Within each iteration of the loop, we check the qualifiers to
2295 // determine if this still looks like a qualification
2296 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002297 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00002298 // until there are no more pointers or pointers-to-members left
2299 // to unwrap. This essentially mimics what
2300 // IsQualificationConversion does, but here we're checking for a
2301 // strict subset of qualifiers.
2302 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2303 // The qualifiers are the same, so this doesn't tell us anything
2304 // about how the sequences rank.
2305 ;
2306 else if (T2.isMoreQualifiedThan(T1)) {
2307 // T1 has fewer qualifiers, so it could be the better sequence.
2308 if (Result == ImplicitConversionSequence::Worse)
2309 // Neither has qualifiers that are a subset of the other's
2310 // qualifiers.
2311 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002312
Douglas Gregor57373262008-10-22 14:17:15 +00002313 Result = ImplicitConversionSequence::Better;
2314 } else if (T1.isMoreQualifiedThan(T2)) {
2315 // T2 has fewer qualifiers, so it could be the better sequence.
2316 if (Result == ImplicitConversionSequence::Better)
2317 // Neither has qualifiers that are a subset of the other's
2318 // qualifiers.
2319 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002320
Douglas Gregor57373262008-10-22 14:17:15 +00002321 Result = ImplicitConversionSequence::Worse;
2322 } else {
2323 // Qualifiers are disjoint.
2324 return ImplicitConversionSequence::Indistinguishable;
2325 }
2326
2327 // If the types after this point are equivalent, we're done.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002328 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00002329 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002330 }
2331
Douglas Gregor57373262008-10-22 14:17:15 +00002332 // Check that the winning standard conversion sequence isn't using
2333 // the deprecated string literal array to pointer conversion.
2334 switch (Result) {
2335 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00002336 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002337 Result = ImplicitConversionSequence::Indistinguishable;
2338 break;
2339
2340 case ImplicitConversionSequence::Indistinguishable:
2341 break;
2342
2343 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00002344 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002345 Result = ImplicitConversionSequence::Indistinguishable;
2346 break;
2347 }
2348
2349 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002350}
2351
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002352/// CompareDerivedToBaseConversions - Compares two standard conversion
2353/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00002354/// various kinds of derived-to-base conversions (C++
2355/// [over.ics.rank]p4b3). As part of these checks, we also look at
2356/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002357ImplicitConversionSequence::CompareKind
2358Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2359 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00002360 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002361 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00002362 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002363 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002364
2365 // Adjust the types we're converting from via the array-to-pointer
2366 // conversion, if we need to.
2367 if (SCS1.First == ICK_Array_To_Pointer)
2368 FromType1 = Context.getArrayDecayedType(FromType1);
2369 if (SCS2.First == ICK_Array_To_Pointer)
2370 FromType2 = Context.getArrayDecayedType(FromType2);
2371
2372 // Canonicalize all of the types.
2373 FromType1 = Context.getCanonicalType(FromType1);
2374 ToType1 = Context.getCanonicalType(ToType1);
2375 FromType2 = Context.getCanonicalType(FromType2);
2376 ToType2 = Context.getCanonicalType(ToType2);
2377
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002378 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002379 //
2380 // If class B is derived directly or indirectly from class A and
2381 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002382 //
2383 // For Objective-C, we let A, B, and C also be Objective-C
2384 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002385
2386 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00002387 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00002388 SCS2.Second == ICK_Pointer_Conversion &&
2389 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2390 FromType1->isPointerType() && FromType2->isPointerType() &&
2391 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002392 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002393 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002394 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002395 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002396 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002397 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002398 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002399 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002400
John McCallc12c5bb2010-05-15 11:32:37 +00002401 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2402 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2403 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2404 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002405
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002406 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002407 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2408 if (IsDerivedFrom(ToPointee1, ToPointee2))
2409 return ImplicitConversionSequence::Better;
2410 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2411 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00002412
2413 if (ToIface1 && ToIface2) {
2414 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2415 return ImplicitConversionSequence::Better;
2416 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2417 return ImplicitConversionSequence::Worse;
2418 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002419 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002420
2421 // -- conversion of B* to A* is better than conversion of C* to A*,
2422 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2423 if (IsDerivedFrom(FromPointee2, FromPointee1))
2424 return ImplicitConversionSequence::Better;
2425 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2426 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00002427
Douglas Gregorcb7de522008-11-26 23:31:11 +00002428 if (FromIface1 && FromIface2) {
2429 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2430 return ImplicitConversionSequence::Better;
2431 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2432 return ImplicitConversionSequence::Worse;
2433 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002434 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002435 }
2436
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002437 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002438 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2439 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2440 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2441 const MemberPointerType * FromMemPointer1 =
2442 FromType1->getAs<MemberPointerType>();
2443 const MemberPointerType * ToMemPointer1 =
2444 ToType1->getAs<MemberPointerType>();
2445 const MemberPointerType * FromMemPointer2 =
2446 FromType2->getAs<MemberPointerType>();
2447 const MemberPointerType * ToMemPointer2 =
2448 ToType2->getAs<MemberPointerType>();
2449 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2450 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2451 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2452 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2453 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2454 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2455 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2456 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002457 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002458 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2459 if (IsDerivedFrom(ToPointee1, ToPointee2))
2460 return ImplicitConversionSequence::Worse;
2461 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2462 return ImplicitConversionSequence::Better;
2463 }
2464 // conversion of B::* to C::* is better than conversion of A::* to C::*
2465 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2466 if (IsDerivedFrom(FromPointee1, FromPointee2))
2467 return ImplicitConversionSequence::Better;
2468 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2469 return ImplicitConversionSequence::Worse;
2470 }
2471 }
2472
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002473 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002474 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00002475 // -- binding of an expression of type C to a reference of type
2476 // B& is better than binding an expression of type C to a
2477 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002478 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2479 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002480 if (IsDerivedFrom(ToType1, ToType2))
2481 return ImplicitConversionSequence::Better;
2482 else if (IsDerivedFrom(ToType2, ToType1))
2483 return ImplicitConversionSequence::Worse;
2484 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002485
Douglas Gregor225c41e2008-11-03 19:09:14 +00002486 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00002487 // -- binding of an expression of type B to a reference of type
2488 // A& is better than binding an expression of type C to a
2489 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002490 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2491 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002492 if (IsDerivedFrom(FromType2, FromType1))
2493 return ImplicitConversionSequence::Better;
2494 else if (IsDerivedFrom(FromType1, FromType2))
2495 return ImplicitConversionSequence::Worse;
2496 }
2497 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002498
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002499 return ImplicitConversionSequence::Indistinguishable;
2500}
2501
Douglas Gregorabe183d2010-04-13 16:31:36 +00002502/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2503/// determine whether they are reference-related,
2504/// reference-compatible, reference-compatible with added
2505/// qualification, or incompatible, for use in C++ initialization by
2506/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2507/// type, and the first type (T1) is the pointee type of the reference
2508/// type being initialized.
2509Sema::ReferenceCompareResult
2510Sema::CompareReferenceRelationship(SourceLocation Loc,
2511 QualType OrigT1, QualType OrigT2,
2512 bool& DerivedToBase) {
2513 assert(!OrigT1->isReferenceType() &&
2514 "T1 must be the pointee type of the reference type");
2515 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2516
2517 QualType T1 = Context.getCanonicalType(OrigT1);
2518 QualType T2 = Context.getCanonicalType(OrigT2);
2519 Qualifiers T1Quals, T2Quals;
2520 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2521 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2522
2523 // C++ [dcl.init.ref]p4:
2524 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2525 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2526 // T1 is a base class of T2.
2527 if (UnqualT1 == UnqualT2)
2528 DerivedToBase = false;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002529 else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00002530 IsDerivedFrom(UnqualT2, UnqualT1))
2531 DerivedToBase = true;
2532 else
2533 return Ref_Incompatible;
2534
2535 // At this point, we know that T1 and T2 are reference-related (at
2536 // least).
2537
2538 // If the type is an array type, promote the element qualifiers to the type
2539 // for comparison.
2540 if (isa<ArrayType>(T1) && T1Quals)
2541 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2542 if (isa<ArrayType>(T2) && T2Quals)
2543 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2544
2545 // C++ [dcl.init.ref]p4:
2546 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2547 // reference-related to T2 and cv1 is the same cv-qualification
2548 // as, or greater cv-qualification than, cv2. For purposes of
2549 // overload resolution, cases for which cv1 is greater
2550 // cv-qualification than cv2 are identified as
2551 // reference-compatible with added qualification (see 13.3.3.2).
2552 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2553 return Ref_Compatible;
2554 else if (T1.isMoreQualifiedThan(T2))
2555 return Ref_Compatible_With_Added_Qualification;
2556 else
2557 return Ref_Related;
2558}
2559
2560/// \brief Compute an implicit conversion sequence for reference
2561/// initialization.
2562static ImplicitConversionSequence
2563TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2564 SourceLocation DeclLoc,
2565 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00002566 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002567 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2568
2569 // Most paths end in a failed conversion.
2570 ImplicitConversionSequence ICS;
2571 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2572
2573 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2574 QualType T2 = Init->getType();
2575
2576 // If the initializer is the address of an overloaded function, try
2577 // to resolve the overloaded function. If all goes well, T2 is the
2578 // type of the resulting function.
2579 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2580 DeclAccessPair Found;
2581 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2582 false, Found))
2583 T2 = Fn->getType();
2584 }
2585
2586 // Compute some basic properties of the types and the initializer.
2587 bool isRValRef = DeclType->isRValueReferenceType();
2588 bool DerivedToBase = false;
Douglas Gregor23ef6c02010-04-16 17:45:54 +00002589 Expr::isLvalueResult InitLvalue = Init->isLvalue(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002590 Sema::ReferenceCompareResult RefRelationship
2591 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
2592
Douglas Gregorabe183d2010-04-13 16:31:36 +00002593
2594 // C++ [over.ics.ref]p3:
2595 // Except for an implicit object parameter, for which see 13.3.1,
2596 // a standard conversion sequence cannot be formed if it requires
2597 // binding an lvalue reference to non-const to an rvalue or
2598 // binding an rvalue reference to an lvalue.
Douglas Gregor66821b52010-04-18 09:22:00 +00002599 //
2600 // FIXME: DPG doesn't trust this code. It seems far too early to
2601 // abort because of a binding of an rvalue reference to an lvalue.
Douglas Gregorabe183d2010-04-13 16:31:36 +00002602 if (isRValRef && InitLvalue == Expr::LV_Valid)
2603 return ICS;
2604
Douglas Gregor66821b52010-04-18 09:22:00 +00002605 // C++0x [dcl.init.ref]p16:
2606 // A reference to type "cv1 T1" is initialized by an expression
2607 // of type "cv2 T2" as follows:
2608
2609 // -- If the initializer expression
Douglas Gregorabe183d2010-04-13 16:31:36 +00002610 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2611 // reference-compatible with "cv2 T2," or
2612 //
2613 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2614 if (InitLvalue == Expr::LV_Valid &&
2615 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2616 // C++ [over.ics.ref]p1:
2617 // When a parameter of reference type binds directly (8.5.3)
2618 // to an argument expression, the implicit conversion sequence
2619 // is the identity conversion, unless the argument expression
2620 // has a type that is a derived class of the parameter type,
2621 // in which case the implicit conversion sequence is a
2622 // derived-to-base Conversion (13.3.3.1).
2623 ICS.setStandard();
2624 ICS.Standard.First = ICK_Identity;
2625 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2626 ICS.Standard.Third = ICK_Identity;
2627 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2628 ICS.Standard.setToType(0, T2);
2629 ICS.Standard.setToType(1, T1);
2630 ICS.Standard.setToType(2, T1);
2631 ICS.Standard.ReferenceBinding = true;
2632 ICS.Standard.DirectBinding = true;
2633 ICS.Standard.RRefBinding = false;
2634 ICS.Standard.CopyConstructor = 0;
2635
2636 // Nothing more to do: the inaccessibility/ambiguity check for
2637 // derived-to-base conversions is suppressed when we're
2638 // computing the implicit conversion sequence (C++
2639 // [over.best.ics]p2).
2640 return ICS;
2641 }
2642
2643 // -- has a class type (i.e., T2 is a class type), where T1 is
2644 // not reference-related to T2, and can be implicitly
2645 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2646 // is reference-compatible with "cv3 T3" 92) (this
2647 // conversion is selected by enumerating the applicable
2648 // conversion functions (13.3.1.6) and choosing the best
2649 // one through overload resolution (13.3)),
2650 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
2651 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2652 RefRelationship == Sema::Ref_Incompatible) {
2653 CXXRecordDecl *T2RecordDecl
2654 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2655
2656 OverloadCandidateSet CandidateSet(DeclLoc);
2657 const UnresolvedSetImpl *Conversions
2658 = T2RecordDecl->getVisibleConversionFunctions();
2659 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2660 E = Conversions->end(); I != E; ++I) {
2661 NamedDecl *D = *I;
2662 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2663 if (isa<UsingShadowDecl>(D))
2664 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2665
2666 FunctionTemplateDecl *ConvTemplate
2667 = dyn_cast<FunctionTemplateDecl>(D);
2668 CXXConversionDecl *Conv;
2669 if (ConvTemplate)
2670 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2671 else
2672 Conv = cast<CXXConversionDecl>(D);
2673
2674 // If the conversion function doesn't return a reference type,
2675 // it can't be considered for this conversion.
2676 if (Conv->getConversionType()->isLValueReferenceType() &&
2677 (AllowExplicit || !Conv->isExplicit())) {
2678 if (ConvTemplate)
2679 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2680 Init, DeclType, CandidateSet);
2681 else
2682 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2683 DeclType, CandidateSet);
2684 }
2685 }
2686
2687 OverloadCandidateSet::iterator Best;
2688 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2689 case OR_Success:
2690 // C++ [over.ics.ref]p1:
2691 //
2692 // [...] If the parameter binds directly to the result of
2693 // applying a conversion function to the argument
2694 // expression, the implicit conversion sequence is a
2695 // user-defined conversion sequence (13.3.3.1.2), with the
2696 // second standard conversion sequence either an identity
2697 // conversion or, if the conversion function returns an
2698 // entity of a type that is a derived class of the parameter
2699 // type, a derived-to-base Conversion.
2700 if (!Best->FinalConversion.DirectBinding)
2701 break;
2702
2703 ICS.setUserDefined();
2704 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2705 ICS.UserDefined.After = Best->FinalConversion;
2706 ICS.UserDefined.ConversionFunction = Best->Function;
2707 ICS.UserDefined.EllipsisConversion = false;
2708 assert(ICS.UserDefined.After.ReferenceBinding &&
2709 ICS.UserDefined.After.DirectBinding &&
2710 "Expected a direct reference binding!");
2711 return ICS;
2712
2713 case OR_Ambiguous:
2714 ICS.setAmbiguous();
2715 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2716 Cand != CandidateSet.end(); ++Cand)
2717 if (Cand->Viable)
2718 ICS.Ambiguous.addConversion(Cand->Function);
2719 return ICS;
2720
2721 case OR_No_Viable_Function:
2722 case OR_Deleted:
2723 // There was no suitable conversion, or we found a deleted
2724 // conversion; continue with other checks.
2725 break;
2726 }
2727 }
2728
2729 // -- Otherwise, the reference shall be to a non-volatile const
2730 // type (i.e., cv1 shall be const), or the reference shall be an
2731 // rvalue reference and the initializer expression shall be an rvalue.
Douglas Gregor66821b52010-04-18 09:22:00 +00002732 //
2733 // We actually handle one oddity of C++ [over.ics.ref] at this
2734 // point, which is that, due to p2 (which short-circuits reference
2735 // binding by only attempting a simple conversion for non-direct
2736 // bindings) and p3's strange wording, we allow a const volatile
2737 // reference to bind to an rvalue. Hence the check for the presence
2738 // of "const" rather than checking for "const" being the only
2739 // qualifier.
2740 if (!isRValRef && !T1.isConstQualified())
Douglas Gregorabe183d2010-04-13 16:31:36 +00002741 return ICS;
2742
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002743 // -- if T2 is a class type and
2744 // -- the initializer expression is an rvalue and "cv1 T1"
2745 // is reference-compatible with "cv2 T2," or
Douglas Gregorabe183d2010-04-13 16:31:36 +00002746 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002747 // -- T1 is not reference-related to T2 and the initializer
2748 // expression can be implicitly converted to an rvalue
2749 // of type "cv3 T3" (this conversion is selected by
2750 // enumerating the applicable conversion functions
2751 // (13.3.1.6) and choosing the best one through overload
2752 // resolution (13.3)),
Douglas Gregorabe183d2010-04-13 16:31:36 +00002753 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002754 // then the reference is bound to the initializer
2755 // expression rvalue in the first case and to the object
2756 // that is the result of the conversion in the second case
2757 // (or, in either case, to the appropriate base class
2758 // subobject of the object).
Douglas Gregorabe183d2010-04-13 16:31:36 +00002759 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002760 // We're only checking the first case here, which is a direct
2761 // binding in C++0x but not in C++03.
Douglas Gregorabe183d2010-04-13 16:31:36 +00002762 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
2763 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2764 ICS.setStandard();
2765 ICS.Standard.First = ICK_Identity;
2766 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2767 ICS.Standard.Third = ICK_Identity;
2768 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2769 ICS.Standard.setToType(0, T2);
2770 ICS.Standard.setToType(1, T1);
2771 ICS.Standard.setToType(2, T1);
2772 ICS.Standard.ReferenceBinding = true;
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002773 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002774 ICS.Standard.RRefBinding = isRValRef;
2775 ICS.Standard.CopyConstructor = 0;
2776 return ICS;
2777 }
2778
2779 // -- Otherwise, a temporary of type "cv1 T1" is created and
2780 // initialized from the initializer expression using the
2781 // rules for a non-reference copy initialization (8.5). The
2782 // reference is then bound to the temporary. If T1 is
2783 // reference-related to T2, cv1 must be the same
2784 // cv-qualification as, or greater cv-qualification than,
2785 // cv2; otherwise, the program is ill-formed.
2786 if (RefRelationship == Sema::Ref_Related) {
2787 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2788 // we would be reference-compatible or reference-compatible with
2789 // added qualification. But that wasn't the case, so the reference
2790 // initialization fails.
2791 return ICS;
2792 }
2793
2794 // If at least one of the types is a class type, the types are not
2795 // related, and we aren't allowed any user conversions, the
2796 // reference binding fails. This case is important for breaking
2797 // recursion, since TryImplicitConversion below will attempt to
2798 // create a temporary through the use of a copy constructor.
2799 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2800 (T1->isRecordType() || T2->isRecordType()))
2801 return ICS;
2802
2803 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00002804 // When a parameter of reference type is not bound directly to
2805 // an argument expression, the conversion sequence is the one
2806 // required to convert the argument expression to the
2807 // underlying type of the reference according to
2808 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2809 // to copy-initializing a temporary of the underlying type with
2810 // the argument expression. Any difference in top-level
2811 // cv-qualification is subsumed by the initialization itself
2812 // and does not constitute a conversion.
2813 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2814 /*AllowExplicit=*/false,
Douglas Gregorabe183d2010-04-13 16:31:36 +00002815 /*InOverloadResolution=*/false);
2816
2817 // Of course, that's still a reference binding.
2818 if (ICS.isStandard()) {
2819 ICS.Standard.ReferenceBinding = true;
2820 ICS.Standard.RRefBinding = isRValRef;
2821 } else if (ICS.isUserDefined()) {
2822 ICS.UserDefined.After.ReferenceBinding = true;
2823 ICS.UserDefined.After.RRefBinding = isRValRef;
2824 }
2825 return ICS;
2826}
2827
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002828/// TryCopyInitialization - Try to copy-initialize a value of type
2829/// ToType from the expression From. Return the implicit conversion
2830/// sequence required to pass this argument, which may be a bad
2831/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00002832/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00002833/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00002834static ImplicitConversionSequence
2835TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregorb7f9e6a2010-04-16 17:53:55 +00002836 bool SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00002837 bool InOverloadResolution) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002838 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00002839 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00002840 /*FIXME:*/From->getLocStart(),
2841 SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00002842 /*AllowExplicit=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002843
Douglas Gregor74eb6582010-04-16 17:51:22 +00002844 return S.TryImplicitConversion(From, ToType,
2845 SuppressUserConversions,
2846 /*AllowExplicit=*/false,
Douglas Gregor74eb6582010-04-16 17:51:22 +00002847 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002848}
2849
Douglas Gregor96176b32008-11-18 23:14:02 +00002850/// TryObjectArgumentInitialization - Try to initialize the object
2851/// parameter of the given member function (@c Method) from the
2852/// expression @p From.
2853ImplicitConversionSequence
John McCall651f3ee2010-01-14 03:28:57 +00002854Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall701c89e2009-12-03 04:06:58 +00002855 CXXMethodDecl *Method,
2856 CXXRecordDecl *ActingContext) {
2857 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002858 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2859 // const volatile object.
2860 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2861 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2862 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00002863
2864 // Set up the conversion sequence as a "bad" conversion, to allow us
2865 // to exit early.
2866 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00002867
2868 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00002869 QualType FromType = OrigFromType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002870 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00002871 FromType = PT->getPointeeType();
2872
2873 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002874
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002875 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor96176b32008-11-18 23:14:02 +00002876 // where X is the class of which the function is a member
2877 // (C++ [over.match.funcs]p4). However, when finding an implicit
2878 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00002879 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00002880 // (C++ [over.match.funcs]p5). We perform a simplified version of
2881 // reference binding here, that allows class rvalues to bind to
2882 // non-constant references.
2883
2884 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2885 // with the implicit object parameter (C++ [over.match.funcs]p5).
2886 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00002887 if (ImplicitParamType.getCVRQualifiers()
2888 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00002889 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00002890 ICS.setBad(BadConversionSequence::bad_qualifiers,
2891 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002892 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00002893 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002894
2895 // Check that we have either the same type or a derived type. It
2896 // affects the conversion rank.
2897 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00002898 ImplicitConversionKind SecondKind;
2899 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2900 SecondKind = ICK_Identity;
2901 } else if (IsDerivedFrom(FromType, ClassType))
2902 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00002903 else {
John McCallb1bdc622010-02-25 01:37:24 +00002904 ICS.setBad(BadConversionSequence::unrelated_class,
2905 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002906 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00002907 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002908
2909 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00002910 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00002911 ICS.Standard.setAsIdentityConversion();
2912 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00002913 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00002914 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002915 ICS.Standard.ReferenceBinding = true;
2916 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00002917 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00002918 return ICS;
2919}
2920
2921/// PerformObjectArgumentInitialization - Perform initialization of
2922/// the implicit object parameter for the given Method with the given
2923/// expression.
2924bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00002925Sema::PerformObjectArgumentInitialization(Expr *&From,
2926 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00002927 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00002928 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002929 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00002930 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00002931 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00002932
Ted Kremenek6217b802009-07-29 21:53:49 +00002933 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00002934 FromRecordType = PT->getPointeeType();
2935 DestType = Method->getThisType(Context);
2936 } else {
2937 FromRecordType = From->getType();
2938 DestType = ImplicitParamRecordType;
2939 }
2940
John McCall701c89e2009-12-03 04:06:58 +00002941 // Note that we always use the true parent context when performing
2942 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00002943 ImplicitConversionSequence ICS
John McCall701c89e2009-12-03 04:06:58 +00002944 = TryObjectArgumentInitialization(From->getType(), Method,
2945 Method->getParent());
John McCall1d318332010-01-12 00:44:57 +00002946 if (ICS.isBad())
Douglas Gregor96176b32008-11-18 23:14:02 +00002947 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00002948 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00002949 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00002950
Douglas Gregor5fccd362010-03-03 23:55:11 +00002951 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall6bb80172010-03-30 21:47:33 +00002952 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor96176b32008-11-18 23:14:02 +00002953
Douglas Gregor5fccd362010-03-03 23:55:11 +00002954 if (!Context.hasSameType(From->getType(), DestType))
Anders Carlssonf1b48b72010-04-24 16:57:13 +00002955 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
2956 /*isLvalue=*/!From->getType()->isPointerType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002957 return false;
2958}
2959
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002960/// TryContextuallyConvertToBool - Attempt to contextually convert the
2961/// expression From to bool (C++0x [conv]p3).
2962ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00002963 // FIXME: This is pretty broken.
Mike Stump1eb44332009-09-09 15:08:12 +00002964 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00002965 // FIXME: Are these flags correct?
2966 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00002967 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00002968 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002969}
2970
2971/// PerformContextuallyConvertToBool - Perform a contextual conversion
2972/// of the expression From to bool (C++0x [conv]p3).
2973bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2974 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall1d318332010-01-12 00:44:57 +00002975 if (!ICS.isBad())
2976 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002977
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002978 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002979 return Diag(From->getSourceRange().getBegin(),
2980 diag::err_typecheck_bool_condition)
2981 << From->getType() << From->getSourceRange();
2982 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002983}
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00002984
2985/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
2986/// expression From to 'id'.
2987ImplicitConversionSequence Sema::TryContextuallyConvertToObjCId(Expr *From) {
John McCallc12c5bb2010-05-15 11:32:37 +00002988 QualType Ty = Context.getObjCIdType();
2989 return TryImplicitConversion(From, Ty,
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00002990 // FIXME: Are these flags correct?
2991 /*SuppressUserConversions=*/false,
2992 /*AllowExplicit=*/true,
2993 /*InOverloadResolution=*/false);
2994}
2995
2996/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
2997/// of the expression From to 'id'.
2998bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCallc12c5bb2010-05-15 11:32:37 +00002999 QualType Ty = Context.getObjCIdType();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003000 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(From);
3001 if (!ICS.isBad())
3002 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3003 return true;
3004}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003005
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003006/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00003007/// candidate functions, using the given function call arguments. If
3008/// @p SuppressUserConversions, then don't allow user-defined
3009/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003010///
3011/// \para PartialOverloading true if we are performing "partial" overloading
3012/// based on an incomplete set of function arguments. This feature is used by
3013/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00003014void
3015Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00003016 DeclAccessPair FoundDecl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003017 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00003018 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00003019 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003020 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00003021 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003022 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003023 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00003024 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00003025 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00003026
Douglas Gregor88a35142008-12-22 05:46:06 +00003027 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003028 if (!isa<CXXConstructorDecl>(Method)) {
3029 // If we get here, it's because we're calling a member function
3030 // that is named without a member access expression (e.g.,
3031 // "this->f") that was either written explicitly or created
3032 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00003033 // function, e.g., X::f(). We use an empty type for the implied
3034 // object argument (C++ [over.call.func]p3), and the acting context
3035 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00003036 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall701c89e2009-12-03 04:06:58 +00003037 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003038 SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003039 return;
3040 }
3041 // We treat a constructor like a non-member function, since its object
3042 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00003043 }
3044
Douglas Gregorfd476482009-11-13 23:59:09 +00003045 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00003046 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00003047
Douglas Gregor7edfb692009-11-23 12:27:39 +00003048 // Overload resolution is always an unevaluated context.
3049 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3050
Douglas Gregor66724ea2009-11-14 01:20:54 +00003051 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3052 // C++ [class.copy]p3:
3053 // A member function template is never instantiated to perform the copy
3054 // of a class object to an object of its class type.
3055 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3056 if (NumArgs == 1 &&
3057 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor12116062010-02-21 18:30:38 +00003058 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3059 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00003060 return;
3061 }
3062
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003063 // Add this candidate
3064 CandidateSet.push_back(OverloadCandidate());
3065 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003066 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003067 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00003068 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003069 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003070 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003071
3072 unsigned NumArgsInProto = Proto->getNumArgs();
3073
3074 // (C++ 13.3.2p2): A candidate function having fewer than m
3075 // parameters is viable only if it has an ellipsis in its parameter
3076 // list (8.3.5).
Douglas Gregor5bd1a112009-09-23 14:56:09 +00003077 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3078 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003079 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003080 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003081 return;
3082 }
3083
3084 // (C++ 13.3.2p2): A candidate function having more than m parameters
3085 // is viable only if the (m+1)st parameter has a default argument
3086 // (8.3.6). For the purposes of overload resolution, the
3087 // parameter list is truncated on the right, so that there are
3088 // exactly m parameters.
3089 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003090 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003091 // Not enough arguments.
3092 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003093 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003094 return;
3095 }
3096
3097 // Determine the implicit conversion sequences for each of the
3098 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003099 Candidate.Conversions.resize(NumArgs);
3100 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3101 if (ArgIdx < NumArgsInProto) {
3102 // (C++ 13.3.2p3): for F to be a viable function, there shall
3103 // exist for each argument an implicit conversion sequence
3104 // (13.3.3.1) that converts that argument to the corresponding
3105 // parameter of F.
3106 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003107 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003108 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003109 SuppressUserConversions,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003110 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003111 if (Candidate.Conversions[ArgIdx].isBad()) {
3112 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003113 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00003114 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00003115 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003116 } else {
3117 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3118 // argument for which there is no corresponding parameter is
3119 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003120 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003121 }
3122 }
3123}
3124
Douglas Gregor063daf62009-03-13 18:40:31 +00003125/// \brief Add all of the function declarations in the given function set to
3126/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00003127void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00003128 Expr **Args, unsigned NumArgs,
3129 OverloadCandidateSet& CandidateSet,
3130 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00003131 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00003132 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3133 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003134 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003135 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003136 cast<CXXMethodDecl>(FD)->getParent(),
3137 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003138 CandidateSet, SuppressUserConversions);
3139 else
John McCall9aa472c2010-03-19 07:35:19 +00003140 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00003141 SuppressUserConversions);
3142 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003143 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00003144 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3145 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003146 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003147 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00003148 /*FIXME: explicit args */ 0,
John McCall701c89e2009-12-03 04:06:58 +00003149 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003150 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00003151 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00003152 else
John McCall9aa472c2010-03-19 07:35:19 +00003153 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCalld5532b62009-11-23 01:53:49 +00003154 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00003155 Args, NumArgs, CandidateSet,
3156 SuppressUserConversions);
3157 }
Douglas Gregor364e0212009-06-27 21:05:07 +00003158 }
Douglas Gregor063daf62009-03-13 18:40:31 +00003159}
3160
John McCall314be4e2009-11-17 07:50:12 +00003161/// AddMethodCandidate - Adds a named decl (which is some kind of
3162/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00003163void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003164 QualType ObjectType,
John McCall314be4e2009-11-17 07:50:12 +00003165 Expr **Args, unsigned NumArgs,
3166 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003167 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00003168 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003169 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00003170
3171 if (isa<UsingShadowDecl>(Decl))
3172 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3173
3174 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3175 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3176 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00003177 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3178 /*ExplicitArgs*/ 0,
John McCall701c89e2009-12-03 04:06:58 +00003179 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00003180 CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003181 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003182 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003183 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall701c89e2009-12-03 04:06:58 +00003184 ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003185 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003186 }
3187}
3188
Douglas Gregor96176b32008-11-18 23:14:02 +00003189/// AddMethodCandidate - Adds the given C++ member function to the set
3190/// of candidate functions, using the given function call arguments
3191/// and the object argument (@c Object). For example, in a call
3192/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3193/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3194/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00003195/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00003196void
John McCall9aa472c2010-03-19 07:35:19 +00003197Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003198 CXXRecordDecl *ActingContext, QualType ObjectType,
3199 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00003200 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003201 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00003202 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003203 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00003204 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003205 assert(!isa<CXXConstructorDecl>(Method) &&
3206 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00003207
Douglas Gregor3f396022009-09-28 04:47:19 +00003208 if (!CandidateSet.isNewCandidate(Method))
3209 return;
3210
Douglas Gregor7edfb692009-11-23 12:27:39 +00003211 // Overload resolution is always an unevaluated context.
3212 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3213
Douglas Gregor96176b32008-11-18 23:14:02 +00003214 // Add this candidate
3215 CandidateSet.push_back(OverloadCandidate());
3216 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003217 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00003218 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003219 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003220 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003221
3222 unsigned NumArgsInProto = Proto->getNumArgs();
3223
3224 // (C++ 13.3.2p2): A candidate function having fewer than m
3225 // parameters is viable only if it has an ellipsis in its parameter
3226 // list (8.3.5).
3227 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3228 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003229 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003230 return;
3231 }
3232
3233 // (C++ 13.3.2p2): A candidate function having more than m parameters
3234 // is viable only if the (m+1)st parameter has a default argument
3235 // (8.3.6). For the purposes of overload resolution, the
3236 // parameter list is truncated on the right, so that there are
3237 // exactly m parameters.
3238 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3239 if (NumArgs < MinRequiredArgs) {
3240 // Not enough arguments.
3241 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003242 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003243 return;
3244 }
3245
3246 Candidate.Viable = true;
3247 Candidate.Conversions.resize(NumArgs + 1);
3248
John McCall701c89e2009-12-03 04:06:58 +00003249 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00003250 // The implicit object argument is ignored.
3251 Candidate.IgnoreObjectArgument = true;
3252 else {
3253 // Determine the implicit conversion sequence for the object
3254 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00003255 Candidate.Conversions[0]
3256 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00003257 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003258 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003259 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00003260 return;
3261 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003262 }
3263
3264 // Determine the implicit conversion sequences for each of the
3265 // arguments.
3266 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3267 if (ArgIdx < NumArgsInProto) {
3268 // (C++ 13.3.2p3): for F to be a viable function, there shall
3269 // exist for each argument an implicit conversion sequence
3270 // (13.3.3.1) that converts that argument to the corresponding
3271 // parameter of F.
3272 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003273 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003274 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003275 SuppressUserConversions,
Anders Carlsson08972922009-08-28 15:33:32 +00003276 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003277 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00003278 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003279 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00003280 break;
3281 }
3282 } else {
3283 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3284 // argument for which there is no corresponding parameter is
3285 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003286 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00003287 }
3288 }
3289}
Douglas Gregora9333192010-05-08 17:41:32 +00003290
Douglas Gregor6b906862009-08-21 00:16:32 +00003291/// \brief Add a C++ member function template as a candidate to the candidate
3292/// set, using template argument deduction to produce an appropriate member
3293/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003294void
Douglas Gregor6b906862009-08-21 00:16:32 +00003295Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00003296 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003297 CXXRecordDecl *ActingContext,
John McCalld5532b62009-11-23 01:53:49 +00003298 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00003299 QualType ObjectType,
3300 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003301 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003302 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003303 if (!CandidateSet.isNewCandidate(MethodTmpl))
3304 return;
3305
Douglas Gregor6b906862009-08-21 00:16:32 +00003306 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003307 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00003308 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003309 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00003310 // candidate functions in the usual way.113) A given name can refer to one
3311 // or more function templates and also to a set of overloaded non-template
3312 // functions. In such a case, the candidate functions generated from each
3313 // function template are combined with the set of non-template candidate
3314 // functions.
John McCall5769d612010-02-08 23:07:23 +00003315 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00003316 FunctionDecl *Specialization = 0;
3317 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003318 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003319 Args, NumArgs, Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003320 CandidateSet.push_back(OverloadCandidate());
3321 OverloadCandidate &Candidate = CandidateSet.back();
3322 Candidate.FoundDecl = FoundDecl;
3323 Candidate.Function = MethodTmpl->getTemplatedDecl();
3324 Candidate.Viable = false;
3325 Candidate.FailureKind = ovl_fail_bad_deduction;
3326 Candidate.IsSurrogate = false;
3327 Candidate.IgnoreObjectArgument = false;
3328 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3329 Info);
3330 return;
3331 }
Mike Stump1eb44332009-09-09 15:08:12 +00003332
Douglas Gregor6b906862009-08-21 00:16:32 +00003333 // Add the function template specialization produced by template argument
3334 // deduction as a candidate.
3335 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00003336 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00003337 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00003338 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003339 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003340 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00003341}
3342
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003343/// \brief Add a C++ function template specialization as a candidate
3344/// in the candidate set, using template argument deduction to produce
3345/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003346void
Douglas Gregore53060f2009-06-25 22:08:12 +00003347Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003348 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00003349 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00003350 Expr **Args, unsigned NumArgs,
3351 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003352 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003353 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3354 return;
3355
Douglas Gregore53060f2009-06-25 22:08:12 +00003356 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003357 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00003358 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003359 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00003360 // candidate functions in the usual way.113) A given name can refer to one
3361 // or more function templates and also to a set of overloaded non-template
3362 // functions. In such a case, the candidate functions generated from each
3363 // function template are combined with the set of non-template candidate
3364 // functions.
John McCall5769d612010-02-08 23:07:23 +00003365 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00003366 FunctionDecl *Specialization = 0;
3367 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003368 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003369 Args, NumArgs, Specialization, Info)) {
John McCall578b69b2009-12-16 08:11:27 +00003370 CandidateSet.push_back(OverloadCandidate());
3371 OverloadCandidate &Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003372 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00003373 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3374 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003375 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00003376 Candidate.IsSurrogate = false;
3377 Candidate.IgnoreObjectArgument = false;
Douglas Gregorff5adac2010-05-08 20:18:54 +00003378 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3379 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00003380 return;
3381 }
Mike Stump1eb44332009-09-09 15:08:12 +00003382
Douglas Gregore53060f2009-06-25 22:08:12 +00003383 // Add the function template specialization produced by template argument
3384 // deduction as a candidate.
3385 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003386 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003387 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00003388}
Mike Stump1eb44332009-09-09 15:08:12 +00003389
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003390/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00003391/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003392/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00003393/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003394/// (which may or may not be the same type as the type that the
3395/// conversion function produces).
3396void
3397Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003398 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003399 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003400 Expr *From, QualType ToType,
3401 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003402 assert(!Conversion->getDescribedFunctionTemplate() &&
3403 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003404 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00003405 if (!CandidateSet.isNewCandidate(Conversion))
3406 return;
3407
Douglas Gregor7edfb692009-11-23 12:27:39 +00003408 // Overload resolution is always an unevaluated context.
3409 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3410
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003411 // Add this candidate
3412 CandidateSet.push_back(OverloadCandidate());
3413 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003414 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003415 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003416 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003417 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003418 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003419 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003420 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003421
Douglas Gregor96176b32008-11-18 23:14:02 +00003422 // Determine the implicit conversion sequence for the implicit
3423 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003424 Candidate.Viable = true;
3425 Candidate.Conversions.resize(1);
John McCall701c89e2009-12-03 04:06:58 +00003426 Candidate.Conversions[0]
3427 = TryObjectArgumentInitialization(From->getType(), Conversion,
3428 ActingContext);
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00003429 // Conversion functions to a different type in the base class is visible in
3430 // the derived class. So, a derived to base conversion should not participate
3431 // in overload resolution.
3432 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
3433 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall1d318332010-01-12 00:44:57 +00003434 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003435 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003436 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003437 return;
3438 }
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003439
3440 // We won't go through a user-define type conversion function to convert a
3441 // derived to base as such conversions are given Conversion Rank. They only
3442 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3443 QualType FromCanon
3444 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3445 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3446 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3447 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003448 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003449 return;
3450 }
3451
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003452 // To determine what the conversion from the result of calling the
3453 // conversion function to the type we're eventually trying to
3454 // convert to (ToType), we need to synthesize a call to the
3455 // conversion function and attempt copy initialization from it. This
3456 // makes sure that we get the right semantics with respect to
3457 // lvalues/rvalues and the type. Fortunately, we can allocate this
3458 // call on the stack and we don't need its arguments to be
3459 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00003460 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003461 From->getLocStart());
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003462 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman73c39ab2009-10-20 08:27:19 +00003463 CastExpr::CK_FunctionToPointerDecay,
Anders Carlssonf1b48b72010-04-24 16:57:13 +00003464 &ConversionRef, CXXBaseSpecifierArray(), false);
Mike Stump1eb44332009-09-09 15:08:12 +00003465
3466 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00003467 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3468 // allocator).
Mike Stump1eb44332009-09-09 15:08:12 +00003469 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003470 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003471 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00003472 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00003473 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00003474 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003475 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00003476
John McCall1d318332010-01-12 00:44:57 +00003477 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003478 case ImplicitConversionSequence::StandardConversion:
3479 Candidate.FinalConversion = ICS.Standard;
Douglas Gregorc520c842010-04-12 23:42:09 +00003480
3481 // C++ [over.ics.user]p3:
3482 // If the user-defined conversion is specified by a specialization of a
3483 // conversion function template, the second standard conversion sequence
3484 // shall have exact match rank.
3485 if (Conversion->getPrimaryTemplate() &&
3486 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3487 Candidate.Viable = false;
3488 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3489 }
3490
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003491 break;
3492
3493 case ImplicitConversionSequence::BadConversion:
3494 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003495 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003496 break;
3497
3498 default:
Mike Stump1eb44332009-09-09 15:08:12 +00003499 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003500 "Can only end up with a standard conversion sequence or failure");
3501 }
3502}
3503
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003504/// \brief Adds a conversion function template specialization
3505/// candidate to the overload set, using template argument deduction
3506/// to deduce the template arguments of the conversion function
3507/// template from the type that we are converting to (C++
3508/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00003509void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003510Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003511 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003512 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003513 Expr *From, QualType ToType,
3514 OverloadCandidateSet &CandidateSet) {
3515 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3516 "Only conversion function templates permitted here");
3517
Douglas Gregor3f396022009-09-28 04:47:19 +00003518 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3519 return;
3520
John McCall5769d612010-02-08 23:07:23 +00003521 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003522 CXXConversionDecl *Specialization = 0;
3523 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00003524 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003525 Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003526 CandidateSet.push_back(OverloadCandidate());
3527 OverloadCandidate &Candidate = CandidateSet.back();
3528 Candidate.FoundDecl = FoundDecl;
3529 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3530 Candidate.Viable = false;
3531 Candidate.FailureKind = ovl_fail_bad_deduction;
3532 Candidate.IsSurrogate = false;
3533 Candidate.IgnoreObjectArgument = false;
3534 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3535 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003536 return;
3537 }
Mike Stump1eb44332009-09-09 15:08:12 +00003538
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003539 // Add the conversion function template specialization produced by
3540 // template argument deduction as a candidate.
3541 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003542 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00003543 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003544}
3545
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003546/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3547/// converts the given @c Object to a function pointer via the
3548/// conversion function @c Conversion, and then attempts to call it
3549/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3550/// the type of function that we'll eventually be calling.
3551void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003552 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003553 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00003554 const FunctionProtoType *Proto,
John McCall701c89e2009-12-03 04:06:58 +00003555 QualType ObjectType,
3556 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003557 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003558 if (!CandidateSet.isNewCandidate(Conversion))
3559 return;
3560
Douglas Gregor7edfb692009-11-23 12:27:39 +00003561 // Overload resolution is always an unevaluated context.
3562 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3563
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003564 CandidateSet.push_back(OverloadCandidate());
3565 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003566 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003567 Candidate.Function = 0;
3568 Candidate.Surrogate = Conversion;
3569 Candidate.Viable = true;
3570 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003571 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003572 Candidate.Conversions.resize(NumArgs + 1);
3573
3574 // Determine the implicit conversion sequence for the implicit
3575 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00003576 ImplicitConversionSequence ObjectInit
John McCall701c89e2009-12-03 04:06:58 +00003577 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00003578 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003579 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003580 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00003581 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003582 return;
3583 }
3584
3585 // The first conversion is actually a user-defined conversion whose
3586 // first conversion is ObjectInit's standard conversion (which is
3587 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00003588 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003589 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00003590 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003591 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00003592 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003593 = Candidate.Conversions[0].UserDefined.Before;
3594 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3595
Mike Stump1eb44332009-09-09 15:08:12 +00003596 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003597 unsigned NumArgsInProto = Proto->getNumArgs();
3598
3599 // (C++ 13.3.2p2): A candidate function having fewer than m
3600 // parameters is viable only if it has an ellipsis in its parameter
3601 // list (8.3.5).
3602 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3603 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003604 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003605 return;
3606 }
3607
3608 // Function types don't have any default arguments, so just check if
3609 // we have enough arguments.
3610 if (NumArgs < NumArgsInProto) {
3611 // Not enough arguments.
3612 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003613 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003614 return;
3615 }
3616
3617 // Determine the implicit conversion sequences for each of the
3618 // arguments.
3619 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3620 if (ArgIdx < NumArgsInProto) {
3621 // (C++ 13.3.2p3): for F to be a viable function, there shall
3622 // exist for each argument an implicit conversion sequence
3623 // (13.3.3.1) that converts that argument to the corresponding
3624 // parameter of F.
3625 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003626 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003627 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00003628 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003629 /*InOverloadResolution=*/false);
John McCall1d318332010-01-12 00:44:57 +00003630 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003631 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003632 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003633 break;
3634 }
3635 } else {
3636 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3637 // argument for which there is no corresponding parameter is
3638 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003639 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003640 }
3641 }
3642}
3643
Douglas Gregor063daf62009-03-13 18:40:31 +00003644/// \brief Add overload candidates for overloaded operators that are
3645/// member functions.
3646///
3647/// Add the overloaded operator candidates that are member functions
3648/// for the operator Op that was used in an operator expression such
3649/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3650/// CandidateSet will store the added overload candidates. (C++
3651/// [over.match.oper]).
3652void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3653 SourceLocation OpLoc,
3654 Expr **Args, unsigned NumArgs,
3655 OverloadCandidateSet& CandidateSet,
3656 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00003657 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3658
3659 // C++ [over.match.oper]p3:
3660 // For a unary operator @ with an operand of a type whose
3661 // cv-unqualified version is T1, and for a binary operator @ with
3662 // a left operand of a type whose cv-unqualified version is T1 and
3663 // a right operand of a type whose cv-unqualified version is T2,
3664 // three sets of candidate functions, designated member
3665 // candidates, non-member candidates and built-in candidates, are
3666 // constructed as follows:
3667 QualType T1 = Args[0]->getType();
3668 QualType T2;
3669 if (NumArgs > 1)
3670 T2 = Args[1]->getType();
3671
3672 // -- If T1 is a class type, the set of member candidates is the
3673 // result of the qualified lookup of T1::operator@
3674 // (13.3.1.1.1); otherwise, the set of member candidates is
3675 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00003676 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003677 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003678 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003679 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003680
John McCalla24dc2e2009-11-17 02:14:36 +00003681 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3682 LookupQualifiedName(Operators, T1Rec->getDecl());
3683 Operators.suppressDiagnostics();
3684
Mike Stump1eb44332009-09-09 15:08:12 +00003685 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003686 OperEnd = Operators.end();
3687 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00003688 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00003689 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall701c89e2009-12-03 04:06:58 +00003690 Args + 1, NumArgs - 1, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00003691 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00003692 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003693}
3694
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003695/// AddBuiltinCandidate - Add a candidate for a built-in
3696/// operator. ResultTy and ParamTys are the result and parameter types
3697/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003698/// arguments being passed to the candidate. IsAssignmentOperator
3699/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003700/// operator. NumContextualBoolArguments is the number of arguments
3701/// (at the beginning of the argument list) that will be contextually
3702/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00003703void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003704 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003705 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003706 bool IsAssignmentOperator,
3707 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00003708 // Overload resolution is always an unevaluated context.
3709 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3710
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003711 // Add this candidate
3712 CandidateSet.push_back(OverloadCandidate());
3713 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003714 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003715 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003716 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003717 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003718 Candidate.BuiltinTypes.ResultTy = ResultTy;
3719 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3720 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3721
3722 // Determine the implicit conversion sequences for each of the
3723 // arguments.
3724 Candidate.Viable = true;
3725 Candidate.Conversions.resize(NumArgs);
3726 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003727 // C++ [over.match.oper]p4:
3728 // For the built-in assignment operators, conversions of the
3729 // left operand are restricted as follows:
3730 // -- no temporaries are introduced to hold the left operand, and
3731 // -- no user-defined conversions are applied to the left
3732 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00003733 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003734 //
3735 // We block these conversions by turning off user-defined
3736 // conversions, since that is the only way that initialization of
3737 // a reference to a non-class type can occur from something that
3738 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003739 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00003740 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003741 "Contextual conversion to bool requires bool type");
3742 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3743 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00003744 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003745 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00003746 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003747 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003748 }
John McCall1d318332010-01-12 00:44:57 +00003749 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003750 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003751 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00003752 break;
3753 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003754 }
3755}
3756
3757/// BuiltinCandidateTypeSet - A set of types that will be used for the
3758/// candidate operator functions for built-in operators (C++
3759/// [over.built]). The types are separated into pointer types and
3760/// enumeration types.
3761class BuiltinCandidateTypeSet {
3762 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003763 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003764
3765 /// PointerTypes - The set of pointer types that will be used in the
3766 /// built-in candidates.
3767 TypeSet PointerTypes;
3768
Sebastian Redl78eb8742009-04-19 21:53:20 +00003769 /// MemberPointerTypes - The set of member pointer types that will be
3770 /// used in the built-in candidates.
3771 TypeSet MemberPointerTypes;
3772
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003773 /// EnumerationTypes - The set of enumeration types that will be
3774 /// used in the built-in candidates.
3775 TypeSet EnumerationTypes;
3776
Douglas Gregor26bcf672010-05-19 03:21:00 +00003777 /// \brief The set of vector types that will be used in the built-in
3778 /// candidates.
3779 TypeSet VectorTypes;
3780
Douglas Gregor5842ba92009-08-24 15:23:48 +00003781 /// Sema - The semantic analysis instance where we are building the
3782 /// candidate type set.
3783 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00003784
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003785 /// Context - The AST context in which we will build the type sets.
3786 ASTContext &Context;
3787
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003788 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3789 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00003790 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003791
3792public:
3793 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003794 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003795
Mike Stump1eb44332009-09-09 15:08:12 +00003796 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor5842ba92009-08-24 15:23:48 +00003797 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003798
Douglas Gregor573d9c32009-10-21 23:19:44 +00003799 void AddTypesConvertedFrom(QualType Ty,
3800 SourceLocation Loc,
3801 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003802 bool AllowExplicitConversions,
3803 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003804
3805 /// pointer_begin - First pointer type found;
3806 iterator pointer_begin() { return PointerTypes.begin(); }
3807
Sebastian Redl78eb8742009-04-19 21:53:20 +00003808 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003809 iterator pointer_end() { return PointerTypes.end(); }
3810
Sebastian Redl78eb8742009-04-19 21:53:20 +00003811 /// member_pointer_begin - First member pointer type found;
3812 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3813
3814 /// member_pointer_end - Past the last member pointer type found;
3815 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3816
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003817 /// enumeration_begin - First enumeration type found;
3818 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3819
Sebastian Redl78eb8742009-04-19 21:53:20 +00003820 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003821 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregor26bcf672010-05-19 03:21:00 +00003822
3823 iterator vector_begin() { return VectorTypes.begin(); }
3824 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003825};
3826
Sebastian Redl78eb8742009-04-19 21:53:20 +00003827/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003828/// the set of pointer types along with any more-qualified variants of
3829/// that type. For example, if @p Ty is "int const *", this routine
3830/// will add "int const *", "int const volatile *", "int const
3831/// restrict *", and "int const volatile restrict *" to the set of
3832/// pointer types. Returns true if the add of @p Ty itself succeeded,
3833/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003834///
3835/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003836bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00003837BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3838 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00003839
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003840 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00003841 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003842 return false;
3843
John McCall0953e762009-09-24 19:53:00 +00003844 const PointerType *PointerTy = Ty->getAs<PointerType>();
3845 assert(PointerTy && "type was not a pointer type!");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003846
John McCall0953e762009-09-24 19:53:00 +00003847 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003848 // Don't add qualified variants of arrays. For one, they're not allowed
3849 // (the qualifier would sink to the element type), and for another, the
3850 // only overload situation where it matters is subscript or pointer +- int,
3851 // and those shouldn't have qualifier variants anyway.
3852 if (PointeeTy->isArrayType())
3853 return true;
John McCall0953e762009-09-24 19:53:00 +00003854 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00003855 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00003856 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003857 bool hasVolatile = VisibleQuals.hasVolatile();
3858 bool hasRestrict = VisibleQuals.hasRestrict();
3859
John McCall0953e762009-09-24 19:53:00 +00003860 // Iterate through all strict supersets of BaseCVR.
3861 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3862 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003863 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3864 // in the types.
3865 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3866 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00003867 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3868 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003869 }
3870
3871 return true;
3872}
3873
Sebastian Redl78eb8742009-04-19 21:53:20 +00003874/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3875/// to the set of pointer types along with any more-qualified variants of
3876/// that type. For example, if @p Ty is "int const *", this routine
3877/// will add "int const *", "int const volatile *", "int const
3878/// restrict *", and "int const volatile restrict *" to the set of
3879/// pointer types. Returns true if the add of @p Ty itself succeeded,
3880/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00003881///
3882/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00003883bool
3884BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3885 QualType Ty) {
3886 // Insert this type.
3887 if (!MemberPointerTypes.insert(Ty))
3888 return false;
3889
John McCall0953e762009-09-24 19:53:00 +00003890 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3891 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00003892
John McCall0953e762009-09-24 19:53:00 +00003893 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00003894 // Don't add qualified variants of arrays. For one, they're not allowed
3895 // (the qualifier would sink to the element type), and for another, the
3896 // only overload situation where it matters is subscript or pointer +- int,
3897 // and those shouldn't have qualifier variants anyway.
3898 if (PointeeTy->isArrayType())
3899 return true;
John McCall0953e762009-09-24 19:53:00 +00003900 const Type *ClassTy = PointerTy->getClass();
3901
3902 // Iterate through all strict supersets of the pointee type's CVR
3903 // qualifiers.
3904 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3905 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3906 if ((CVR | BaseCVR) != CVR) continue;
3907
3908 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3909 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00003910 }
3911
3912 return true;
3913}
3914
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003915/// AddTypesConvertedFrom - Add each of the types to which the type @p
3916/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00003917/// primarily interested in pointer types and enumeration types. We also
3918/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003919/// AllowUserConversions is true if we should look at the conversion
3920/// functions of a class type, and AllowExplicitConversions if we
3921/// should also include the explicit conversion functions of a class
3922/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00003923void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003924BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00003925 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003926 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003927 bool AllowExplicitConversions,
3928 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003929 // Only deal with canonical types.
3930 Ty = Context.getCanonicalType(Ty);
3931
3932 // Look through reference types; they aren't part of the type of an
3933 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00003934 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003935 Ty = RefTy->getPointeeType();
3936
3937 // We don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00003938 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003939
Sebastian Redla65b5512009-11-05 16:36:20 +00003940 // If we're dealing with an array type, decay to the pointer.
3941 if (Ty->isArrayType())
3942 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3943
Ted Kremenek6217b802009-07-29 21:53:49 +00003944 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003945 QualType PointeeTy = PointerTy->getPointeeType();
3946
3947 // Insert our type, and its more-qualified variants, into the set
3948 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00003949 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003950 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00003951 } else if (Ty->isMemberPointerType()) {
3952 // Member pointers are far easier, since the pointee can't be converted.
3953 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3954 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003955 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00003956 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00003957 } else if (Ty->isVectorType()) {
3958 VectorTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003959 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003960 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003961 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00003962 // No conversion functions in incomplete types.
3963 return;
3964 }
Mike Stump1eb44332009-09-09 15:08:12 +00003965
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003966 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00003967 const UnresolvedSetImpl *Conversions
Fariborz Jahanianca4fb042009-10-07 17:26:09 +00003968 = ClassDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00003969 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00003970 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00003971 NamedDecl *D = I.getDecl();
3972 if (isa<UsingShadowDecl>(D))
3973 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003974
Mike Stump1eb44332009-09-09 15:08:12 +00003975 // Skip conversion function templates; they don't tell us anything
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003976 // about which builtin types we can convert to.
John McCall32daa422010-03-31 01:36:47 +00003977 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003978 continue;
3979
John McCall32daa422010-03-31 01:36:47 +00003980 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003981 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00003982 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00003983 VisibleQuals);
3984 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003985 }
3986 }
3987 }
3988}
3989
Douglas Gregor19b7b152009-08-24 13:43:27 +00003990/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3991/// the volatile- and non-volatile-qualified assignment operators for the
3992/// given type to the candidate set.
3993static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3994 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00003995 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00003996 unsigned NumArgs,
3997 OverloadCandidateSet &CandidateSet) {
3998 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00003999
Douglas Gregor19b7b152009-08-24 13:43:27 +00004000 // T& operator=(T&, T)
4001 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4002 ParamTypes[1] = T;
4003 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4004 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004005
Douglas Gregor19b7b152009-08-24 13:43:27 +00004006 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4007 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00004008 ParamTypes[0]
4009 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00004010 ParamTypes[1] = T;
4011 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00004012 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00004013 }
4014}
Mike Stump1eb44332009-09-09 15:08:12 +00004015
Sebastian Redl9994a342009-10-25 17:03:50 +00004016/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4017/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004018static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4019 Qualifiers VRQuals;
4020 const RecordType *TyRec;
4021 if (const MemberPointerType *RHSMPType =
4022 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004023 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004024 else
4025 TyRec = ArgExpr->getType()->getAs<RecordType>();
4026 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004027 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004028 VRQuals.addVolatile();
4029 VRQuals.addRestrict();
4030 return VRQuals;
4031 }
4032
4033 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00004034 if (!ClassDecl->hasDefinition())
4035 return VRQuals;
4036
John McCalleec51cf2010-01-20 00:46:10 +00004037 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00004038 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004039
John McCalleec51cf2010-01-20 00:46:10 +00004040 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004041 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00004042 NamedDecl *D = I.getDecl();
4043 if (isa<UsingShadowDecl>(D))
4044 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4045 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004046 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4047 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4048 CanTy = ResTypeRef->getPointeeType();
4049 // Need to go down the pointer/mempointer chain and add qualifiers
4050 // as see them.
4051 bool done = false;
4052 while (!done) {
4053 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4054 CanTy = ResTypePtr->getPointeeType();
4055 else if (const MemberPointerType *ResTypeMPtr =
4056 CanTy->getAs<MemberPointerType>())
4057 CanTy = ResTypeMPtr->getPointeeType();
4058 else
4059 done = true;
4060 if (CanTy.isVolatileQualified())
4061 VRQuals.addVolatile();
4062 if (CanTy.isRestrictQualified())
4063 VRQuals.addRestrict();
4064 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4065 return VRQuals;
4066 }
4067 }
4068 }
4069 return VRQuals;
4070}
4071
Douglas Gregor74253732008-11-19 15:42:04 +00004072/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4073/// operator overloads to the candidate set (C++ [over.built]), based
4074/// on the operator @p Op and the arguments given. For example, if the
4075/// operator is a binary '+', this routine might add "int
4076/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004077void
Mike Stump1eb44332009-09-09 15:08:12 +00004078Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004079 SourceLocation OpLoc,
Douglas Gregor74253732008-11-19 15:42:04 +00004080 Expr **Args, unsigned NumArgs,
4081 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004082 // The set of "promoted arithmetic types", which are the arithmetic
4083 // types are that preserved by promotion (C++ [over.built]p2). Note
4084 // that the first few of these types are the promoted integral
4085 // types; these types need to be first.
4086 // FIXME: What about complex?
4087 const unsigned FirstIntegralType = 0;
4088 const unsigned LastIntegralType = 13;
Mike Stump1eb44332009-09-09 15:08:12 +00004089 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004090 LastPromotedIntegralType = 13;
4091 const unsigned FirstPromotedArithmeticType = 7,
4092 LastPromotedArithmeticType = 16;
4093 const unsigned NumArithmeticTypes = 16;
4094 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump1eb44332009-09-09 15:08:12 +00004095 Context.BoolTy, Context.CharTy, Context.WCharTy,
4096// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004097 Context.SignedCharTy, Context.ShortTy,
4098 Context.UnsignedCharTy, Context.UnsignedShortTy,
4099 Context.IntTy, Context.LongTy, Context.LongLongTy,
4100 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
4101 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
4102 };
Douglas Gregor652371a2009-10-21 22:01:30 +00004103 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
4104 "Invalid first promoted integral type");
4105 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4106 == Context.UnsignedLongLongTy &&
4107 "Invalid last promoted integral type");
4108 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
4109 "Invalid first promoted arithmetic type");
4110 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4111 == Context.LongDoubleTy &&
4112 "Invalid last promoted arithmetic type");
4113
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004114 // Find all of the types that the arguments can convert to, but only
4115 // if the operator we're looking at has built-in operator candidates
4116 // that make use of these types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004117 Qualifiers VisibleTypeConversionsQuals;
4118 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004119 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4120 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4121
Douglas Gregor5842ba92009-08-24 15:23:48 +00004122 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004123 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4124 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4125 OpLoc,
4126 true,
4127 (Op == OO_Exclaim ||
4128 Op == OO_AmpAmp ||
4129 Op == OO_PipePipe),
4130 VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004131
4132 bool isComparison = false;
4133 switch (Op) {
4134 case OO_None:
4135 case NUM_OVERLOADED_OPERATORS:
4136 assert(false && "Expected an overloaded operator");
4137 break;
4138
Douglas Gregor74253732008-11-19 15:42:04 +00004139 case OO_Star: // '*' is either unary or binary
Mike Stump1eb44332009-09-09 15:08:12 +00004140 if (NumArgs == 1)
Douglas Gregor74253732008-11-19 15:42:04 +00004141 goto UnaryStar;
4142 else
4143 goto BinaryStar;
4144 break;
4145
4146 case OO_Plus: // '+' is either unary or binary
4147 if (NumArgs == 1)
4148 goto UnaryPlus;
4149 else
4150 goto BinaryPlus;
4151 break;
4152
4153 case OO_Minus: // '-' is either unary or binary
4154 if (NumArgs == 1)
4155 goto UnaryMinus;
4156 else
4157 goto BinaryMinus;
4158 break;
4159
4160 case OO_Amp: // '&' is either unary or binary
4161 if (NumArgs == 1)
4162 goto UnaryAmp;
4163 else
4164 goto BinaryAmp;
4165
4166 case OO_PlusPlus:
4167 case OO_MinusMinus:
4168 // C++ [over.built]p3:
4169 //
4170 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4171 // is either volatile or empty, there exist candidate operator
4172 // functions of the form
4173 //
4174 // VQ T& operator++(VQ T&);
4175 // T operator++(VQ T&, int);
4176 //
4177 // C++ [over.built]p4:
4178 //
4179 // For every pair (T, VQ), where T is an arithmetic type other
4180 // than bool, and VQ is either volatile or empty, there exist
4181 // candidate operator functions of the form
4182 //
4183 // VQ T& operator--(VQ T&);
4184 // T operator--(VQ T&, int);
Mike Stump1eb44332009-09-09 15:08:12 +00004185 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor74253732008-11-19 15:42:04 +00004186 Arith < NumArithmeticTypes; ++Arith) {
4187 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump1eb44332009-09-09 15:08:12 +00004188 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004189 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00004190
4191 // Non-volatile version.
4192 if (NumArgs == 1)
4193 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4194 else
4195 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004196 // heuristic to reduce number of builtin candidates in the set.
4197 // Add volatile version only if there are conversions to a volatile type.
4198 if (VisibleTypeConversionsQuals.hasVolatile()) {
4199 // Volatile version
4200 ParamTypes[0]
4201 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4202 if (NumArgs == 1)
4203 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4204 else
4205 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4206 }
Douglas Gregor74253732008-11-19 15:42:04 +00004207 }
4208
4209 // C++ [over.built]p5:
4210 //
4211 // For every pair (T, VQ), where T is a cv-qualified or
4212 // cv-unqualified object type, and VQ is either volatile or
4213 // empty, there exist candidate operator functions of the form
4214 //
4215 // T*VQ& operator++(T*VQ&);
4216 // T*VQ& operator--(T*VQ&);
4217 // T* operator++(T*VQ&, int);
4218 // T* operator--(T*VQ&, int);
4219 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4220 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4221 // Skip pointer types that aren't pointers to object types.
Ted Kremenek6217b802009-07-29 21:53:49 +00004222 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00004223 continue;
4224
Mike Stump1eb44332009-09-09 15:08:12 +00004225 QualType ParamTypes[2] = {
4226 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00004227 };
Mike Stump1eb44332009-09-09 15:08:12 +00004228
Douglas Gregor74253732008-11-19 15:42:04 +00004229 // Without volatile
4230 if (NumArgs == 1)
4231 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4232 else
4233 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4234
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004235 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4236 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00004237 // With volatile
John McCall0953e762009-09-24 19:53:00 +00004238 ParamTypes[0]
4239 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor74253732008-11-19 15:42:04 +00004240 if (NumArgs == 1)
4241 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4242 else
4243 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4244 }
4245 }
4246 break;
4247
4248 UnaryStar:
4249 // C++ [over.built]p6:
4250 // For every cv-qualified or cv-unqualified object type T, there
4251 // exist candidate operator functions of the form
4252 //
4253 // T& operator*(T*);
4254 //
4255 // C++ [over.built]p7:
4256 // For every function type T, there exist candidate operator
4257 // functions of the form
4258 // T& operator*(T*);
4259 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4260 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4261 QualType ParamTy = *Ptr;
Ted Kremenek6217b802009-07-29 21:53:49 +00004262 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004263 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00004264 &ParamTy, Args, 1, CandidateSet);
4265 }
4266 break;
4267
4268 UnaryPlus:
4269 // C++ [over.built]p8:
4270 // For every type T, there exist candidate operator functions of
4271 // the form
4272 //
4273 // T* operator+(T*);
4274 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4275 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4276 QualType ParamTy = *Ptr;
4277 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4278 }
Mike Stump1eb44332009-09-09 15:08:12 +00004279
Douglas Gregor74253732008-11-19 15:42:04 +00004280 // Fall through
4281
4282 UnaryMinus:
4283 // C++ [over.built]p9:
4284 // For every promoted arithmetic type T, there exist candidate
4285 // operator functions of the form
4286 //
4287 // T operator+(T);
4288 // T operator-(T);
Mike Stump1eb44332009-09-09 15:08:12 +00004289 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor74253732008-11-19 15:42:04 +00004290 Arith < LastPromotedArithmeticType; ++Arith) {
4291 QualType ArithTy = ArithmeticTypes[Arith];
4292 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4293 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004294
4295 // Extension: We also add these operators for vector types.
4296 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4297 VecEnd = CandidateTypes.vector_end();
4298 Vec != VecEnd; ++Vec) {
4299 QualType VecTy = *Vec;
4300 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4301 }
Douglas Gregor74253732008-11-19 15:42:04 +00004302 break;
4303
4304 case OO_Tilde:
4305 // C++ [over.built]p10:
4306 // For every promoted integral type T, there exist candidate
4307 // operator functions of the form
4308 //
4309 // T operator~(T);
Mike Stump1eb44332009-09-09 15:08:12 +00004310 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor74253732008-11-19 15:42:04 +00004311 Int < LastPromotedIntegralType; ++Int) {
4312 QualType IntTy = ArithmeticTypes[Int];
4313 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4314 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004315
4316 // Extension: We also add this operator for vector types.
4317 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4318 VecEnd = CandidateTypes.vector_end();
4319 Vec != VecEnd; ++Vec) {
4320 QualType VecTy = *Vec;
4321 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4322 }
Douglas Gregor74253732008-11-19 15:42:04 +00004323 break;
4324
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004325 case OO_New:
4326 case OO_Delete:
4327 case OO_Array_New:
4328 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004329 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00004330 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004331 break;
4332
4333 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00004334 UnaryAmp:
4335 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004336 // C++ [over.match.oper]p3:
4337 // -- For the operator ',', the unary operator '&', or the
4338 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004339 break;
4340
Douglas Gregor19b7b152009-08-24 13:43:27 +00004341 case OO_EqualEqual:
4342 case OO_ExclaimEqual:
4343 // C++ [over.match.oper]p16:
Mike Stump1eb44332009-09-09 15:08:12 +00004344 // For every pointer to member type T, there exist candidate operator
4345 // functions of the form
Douglas Gregor19b7b152009-08-24 13:43:27 +00004346 //
4347 // bool operator==(T,T);
4348 // bool operator!=(T,T);
Mike Stump1eb44332009-09-09 15:08:12 +00004349 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor19b7b152009-08-24 13:43:27 +00004350 MemPtr = CandidateTypes.member_pointer_begin(),
4351 MemPtrEnd = CandidateTypes.member_pointer_end();
4352 MemPtr != MemPtrEnd;
4353 ++MemPtr) {
4354 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4355 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4356 }
Mike Stump1eb44332009-09-09 15:08:12 +00004357
Douglas Gregor19b7b152009-08-24 13:43:27 +00004358 // Fall through
Mike Stump1eb44332009-09-09 15:08:12 +00004359
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004360 case OO_Less:
4361 case OO_Greater:
4362 case OO_LessEqual:
4363 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004364 // C++ [over.built]p15:
4365 //
4366 // For every pointer or enumeration type T, there exist
4367 // candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004368 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004369 // bool operator<(T, T);
4370 // bool operator>(T, T);
4371 // bool operator<=(T, T);
4372 // bool operator>=(T, T);
4373 // bool operator==(T, T);
4374 // bool operator!=(T, T);
4375 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4376 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4377 QualType ParamTypes[2] = { *Ptr, *Ptr };
4378 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4379 }
Mike Stump1eb44332009-09-09 15:08:12 +00004380 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004381 = CandidateTypes.enumeration_begin();
4382 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4383 QualType ParamTypes[2] = { *Enum, *Enum };
4384 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4385 }
4386
4387 // Fall through.
4388 isComparison = true;
4389
Douglas Gregor74253732008-11-19 15:42:04 +00004390 BinaryPlus:
4391 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004392 if (!isComparison) {
4393 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4394
4395 // C++ [over.built]p13:
4396 //
4397 // For every cv-qualified or cv-unqualified object type T
4398 // there exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004399 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004400 // T* operator+(T*, ptrdiff_t);
4401 // T& operator[](T*, ptrdiff_t); [BELOW]
4402 // T* operator-(T*, ptrdiff_t);
4403 // T* operator+(ptrdiff_t, T*);
4404 // T& operator[](ptrdiff_t, T*); [BELOW]
4405 //
4406 // C++ [over.built]p14:
4407 //
4408 // For every T, where T is a pointer to object type, there
4409 // exist candidate operator functions of the form
4410 //
4411 // ptrdiff_t operator-(T, T);
Mike Stump1eb44332009-09-09 15:08:12 +00004412 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004413 = CandidateTypes.pointer_begin();
4414 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4415 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4416
4417 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4418 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4419
4420 if (Op == OO_Plus) {
4421 // T* operator+(ptrdiff_t, T*);
4422 ParamTypes[0] = ParamTypes[1];
4423 ParamTypes[1] = *Ptr;
4424 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4425 } else {
4426 // ptrdiff_t operator-(T, T);
4427 ParamTypes[1] = *Ptr;
4428 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4429 Args, 2, CandidateSet);
4430 }
4431 }
4432 }
4433 // Fall through
4434
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004435 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00004436 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004437 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004438 // C++ [over.built]p12:
4439 //
4440 // For every pair of promoted arithmetic types L and R, there
4441 // exist candidate operator functions of the form
4442 //
4443 // LR operator*(L, R);
4444 // LR operator/(L, R);
4445 // LR operator+(L, R);
4446 // LR operator-(L, R);
4447 // bool operator<(L, R);
4448 // bool operator>(L, R);
4449 // bool operator<=(L, R);
4450 // bool operator>=(L, R);
4451 // bool operator==(L, R);
4452 // bool operator!=(L, R);
4453 //
4454 // where LR is the result of the usual arithmetic conversions
4455 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004456 //
4457 // C++ [over.built]p24:
4458 //
4459 // For every pair of promoted arithmetic types L and R, there exist
4460 // candidate operator functions of the form
4461 //
4462 // LR operator?(bool, L, R);
4463 //
4464 // where LR is the result of the usual arithmetic conversions
4465 // between types L and R.
4466 // Our candidates ignore the first parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00004467 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004468 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004469 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004470 Right < LastPromotedArithmeticType; ++Right) {
4471 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00004472 QualType Result
4473 = isComparison
4474 ? Context.BoolTy
4475 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004476 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4477 }
4478 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004479
4480 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
4481 // conditional operator for vector types.
4482 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4483 Vec1End = CandidateTypes.vector_end();
4484 Vec1 != Vec1End; ++Vec1)
4485 for (BuiltinCandidateTypeSet::iterator
4486 Vec2 = CandidateTypes.vector_begin(),
4487 Vec2End = CandidateTypes.vector_end();
4488 Vec2 != Vec2End; ++Vec2) {
4489 QualType LandR[2] = { *Vec1, *Vec2 };
4490 QualType Result;
4491 if (isComparison)
4492 Result = Context.BoolTy;
4493 else {
4494 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
4495 Result = *Vec1;
4496 else
4497 Result = *Vec2;
4498 }
4499
4500 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4501 }
4502
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004503 break;
4504
4505 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00004506 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004507 case OO_Caret:
4508 case OO_Pipe:
4509 case OO_LessLess:
4510 case OO_GreaterGreater:
4511 // C++ [over.built]p17:
4512 //
4513 // For every pair of promoted integral types L and R, there
4514 // exist candidate operator functions of the form
4515 //
4516 // LR operator%(L, R);
4517 // LR operator&(L, R);
4518 // LR operator^(L, R);
4519 // LR operator|(L, R);
4520 // L operator<<(L, R);
4521 // L operator>>(L, R);
4522 //
4523 // where LR is the result of the usual arithmetic conversions
4524 // between types L and R.
Mike Stump1eb44332009-09-09 15:08:12 +00004525 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004526 Left < LastPromotedIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004527 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004528 Right < LastPromotedIntegralType; ++Right) {
4529 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4530 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4531 ? LandR[0]
Eli Friedmana95d7572009-08-19 07:44:53 +00004532 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004533 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4534 }
4535 }
4536 break;
4537
4538 case OO_Equal:
4539 // C++ [over.built]p20:
4540 //
4541 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00004542 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004543 // empty, there exist candidate operator functions of the form
4544 //
4545 // VQ T& operator=(VQ T&, T);
Douglas Gregor19b7b152009-08-24 13:43:27 +00004546 for (BuiltinCandidateTypeSet::iterator
4547 Enum = CandidateTypes.enumeration_begin(),
4548 EnumEnd = CandidateTypes.enumeration_end();
4549 Enum != EnumEnd; ++Enum)
Mike Stump1eb44332009-09-09 15:08:12 +00004550 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004551 CandidateSet);
4552 for (BuiltinCandidateTypeSet::iterator
4553 MemPtr = CandidateTypes.member_pointer_begin(),
4554 MemPtrEnd = CandidateTypes.member_pointer_end();
4555 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump1eb44332009-09-09 15:08:12 +00004556 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004557 CandidateSet);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004558
4559 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004560
4561 case OO_PlusEqual:
4562 case OO_MinusEqual:
4563 // C++ [over.built]p19:
4564 //
4565 // For every pair (T, VQ), where T is any type and VQ is either
4566 // volatile or empty, there exist candidate operator functions
4567 // of the form
4568 //
4569 // T*VQ& operator=(T*VQ&, T*);
4570 //
4571 // C++ [over.built]p21:
4572 //
4573 // For every pair (T, VQ), where T is a cv-qualified or
4574 // cv-unqualified object type and VQ is either volatile or
4575 // empty, there exist candidate operator functions of the form
4576 //
4577 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4578 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4579 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4580 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4581 QualType ParamTypes[2];
4582 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4583
4584 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004585 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004586 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4587 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004588
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004589 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4590 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00004591 // volatile version
John McCall0953e762009-09-24 19:53:00 +00004592 ParamTypes[0]
4593 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004594 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4595 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00004596 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004597 }
4598 // Fall through.
4599
4600 case OO_StarEqual:
4601 case OO_SlashEqual:
4602 // C++ [over.built]p18:
4603 //
4604 // For every triple (L, VQ, R), where L is an arithmetic type,
4605 // VQ is either volatile or empty, and R is a promoted
4606 // arithmetic type, there exist candidate operator functions of
4607 // the form
4608 //
4609 // VQ L& operator=(VQ L&, R);
4610 // VQ L& operator*=(VQ L&, R);
4611 // VQ L& operator/=(VQ L&, R);
4612 // VQ L& operator+=(VQ L&, R);
4613 // VQ L& operator-=(VQ L&, R);
4614 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004615 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004616 Right < LastPromotedArithmeticType; ++Right) {
4617 QualType ParamTypes[2];
4618 ParamTypes[1] = ArithmeticTypes[Right];
4619
4620 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004621 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004622 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4623 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004624
4625 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004626 if (VisibleTypeConversionsQuals.hasVolatile()) {
4627 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4628 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4629 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4630 /*IsAssigmentOperator=*/Op == OO_Equal);
4631 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004632 }
4633 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004634
4635 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
4636 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4637 Vec1End = CandidateTypes.vector_end();
4638 Vec1 != Vec1End; ++Vec1)
4639 for (BuiltinCandidateTypeSet::iterator
4640 Vec2 = CandidateTypes.vector_begin(),
4641 Vec2End = CandidateTypes.vector_end();
4642 Vec2 != Vec2End; ++Vec2) {
4643 QualType ParamTypes[2];
4644 ParamTypes[1] = *Vec2;
4645 // Add this built-in operator as a candidate (VQ is empty).
4646 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
4647 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4648 /*IsAssigmentOperator=*/Op == OO_Equal);
4649
4650 // Add this built-in operator as a candidate (VQ is 'volatile').
4651 if (VisibleTypeConversionsQuals.hasVolatile()) {
4652 ParamTypes[0] = Context.getVolatileType(*Vec1);
4653 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4654 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4655 /*IsAssigmentOperator=*/Op == OO_Equal);
4656 }
4657 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004658 break;
4659
4660 case OO_PercentEqual:
4661 case OO_LessLessEqual:
4662 case OO_GreaterGreaterEqual:
4663 case OO_AmpEqual:
4664 case OO_CaretEqual:
4665 case OO_PipeEqual:
4666 // C++ [over.built]p22:
4667 //
4668 // For every triple (L, VQ, R), where L is an integral type, VQ
4669 // is either volatile or empty, and R is a promoted integral
4670 // type, there exist candidate operator functions of the form
4671 //
4672 // VQ L& operator%=(VQ L&, R);
4673 // VQ L& operator<<=(VQ L&, R);
4674 // VQ L& operator>>=(VQ L&, R);
4675 // VQ L& operator&=(VQ L&, R);
4676 // VQ L& operator^=(VQ L&, R);
4677 // VQ L& operator|=(VQ L&, R);
4678 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004679 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004680 Right < LastPromotedIntegralType; ++Right) {
4681 QualType ParamTypes[2];
4682 ParamTypes[1] = ArithmeticTypes[Right];
4683
4684 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004685 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004686 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian035c46f2009-10-20 00:04:40 +00004687 if (VisibleTypeConversionsQuals.hasVolatile()) {
4688 // Add this built-in operator as a candidate (VQ is 'volatile').
4689 ParamTypes[0] = ArithmeticTypes[Left];
4690 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4691 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4692 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4693 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004694 }
4695 }
4696 break;
4697
Douglas Gregor74253732008-11-19 15:42:04 +00004698 case OO_Exclaim: {
4699 // C++ [over.operator]p23:
4700 //
4701 // There also exist candidate operator functions of the form
4702 //
Mike Stump1eb44332009-09-09 15:08:12 +00004703 // bool operator!(bool);
Douglas Gregor74253732008-11-19 15:42:04 +00004704 // bool operator&&(bool, bool); [BELOW]
4705 // bool operator||(bool, bool); [BELOW]
4706 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004707 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4708 /*IsAssignmentOperator=*/false,
4709 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00004710 break;
4711 }
4712
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004713 case OO_AmpAmp:
4714 case OO_PipePipe: {
4715 // C++ [over.operator]p23:
4716 //
4717 // There also exist candidate operator functions of the form
4718 //
Douglas Gregor74253732008-11-19 15:42:04 +00004719 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004720 // bool operator&&(bool, bool);
4721 // bool operator||(bool, bool);
4722 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004723 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4724 /*IsAssignmentOperator=*/false,
4725 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004726 break;
4727 }
4728
4729 case OO_Subscript:
4730 // C++ [over.built]p13:
4731 //
4732 // For every cv-qualified or cv-unqualified object type T there
4733 // exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004734 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004735 // T* operator+(T*, ptrdiff_t); [ABOVE]
4736 // T& operator[](T*, ptrdiff_t);
4737 // T* operator-(T*, ptrdiff_t); [ABOVE]
4738 // T* operator+(ptrdiff_t, T*); [ABOVE]
4739 // T& operator[](ptrdiff_t, T*);
4740 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4741 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4742 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenek6217b802009-07-29 21:53:49 +00004743 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004744 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004745
4746 // T& operator[](T*, ptrdiff_t)
4747 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4748
4749 // T& operator[](ptrdiff_t, T*);
4750 ParamTypes[0] = ParamTypes[1];
4751 ParamTypes[1] = *Ptr;
4752 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004753 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004754 break;
4755
4756 case OO_ArrowStar:
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004757 // C++ [over.built]p11:
4758 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4759 // C1 is the same type as C2 or is a derived class of C2, T is an object
4760 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4761 // there exist candidate operator functions of the form
4762 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4763 // where CV12 is the union of CV1 and CV2.
4764 {
4765 for (BuiltinCandidateTypeSet::iterator Ptr =
4766 CandidateTypes.pointer_begin();
4767 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4768 QualType C1Ty = (*Ptr);
4769 QualType C1;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004770 QualifierCollector Q1;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004771 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004772 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004773 if (!isa<RecordType>(C1))
4774 continue;
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004775 // heuristic to reduce number of builtin candidates in the set.
4776 // Add volatile/restrict version only if there are conversions to a
4777 // volatile/restrict type.
4778 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4779 continue;
4780 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4781 continue;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004782 }
4783 for (BuiltinCandidateTypeSet::iterator
4784 MemPtr = CandidateTypes.member_pointer_begin(),
4785 MemPtrEnd = CandidateTypes.member_pointer_end();
4786 MemPtr != MemPtrEnd; ++MemPtr) {
4787 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4788 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian43036972009-10-07 16:56:50 +00004789 C2 = C2.getUnqualifiedType();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004790 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4791 break;
4792 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4793 // build CV12 T&
4794 QualType T = mptr->getPointeeType();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004795 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4796 T.isVolatileQualified())
4797 continue;
4798 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4799 T.isRestrictQualified())
4800 continue;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00004801 T = Q1.apply(T);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00004802 QualType ResultTy = Context.getLValueReferenceType(T);
4803 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4804 }
4805 }
4806 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004807 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004808
4809 case OO_Conditional:
4810 // Note that we don't consider the first argument, since it has been
4811 // contextually converted to bool long ago. The candidates below are
4812 // therefore added as binary.
4813 //
4814 // C++ [over.built]p24:
4815 // For every type T, where T is a pointer or pointer-to-member type,
4816 // there exist candidate operator functions of the form
4817 //
4818 // T operator?(bool, T, T);
4819 //
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004820 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4821 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4822 QualType ParamTypes[2] = { *Ptr, *Ptr };
4823 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4824 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00004825 for (BuiltinCandidateTypeSet::iterator Ptr =
4826 CandidateTypes.member_pointer_begin(),
4827 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4828 QualType ParamTypes[2] = { *Ptr, *Ptr };
4829 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4830 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004831 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004832 }
4833}
4834
Douglas Gregorfa047642009-02-04 00:32:51 +00004835/// \brief Add function candidates found via argument-dependent lookup
4836/// to the set of overloading candidates.
4837///
4838/// This routine performs argument-dependent name lookup based on the
4839/// given function name (which may also be an operator name) and adds
4840/// all of the overload candidates found by ADL to the overload
4841/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00004842void
Douglas Gregorfa047642009-02-04 00:32:51 +00004843Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00004844 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00004845 Expr **Args, unsigned NumArgs,
John McCalld5532b62009-11-23 01:53:49 +00004846 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004847 OverloadCandidateSet& CandidateSet,
4848 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00004849 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00004850
John McCalla113e722010-01-26 06:04:06 +00004851 // FIXME: This approach for uniquing ADL results (and removing
4852 // redundant candidates from the set) relies on pointer-equality,
4853 // which means we need to key off the canonical decl. However,
4854 // always going back to the canonical decl might not get us the
4855 // right set of default arguments. What default arguments are
4856 // we supposed to consider on ADL candidates, anyway?
4857
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004858 // FIXME: Pass in the explicit template arguments?
John McCall7edb5fd2010-01-26 07:16:45 +00004859 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00004860
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004861 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004862 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4863 CandEnd = CandidateSet.end();
4864 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00004865 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00004866 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00004867 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00004868 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00004869 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00004870
4871 // For each of the ADL candidates we found, add it to the overload
4872 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00004873 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00004874 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00004875 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00004876 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004877 continue;
4878
John McCall9aa472c2010-03-19 07:35:19 +00004879 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00004880 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004881 } else
John McCall6e266892010-01-26 03:27:55 +00004882 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00004883 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004884 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00004885 }
Douglas Gregorfa047642009-02-04 00:32:51 +00004886}
4887
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004888/// isBetterOverloadCandidate - Determines whether the first overload
4889/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00004890bool
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004891Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCall5769d612010-02-08 23:07:23 +00004892 const OverloadCandidate& Cand2,
4893 SourceLocation Loc) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004894 // Define viable functions to be better candidates than non-viable
4895 // functions.
4896 if (!Cand2.Viable)
4897 return Cand1.Viable;
4898 else if (!Cand1.Viable)
4899 return false;
4900
Douglas Gregor88a35142008-12-22 05:46:06 +00004901 // C++ [over.match.best]p1:
4902 //
4903 // -- if F is a static member function, ICS1(F) is defined such
4904 // that ICS1(F) is neither better nor worse than ICS1(G) for
4905 // any function G, and, symmetrically, ICS1(G) is neither
4906 // better nor worse than ICS1(F).
4907 unsigned StartArg = 0;
4908 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4909 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004910
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004911 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00004912 // A viable function F1 is defined to be a better function than another
4913 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004914 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004915 unsigned NumArgs = Cand1.Conversions.size();
4916 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4917 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004918 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004919 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4920 Cand2.Conversions[ArgIdx])) {
4921 case ImplicitConversionSequence::Better:
4922 // Cand1 has a better conversion sequence.
4923 HasBetterConversion = true;
4924 break;
4925
4926 case ImplicitConversionSequence::Worse:
4927 // Cand1 can't be better than Cand2.
4928 return false;
4929
4930 case ImplicitConversionSequence::Indistinguishable:
4931 // Do nothing.
4932 break;
4933 }
4934 }
4935
Mike Stump1eb44332009-09-09 15:08:12 +00004936 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004937 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004938 if (HasBetterConversion)
4939 return true;
4940
Mike Stump1eb44332009-09-09 15:08:12 +00004941 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004942 // specialization, or, if not that,
4943 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4944 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4945 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00004946
4947 // -- F1 and F2 are function template specializations, and the function
4948 // template for F1 is more specialized than the template for F2
4949 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00004950 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00004951 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4952 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004953 if (FunctionTemplateDecl *BetterTemplate
4954 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4955 Cand2.Function->getPrimaryTemplate(),
John McCall5769d612010-02-08 23:07:23 +00004956 Loc,
Douglas Gregor5d7d3752009-09-14 23:02:14 +00004957 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4958 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004959 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004960
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004961 // -- the context is an initialization by user-defined conversion
4962 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4963 // from the return type of F1 to the destination type (i.e.,
4964 // the type of the entity being initialized) is a better
4965 // conversion sequence than the standard conversion sequence
4966 // from the return type of F2 to the destination type.
Mike Stump1eb44332009-09-09 15:08:12 +00004967 if (Cand1.Function && Cand2.Function &&
4968 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004969 isa<CXXConversionDecl>(Cand2.Function)) {
4970 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4971 Cand2.FinalConversion)) {
4972 case ImplicitConversionSequence::Better:
4973 // Cand1 has a better conversion sequence.
4974 return true;
4975
4976 case ImplicitConversionSequence::Worse:
4977 // Cand1 can't be better than Cand2.
4978 return false;
4979
4980 case ImplicitConversionSequence::Indistinguishable:
4981 // Do nothing
4982 break;
4983 }
4984 }
4985
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004986 return false;
4987}
4988
Mike Stump1eb44332009-09-09 15:08:12 +00004989/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00004990/// within an overload candidate set.
4991///
4992/// \param CandidateSet the set of candidate functions.
4993///
4994/// \param Loc the location of the function name (or operator symbol) for
4995/// which overload resolution occurs.
4996///
Mike Stump1eb44332009-09-09 15:08:12 +00004997/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00004998/// function, Best points to the candidate function found.
4999///
5000/// \returns The result of overload resolution.
Douglas Gregor20093b42009-12-09 23:02:17 +00005001OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
5002 SourceLocation Loc,
5003 OverloadCandidateSet::iterator& Best) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005004 // Find the best viable function.
5005 Best = CandidateSet.end();
5006 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5007 Cand != CandidateSet.end(); ++Cand) {
5008 if (Cand->Viable) {
John McCall5769d612010-02-08 23:07:23 +00005009 if (Best == CandidateSet.end() ||
5010 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005011 Best = Cand;
5012 }
5013 }
5014
5015 // If we didn't find any viable functions, abort.
5016 if (Best == CandidateSet.end())
5017 return OR_No_Viable_Function;
5018
5019 // Make sure that this function is better than every other viable
5020 // function. If not, we have an ambiguity.
5021 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5022 Cand != CandidateSet.end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00005023 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005024 Cand != Best &&
John McCall5769d612010-02-08 23:07:23 +00005025 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005026 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005027 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005028 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005029 }
Mike Stump1eb44332009-09-09 15:08:12 +00005030
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005031 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005032 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00005033 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005034 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005035 return OR_Deleted;
5036
Douglas Gregore0762c92009-06-19 23:52:42 +00005037 // C++ [basic.def.odr]p2:
5038 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00005039 // when referred to from a potentially-evaluated expression. [Note: this
5040 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00005041 // (clause 13), user-defined conversions (12.3.2), allocation function for
5042 // placement new (5.3.4), as well as non-default initialization (8.5).
5043 if (Best->Function)
5044 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005045 return OR_Success;
5046}
5047
John McCall3c80f572010-01-12 02:15:36 +00005048namespace {
5049
5050enum OverloadCandidateKind {
5051 oc_function,
5052 oc_method,
5053 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00005054 oc_function_template,
5055 oc_method_template,
5056 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00005057 oc_implicit_default_constructor,
5058 oc_implicit_copy_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00005059 oc_implicit_copy_assignment
John McCall3c80f572010-01-12 02:15:36 +00005060};
5061
John McCall220ccbf2010-01-13 00:25:19 +00005062OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5063 FunctionDecl *Fn,
5064 std::string &Description) {
5065 bool isTemplate = false;
5066
5067 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5068 isTemplate = true;
5069 Description = S.getTemplateArgumentBindingsText(
5070 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5071 }
John McCallb1622a12010-01-06 09:43:14 +00005072
5073 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00005074 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00005075 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00005076
John McCall3c80f572010-01-12 02:15:36 +00005077 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5078 : oc_implicit_default_constructor;
John McCallb1622a12010-01-06 09:43:14 +00005079 }
5080
5081 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5082 // This actually gets spelled 'candidate function' for now, but
5083 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00005084 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00005085 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00005086
5087 assert(Meth->isCopyAssignment()
5088 && "implicit method is not copy assignment operator?");
John McCall3c80f572010-01-12 02:15:36 +00005089 return oc_implicit_copy_assignment;
5090 }
5091
John McCall220ccbf2010-01-13 00:25:19 +00005092 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00005093}
5094
5095} // end anonymous namespace
5096
5097// Notes the location of an overload candidate.
5098void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCall220ccbf2010-01-13 00:25:19 +00005099 std::string FnDesc;
5100 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5101 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5102 << (unsigned) K << FnDesc;
John McCallb1622a12010-01-06 09:43:14 +00005103}
5104
John McCall1d318332010-01-12 00:44:57 +00005105/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5106/// "lead" diagnostic; it will be given two arguments, the source and
5107/// target types of the conversion.
5108void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
5109 SourceLocation CaretLoc,
5110 const PartialDiagnostic &PDiag) {
5111 Diag(CaretLoc, PDiag)
5112 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
5113 for (AmbiguousConversionSequence::const_iterator
5114 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
5115 NoteOverloadCandidate(*I);
5116 }
John McCall81201622010-01-08 04:41:39 +00005117}
5118
John McCall1d318332010-01-12 00:44:57 +00005119namespace {
5120
John McCalladbb8f82010-01-13 09:16:55 +00005121void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5122 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5123 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00005124 assert(Cand->Function && "for now, candidate must be a function");
5125 FunctionDecl *Fn = Cand->Function;
5126
5127 // There's a conversion slot for the object argument if this is a
5128 // non-constructor method. Note that 'I' corresponds the
5129 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00005130 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00005131 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00005132 if (I == 0)
5133 isObjectArgument = true;
5134 else
5135 I--;
John McCall220ccbf2010-01-13 00:25:19 +00005136 }
5137
John McCall220ccbf2010-01-13 00:25:19 +00005138 std::string FnDesc;
5139 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5140
John McCalladbb8f82010-01-13 09:16:55 +00005141 Expr *FromExpr = Conv.Bad.FromExpr;
5142 QualType FromTy = Conv.Bad.getFromType();
5143 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00005144
John McCall5920dbb2010-02-02 02:42:52 +00005145 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00005146 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00005147 Expr *E = FromExpr->IgnoreParens();
5148 if (isa<UnaryOperator>(E))
5149 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00005150 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00005151
5152 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5153 << (unsigned) FnKind << FnDesc
5154 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5155 << ToTy << Name << I+1;
5156 return;
5157 }
5158
John McCall258b2032010-01-23 08:10:49 +00005159 // Do some hand-waving analysis to see if the non-viability is due
5160 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00005161 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5162 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5163 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5164 CToTy = RT->getPointeeType();
5165 else {
5166 // TODO: detect and diagnose the full richness of const mismatches.
5167 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5168 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5169 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5170 }
5171
5172 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5173 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5174 // It is dumb that we have to do this here.
5175 while (isa<ArrayType>(CFromTy))
5176 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5177 while (isa<ArrayType>(CToTy))
5178 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5179
5180 Qualifiers FromQs = CFromTy.getQualifiers();
5181 Qualifiers ToQs = CToTy.getQualifiers();
5182
5183 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5184 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5185 << (unsigned) FnKind << FnDesc
5186 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5187 << FromTy
5188 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5189 << (unsigned) isObjectArgument << I+1;
5190 return;
5191 }
5192
5193 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5194 assert(CVR && "unexpected qualifiers mismatch");
5195
5196 if (isObjectArgument) {
5197 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5198 << (unsigned) FnKind << FnDesc
5199 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5200 << FromTy << (CVR - 1);
5201 } else {
5202 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5203 << (unsigned) FnKind << FnDesc
5204 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5205 << FromTy << (CVR - 1) << I+1;
5206 }
5207 return;
5208 }
5209
John McCall258b2032010-01-23 08:10:49 +00005210 // Diagnose references or pointers to incomplete types differently,
5211 // since it's far from impossible that the incompleteness triggered
5212 // the failure.
5213 QualType TempFromTy = FromTy.getNonReferenceType();
5214 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5215 TempFromTy = PTy->getPointeeType();
5216 if (TempFromTy->isIncompleteType()) {
5217 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5218 << (unsigned) FnKind << FnDesc
5219 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5220 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5221 return;
5222 }
5223
John McCall651f3ee2010-01-14 03:28:57 +00005224 // TODO: specialize more based on the kind of mismatch
John McCall220ccbf2010-01-13 00:25:19 +00005225 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5226 << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00005227 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalle81e15e2010-01-14 00:56:20 +00005228 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCalladbb8f82010-01-13 09:16:55 +00005229}
5230
5231void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5232 unsigned NumFormalArgs) {
5233 // TODO: treat calls to a missing default constructor as a special case
5234
5235 FunctionDecl *Fn = Cand->Function;
5236 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5237
5238 unsigned MinParams = Fn->getMinRequiredArguments();
5239
5240 // at least / at most / exactly
Douglas Gregora18592e2010-05-08 18:13:28 +00005241 // FIXME: variadic templates "at most" should account for parameter packs
John McCalladbb8f82010-01-13 09:16:55 +00005242 unsigned mode, modeCount;
5243 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00005244 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5245 (Cand->FailureKind == ovl_fail_bad_deduction &&
5246 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCalladbb8f82010-01-13 09:16:55 +00005247 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5248 mode = 0; // "at least"
5249 else
5250 mode = 2; // "exactly"
5251 modeCount = MinParams;
5252 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00005253 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5254 (Cand->FailureKind == ovl_fail_bad_deduction &&
5255 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00005256 if (MinParams != FnTy->getNumArgs())
5257 mode = 1; // "at most"
5258 else
5259 mode = 2; // "exactly"
5260 modeCount = FnTy->getNumArgs();
5261 }
5262
5263 std::string Description;
5264 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5265
5266 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregora18592e2010-05-08 18:13:28 +00005267 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5268 << modeCount << NumFormalArgs;
John McCall220ccbf2010-01-13 00:25:19 +00005269}
5270
John McCall342fec42010-02-01 18:53:26 +00005271/// Diagnose a failed template-argument deduction.
5272void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5273 Expr **Args, unsigned NumArgs) {
5274 FunctionDecl *Fn = Cand->Function; // pattern
5275
Douglas Gregora9333192010-05-08 17:41:32 +00005276 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00005277 NamedDecl *ParamD;
5278 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5279 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5280 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00005281 switch (Cand->DeductionFailure.Result) {
5282 case Sema::TDK_Success:
5283 llvm_unreachable("TDK_success while diagnosing bad deduction");
5284
5285 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00005286 assert(ParamD && "no parameter found for incomplete deduction result");
5287 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5288 << ParamD->getDeclName();
5289 return;
5290 }
5291
Douglas Gregora9333192010-05-08 17:41:32 +00005292 case Sema::TDK_Inconsistent:
5293 case Sema::TDK_InconsistentQuals: {
Douglas Gregorf1a84452010-05-08 19:15:54 +00005294 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00005295 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00005296 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00005297 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00005298 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00005299 which = 1;
5300 else {
Douglas Gregora9333192010-05-08 17:41:32 +00005301 which = 2;
5302 }
5303
5304 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5305 << which << ParamD->getDeclName()
5306 << *Cand->DeductionFailure.getFirstArg()
5307 << *Cand->DeductionFailure.getSecondArg();
5308 return;
5309 }
Douglas Gregora18592e2010-05-08 18:13:28 +00005310
Douglas Gregorf1a84452010-05-08 19:15:54 +00005311 case Sema::TDK_InvalidExplicitArguments:
5312 assert(ParamD && "no parameter found for invalid explicit arguments");
5313 if (ParamD->getDeclName())
5314 S.Diag(Fn->getLocation(),
5315 diag::note_ovl_candidate_explicit_arg_mismatch_named)
5316 << ParamD->getDeclName();
5317 else {
5318 int index = 0;
5319 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5320 index = TTP->getIndex();
5321 else if (NonTypeTemplateParmDecl *NTTP
5322 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5323 index = NTTP->getIndex();
5324 else
5325 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
5326 S.Diag(Fn->getLocation(),
5327 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
5328 << (index + 1);
5329 }
5330 return;
5331
Douglas Gregora18592e2010-05-08 18:13:28 +00005332 case Sema::TDK_TooManyArguments:
5333 case Sema::TDK_TooFewArguments:
5334 DiagnoseArityMismatch(S, Cand, NumArgs);
5335 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00005336
5337 case Sema::TDK_InstantiationDepth:
5338 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
5339 return;
5340
5341 case Sema::TDK_SubstitutionFailure: {
5342 std::string ArgString;
5343 if (TemplateArgumentList *Args
5344 = Cand->DeductionFailure.getTemplateArgumentList())
5345 ArgString = S.getTemplateArgumentBindingsText(
5346 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
5347 *Args);
5348 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
5349 << ArgString;
5350 return;
5351 }
Douglas Gregora9333192010-05-08 17:41:32 +00005352
John McCall342fec42010-02-01 18:53:26 +00005353 // TODO: diagnose these individually, then kill off
5354 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00005355 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00005356 case Sema::TDK_FailedOverloadResolution:
5357 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
5358 return;
5359 }
5360}
5361
5362/// Generates a 'note' diagnostic for an overload candidate. We've
5363/// already generated a primary error at the call site.
5364///
5365/// It really does need to be a single diagnostic with its caret
5366/// pointed at the candidate declaration. Yes, this creates some
5367/// major challenges of technical writing. Yes, this makes pointing
5368/// out problems with specific arguments quite awkward. It's still
5369/// better than generating twenty screens of text for every failed
5370/// overload.
5371///
5372/// It would be great to be able to express per-candidate problems
5373/// more richly for those diagnostic clients that cared, but we'd
5374/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00005375void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
5376 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00005377 FunctionDecl *Fn = Cand->Function;
5378
John McCall81201622010-01-08 04:41:39 +00005379 // Note deleted candidates, but only if they're viable.
John McCall3c80f572010-01-12 02:15:36 +00005380 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCall220ccbf2010-01-13 00:25:19 +00005381 std::string FnDesc;
5382 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00005383
5384 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00005385 << FnKind << FnDesc << Fn->isDeleted();
John McCalla1d7d622010-01-08 00:58:21 +00005386 return;
John McCall81201622010-01-08 04:41:39 +00005387 }
5388
John McCall220ccbf2010-01-13 00:25:19 +00005389 // We don't really have anything else to say about viable candidates.
5390 if (Cand->Viable) {
5391 S.NoteOverloadCandidate(Fn);
5392 return;
5393 }
John McCall1d318332010-01-12 00:44:57 +00005394
John McCalladbb8f82010-01-13 09:16:55 +00005395 switch (Cand->FailureKind) {
5396 case ovl_fail_too_many_arguments:
5397 case ovl_fail_too_few_arguments:
5398 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00005399
John McCalladbb8f82010-01-13 09:16:55 +00005400 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00005401 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5402
John McCall717e8912010-01-23 05:17:32 +00005403 case ovl_fail_trivial_conversion:
5404 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00005405 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00005406 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00005407
John McCallb1bdc622010-02-25 01:37:24 +00005408 case ovl_fail_bad_conversion: {
5409 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5410 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00005411 if (Cand->Conversions[I].isBad())
5412 return DiagnoseBadConversion(S, Cand, I);
5413
5414 // FIXME: this currently happens when we're called from SemaInit
5415 // when user-conversion overload fails. Figure out how to handle
5416 // those conditions and diagnose them well.
5417 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00005418 }
John McCallb1bdc622010-02-25 01:37:24 +00005419 }
John McCalla1d7d622010-01-08 00:58:21 +00005420}
5421
5422void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5423 // Desugar the type of the surrogate down to a function type,
5424 // retaining as many typedefs as possible while still showing
5425 // the function type (and, therefore, its parameter types).
5426 QualType FnType = Cand->Surrogate->getConversionType();
5427 bool isLValueReference = false;
5428 bool isRValueReference = false;
5429 bool isPointer = false;
5430 if (const LValueReferenceType *FnTypeRef =
5431 FnType->getAs<LValueReferenceType>()) {
5432 FnType = FnTypeRef->getPointeeType();
5433 isLValueReference = true;
5434 } else if (const RValueReferenceType *FnTypeRef =
5435 FnType->getAs<RValueReferenceType>()) {
5436 FnType = FnTypeRef->getPointeeType();
5437 isRValueReference = true;
5438 }
5439 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5440 FnType = FnTypePtr->getPointeeType();
5441 isPointer = true;
5442 }
5443 // Desugar down to a function type.
5444 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5445 // Reconstruct the pointer/reference as appropriate.
5446 if (isPointer) FnType = S.Context.getPointerType(FnType);
5447 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5448 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5449
5450 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5451 << FnType;
5452}
5453
5454void NoteBuiltinOperatorCandidate(Sema &S,
5455 const char *Opc,
5456 SourceLocation OpLoc,
5457 OverloadCandidate *Cand) {
5458 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5459 std::string TypeStr("operator");
5460 TypeStr += Opc;
5461 TypeStr += "(";
5462 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5463 if (Cand->Conversions.size() == 1) {
5464 TypeStr += ")";
5465 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5466 } else {
5467 TypeStr += ", ";
5468 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5469 TypeStr += ")";
5470 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5471 }
5472}
5473
5474void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5475 OverloadCandidate *Cand) {
5476 unsigned NoOperands = Cand->Conversions.size();
5477 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5478 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00005479 if (ICS.isBad()) break; // all meaningless after first invalid
5480 if (!ICS.isAmbiguous()) continue;
5481
5482 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005483 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00005484 }
5485}
5486
John McCall1b77e732010-01-15 23:32:50 +00005487SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5488 if (Cand->Function)
5489 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00005490 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00005491 return Cand->Surrogate->getLocation();
5492 return SourceLocation();
5493}
5494
John McCallbf65c0b2010-01-12 00:48:53 +00005495struct CompareOverloadCandidatesForDisplay {
5496 Sema &S;
5497 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00005498
5499 bool operator()(const OverloadCandidate *L,
5500 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00005501 // Fast-path this check.
5502 if (L == R) return false;
5503
John McCall81201622010-01-08 04:41:39 +00005504 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00005505 if (L->Viable) {
5506 if (!R->Viable) return true;
5507
5508 // TODO: introduce a tri-valued comparison for overload
5509 // candidates. Would be more worthwhile if we had a sort
5510 // that could exploit it.
John McCall5769d612010-02-08 23:07:23 +00005511 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5512 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00005513 } else if (R->Viable)
5514 return false;
John McCall81201622010-01-08 04:41:39 +00005515
John McCall1b77e732010-01-15 23:32:50 +00005516 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00005517
John McCall1b77e732010-01-15 23:32:50 +00005518 // Criteria by which we can sort non-viable candidates:
5519 if (!L->Viable) {
5520 // 1. Arity mismatches come after other candidates.
5521 if (L->FailureKind == ovl_fail_too_many_arguments ||
5522 L->FailureKind == ovl_fail_too_few_arguments)
5523 return false;
5524 if (R->FailureKind == ovl_fail_too_many_arguments ||
5525 R->FailureKind == ovl_fail_too_few_arguments)
5526 return true;
John McCall81201622010-01-08 04:41:39 +00005527
John McCall717e8912010-01-23 05:17:32 +00005528 // 2. Bad conversions come first and are ordered by the number
5529 // of bad conversions and quality of good conversions.
5530 if (L->FailureKind == ovl_fail_bad_conversion) {
5531 if (R->FailureKind != ovl_fail_bad_conversion)
5532 return true;
5533
5534 // If there's any ordering between the defined conversions...
5535 // FIXME: this might not be transitive.
5536 assert(L->Conversions.size() == R->Conversions.size());
5537
5538 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00005539 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5540 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall717e8912010-01-23 05:17:32 +00005541 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5542 R->Conversions[I])) {
5543 case ImplicitConversionSequence::Better:
5544 leftBetter++;
5545 break;
5546
5547 case ImplicitConversionSequence::Worse:
5548 leftBetter--;
5549 break;
5550
5551 case ImplicitConversionSequence::Indistinguishable:
5552 break;
5553 }
5554 }
5555 if (leftBetter > 0) return true;
5556 if (leftBetter < 0) return false;
5557
5558 } else if (R->FailureKind == ovl_fail_bad_conversion)
5559 return false;
5560
John McCall1b77e732010-01-15 23:32:50 +00005561 // TODO: others?
5562 }
5563
5564 // Sort everything else by location.
5565 SourceLocation LLoc = GetLocationForCandidate(L);
5566 SourceLocation RLoc = GetLocationForCandidate(R);
5567
5568 // Put candidates without locations (e.g. builtins) at the end.
5569 if (LLoc.isInvalid()) return false;
5570 if (RLoc.isInvalid()) return true;
5571
5572 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00005573 }
5574};
5575
John McCall717e8912010-01-23 05:17:32 +00005576/// CompleteNonViableCandidate - Normally, overload resolution only
5577/// computes up to the first
5578void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5579 Expr **Args, unsigned NumArgs) {
5580 assert(!Cand->Viable);
5581
5582 // Don't do anything on failures other than bad conversion.
5583 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5584
5585 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00005586 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCall717e8912010-01-23 05:17:32 +00005587 unsigned ConvCount = Cand->Conversions.size();
5588 while (true) {
5589 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5590 ConvIdx++;
5591 if (Cand->Conversions[ConvIdx - 1].isBad())
5592 break;
5593 }
5594
5595 if (ConvIdx == ConvCount)
5596 return;
5597
John McCallb1bdc622010-02-25 01:37:24 +00005598 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
5599 "remaining conversion is initialized?");
5600
Douglas Gregor23ef6c02010-04-16 17:45:54 +00005601 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00005602 // operation somehow.
5603 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00005604
5605 const FunctionProtoType* Proto;
5606 unsigned ArgIdx = ConvIdx;
5607
5608 if (Cand->IsSurrogate) {
5609 QualType ConvType
5610 = Cand->Surrogate->getConversionType().getNonReferenceType();
5611 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5612 ConvType = ConvPtrType->getPointeeType();
5613 Proto = ConvType->getAs<FunctionProtoType>();
5614 ArgIdx--;
5615 } else if (Cand->Function) {
5616 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
5617 if (isa<CXXMethodDecl>(Cand->Function) &&
5618 !isa<CXXConstructorDecl>(Cand->Function))
5619 ArgIdx--;
5620 } else {
5621 // Builtin binary operator with a bad first conversion.
5622 assert(ConvCount <= 3);
5623 for (; ConvIdx != ConvCount; ++ConvIdx)
5624 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005625 = TryCopyInitialization(S, Args[ConvIdx],
5626 Cand->BuiltinTypes.ParamTypes[ConvIdx],
5627 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00005628 /*InOverloadResolution*/ true);
John McCall717e8912010-01-23 05:17:32 +00005629 return;
5630 }
5631
5632 // Fill in the rest of the conversions.
5633 unsigned NumArgsInProto = Proto->getNumArgs();
5634 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
5635 if (ArgIdx < NumArgsInProto)
5636 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005637 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
5638 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00005639 /*InOverloadResolution=*/true);
John McCall717e8912010-01-23 05:17:32 +00005640 else
5641 Cand->Conversions[ConvIdx].setEllipsis();
5642 }
5643}
5644
John McCalla1d7d622010-01-08 00:58:21 +00005645} // end anonymous namespace
5646
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005647/// PrintOverloadCandidates - When overload resolution fails, prints
5648/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00005649/// set.
Mike Stump1eb44332009-09-09 15:08:12 +00005650void
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005651Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall81201622010-01-08 04:41:39 +00005652 OverloadCandidateDisplayKind OCD,
John McCallcbce6062010-01-12 07:18:19 +00005653 Expr **Args, unsigned NumArgs,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005654 const char *Opc,
Fariborz Jahanian16a5eac2009-10-09 00:13:15 +00005655 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00005656 // Sort the candidates by viability and position. Sorting directly would
5657 // be prohibitive, so we make a set of pointers and sort those.
5658 llvm::SmallVector<OverloadCandidate*, 32> Cands;
5659 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
5660 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5661 LastCand = CandidateSet.end();
John McCall717e8912010-01-23 05:17:32 +00005662 Cand != LastCand; ++Cand) {
5663 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00005664 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00005665 else if (OCD == OCD_AllCandidates) {
5666 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
5667 Cands.push_back(Cand);
5668 }
5669 }
5670
John McCallbf65c0b2010-01-12 00:48:53 +00005671 std::sort(Cands.begin(), Cands.end(),
5672 CompareOverloadCandidatesForDisplay(*this));
John McCall81201622010-01-08 04:41:39 +00005673
John McCall1d318332010-01-12 00:44:57 +00005674 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00005675
John McCall81201622010-01-08 04:41:39 +00005676 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
5677 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
5678 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00005679
John McCalla1d7d622010-01-08 00:58:21 +00005680 if (Cand->Function)
John McCall220ccbf2010-01-13 00:25:19 +00005681 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00005682 else if (Cand->IsSurrogate)
5683 NoteSurrogateCandidate(*this, Cand);
5684
5685 // This a builtin candidate. We do not, in general, want to list
5686 // every possible builtin candidate.
John McCall1d318332010-01-12 00:44:57 +00005687 else if (Cand->Viable) {
5688 // Generally we only see ambiguities including viable builtin
5689 // operators if overload resolution got screwed up by an
5690 // ambiguous user-defined conversion.
5691 //
5692 // FIXME: It's quite possible for different conversions to see
5693 // different ambiguities, though.
5694 if (!ReportedAmbiguousConversions) {
5695 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
5696 ReportedAmbiguousConversions = true;
5697 }
John McCalla1d7d622010-01-08 00:58:21 +00005698
John McCall1d318332010-01-12 00:44:57 +00005699 // If this is a viable builtin, print it.
John McCalla1d7d622010-01-08 00:58:21 +00005700 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005701 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005702 }
5703}
5704
John McCall9aa472c2010-03-19 07:35:19 +00005705static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCallc373d482010-01-27 01:50:18 +00005706 if (isa<UnresolvedLookupExpr>(E))
John McCall9aa472c2010-03-19 07:35:19 +00005707 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00005708
John McCall9aa472c2010-03-19 07:35:19 +00005709 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00005710}
5711
Douglas Gregor904eed32008-11-10 20:40:00 +00005712/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
5713/// an overloaded function (C++ [over.over]), where @p From is an
5714/// expression with overloaded function type and @p ToType is the type
5715/// we're trying to resolve to. For example:
5716///
5717/// @code
5718/// int f(double);
5719/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00005720///
Douglas Gregor904eed32008-11-10 20:40:00 +00005721/// int (*pfd)(double) = f; // selects f(double)
5722/// @endcode
5723///
5724/// This routine returns the resulting FunctionDecl if it could be
5725/// resolved, and NULL otherwise. When @p Complain is true, this
5726/// routine will emit diagnostics if there is an error.
5727FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00005728Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall6bb80172010-03-30 21:47:33 +00005729 bool Complain,
5730 DeclAccessPair &FoundResult) {
Douglas Gregor904eed32008-11-10 20:40:00 +00005731 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00005732 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00005733 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00005734 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00005735 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00005736 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00005737 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00005738 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00005739 FunctionType = MemTypePtr->getPointeeType();
5740 IsMember = true;
5741 }
Douglas Gregor904eed32008-11-10 20:40:00 +00005742
Douglas Gregor904eed32008-11-10 20:40:00 +00005743 // C++ [over.over]p1:
5744 // [...] [Note: any redundant set of parentheses surrounding the
5745 // overloaded function name is ignored (5.1). ]
Douglas Gregor904eed32008-11-10 20:40:00 +00005746 // C++ [over.over]p1:
5747 // [...] The overloaded function name can be preceded by the &
5748 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00005749 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5750 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
5751 if (OvlExpr->hasExplicitTemplateArgs()) {
5752 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5753 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregor904eed32008-11-10 20:40:00 +00005754 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00005755
5756 // We expect a pointer or reference to function, or a function pointer.
5757 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
5758 if (!FunctionType->isFunctionType()) {
5759 if (Complain)
5760 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
5761 << OvlExpr->getName() << ToType;
5762
5763 return 0;
5764 }
5765
5766 assert(From->getType() == Context.OverloadTy);
Douglas Gregor904eed32008-11-10 20:40:00 +00005767
Douglas Gregor904eed32008-11-10 20:40:00 +00005768 // Look through all of the overloaded functions, searching for one
5769 // whose type matches exactly.
John McCall9aa472c2010-03-19 07:35:19 +00005770 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb7a09262010-04-01 18:32:35 +00005771 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
5772
Douglas Gregor00aeb522009-07-08 23:33:52 +00005773 bool FoundNonTemplateFunction = false;
John McCall7bb12da2010-02-02 06:20:04 +00005774 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5775 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00005776 // Look through any using declarations to find the underlying function.
5777 NamedDecl *Fn = (*I)->getUnderlyingDecl();
5778
Douglas Gregor904eed32008-11-10 20:40:00 +00005779 // C++ [over.over]p3:
5780 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00005781 // targets of type "pointer-to-function" or "reference-to-function."
5782 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00005783 // type "pointer-to-member-function."
5784 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00005785
Mike Stump1eb44332009-09-09 15:08:12 +00005786 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthbd647292009-12-29 06:17:27 +00005787 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump1eb44332009-09-09 15:08:12 +00005788 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00005789 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00005790 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00005791 // static when converting to member pointer.
5792 if (Method->isStatic() == IsMember)
5793 continue;
5794 } else if (IsMember)
5795 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00005796
Douglas Gregor00aeb522009-07-08 23:33:52 +00005797 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00005798 // If the name is a function template, template argument deduction is
5799 // done (14.8.2.2), and if the argument deduction succeeds, the
5800 // resulting template argument list is used to generate a single
5801 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00005802 // overloaded functions considered.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005803 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor83314aa2009-07-08 20:55:45 +00005804 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00005805 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor83314aa2009-07-08 20:55:45 +00005806 if (TemplateDeductionResult Result
John McCall7bb12da2010-02-02 06:20:04 +00005807 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00005808 FunctionType, Specialization, Info)) {
5809 // FIXME: make a note of the failed deduction for diagnostics.
5810 (void)Result;
5811 } else {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00005812 // FIXME: If the match isn't exact, shouldn't we just drop this as
5813 // a candidate? Find a testcase before changing the code.
Mike Stump1eb44332009-09-09 15:08:12 +00005814 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00005815 == Context.getCanonicalType(Specialization->getType()));
John McCall9aa472c2010-03-19 07:35:19 +00005816 Matches.push_back(std::make_pair(I.getPair(),
5817 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor83314aa2009-07-08 20:55:45 +00005818 }
John McCallba135432009-11-21 08:51:07 +00005819
5820 continue;
Douglas Gregor83314aa2009-07-08 20:55:45 +00005821 }
Mike Stump1eb44332009-09-09 15:08:12 +00005822
Chandler Carruthbd647292009-12-29 06:17:27 +00005823 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00005824 // Skip non-static functions when converting to pointer, and static
5825 // when converting to member pointer.
5826 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00005827 continue;
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005828
5829 // If we have explicit template arguments, skip non-templates.
John McCall7bb12da2010-02-02 06:20:04 +00005830 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00005831 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00005832 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00005833 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00005834
Chandler Carruthbd647292009-12-29 06:17:27 +00005835 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00005836 QualType ResultTy;
5837 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5838 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5839 ResultTy)) {
John McCall9aa472c2010-03-19 07:35:19 +00005840 Matches.push_back(std::make_pair(I.getPair(),
5841 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00005842 FoundNonTemplateFunction = true;
5843 }
Mike Stump1eb44332009-09-09 15:08:12 +00005844 }
Douglas Gregor904eed32008-11-10 20:40:00 +00005845 }
5846
Douglas Gregor00aeb522009-07-08 23:33:52 +00005847 // If there were 0 or 1 matches, we're done.
Douglas Gregor1a8cf732010-04-14 23:11:21 +00005848 if (Matches.empty()) {
5849 if (Complain) {
5850 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
5851 << OvlExpr->getName() << FunctionType;
5852 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5853 E = OvlExpr->decls_end();
5854 I != E; ++I)
5855 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
5856 NoteOverloadCandidate(F);
5857 }
5858
Douglas Gregor00aeb522009-07-08 23:33:52 +00005859 return 0;
Douglas Gregor1a8cf732010-04-14 23:11:21 +00005860 } else if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00005861 FunctionDecl *Result = Matches[0].second;
John McCall6bb80172010-03-30 21:47:33 +00005862 FoundResult = Matches[0].first;
Sebastian Redl07ab2022009-10-17 21:12:09 +00005863 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCallc373d482010-01-27 01:50:18 +00005864 if (Complain)
John McCall6bb80172010-03-30 21:47:33 +00005865 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redl07ab2022009-10-17 21:12:09 +00005866 return Result;
5867 }
Douglas Gregor00aeb522009-07-08 23:33:52 +00005868
5869 // C++ [over.over]p4:
5870 // If more than one function is selected, [...]
Douglas Gregor312a2022009-09-26 03:56:17 +00005871 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005872 // [...] and any given function template specialization F1 is
5873 // eliminated if the set contains a second function template
5874 // specialization whose function template is more specialized
5875 // than the function template of F1 according to the partial
5876 // ordering rules of 14.5.5.2.
5877
5878 // The algorithm specified above is quadratic. We instead use a
5879 // two-pass algorithm (similar to the one used to identify the
5880 // best viable function in an overload set) that identifies the
5881 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00005882
5883 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
5884 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5885 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCallc373d482010-01-27 01:50:18 +00005886
5887 UnresolvedSetIterator Result =
John McCall9aa472c2010-03-19 07:35:19 +00005888 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redl07ab2022009-10-17 21:12:09 +00005889 TPOC_Other, From->getLocStart(),
5890 PDiag(),
5891 PDiag(diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00005892 << Matches[0].second->getDeclName(),
John McCall220ccbf2010-01-13 00:25:19 +00005893 PDiag(diag::note_ovl_candidate)
5894 << (unsigned) oc_function_template);
John McCall9aa472c2010-03-19 07:35:19 +00005895 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCallc373d482010-01-27 01:50:18 +00005896 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall6bb80172010-03-30 21:47:33 +00005897 FoundResult = Matches[Result - MatchesCopy.begin()].first;
John McCallb697e082010-05-06 18:15:07 +00005898 if (Complain) {
John McCall6bb80172010-03-30 21:47:33 +00005899 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCallb697e082010-05-06 18:15:07 +00005900 DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc());
5901 }
John McCallc373d482010-01-27 01:50:18 +00005902 return cast<FunctionDecl>(*Result);
Douglas Gregor00aeb522009-07-08 23:33:52 +00005903 }
Mike Stump1eb44332009-09-09 15:08:12 +00005904
Douglas Gregor312a2022009-09-26 03:56:17 +00005905 // [...] any function template specializations in the set are
5906 // eliminated if the set also contains a non-template function, [...]
John McCallc373d482010-01-27 01:50:18 +00005907 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCall9aa472c2010-03-19 07:35:19 +00005908 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCallc373d482010-01-27 01:50:18 +00005909 ++I;
5910 else {
John McCall9aa472c2010-03-19 07:35:19 +00005911 Matches[I] = Matches[--N];
5912 Matches.set_size(N);
John McCallc373d482010-01-27 01:50:18 +00005913 }
5914 }
Douglas Gregor312a2022009-09-26 03:56:17 +00005915
Mike Stump1eb44332009-09-09 15:08:12 +00005916 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00005917 // selected function.
John McCallc373d482010-01-27 01:50:18 +00005918 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00005919 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall6bb80172010-03-30 21:47:33 +00005920 FoundResult = Matches[0].first;
John McCallb697e082010-05-06 18:15:07 +00005921 if (Complain) {
John McCall9aa472c2010-03-19 07:35:19 +00005922 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
John McCallb697e082010-05-06 18:15:07 +00005923 DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc());
5924 }
John McCall9aa472c2010-03-19 07:35:19 +00005925 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redl07ab2022009-10-17 21:12:09 +00005926 }
Mike Stump1eb44332009-09-09 15:08:12 +00005927
Douglas Gregor00aeb522009-07-08 23:33:52 +00005928 // FIXME: We should probably return the same thing that BestViableFunction
5929 // returns (even if we issue the diagnostics here).
5930 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00005931 << Matches[0].second->getDeclName();
5932 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5933 NoteOverloadCandidate(Matches[I].second);
Douglas Gregor904eed32008-11-10 20:40:00 +00005934 return 0;
5935}
5936
Douglas Gregor4b52e252009-12-21 23:17:24 +00005937/// \brief Given an expression that refers to an overloaded function, try to
5938/// resolve that overloaded function expression down to a single function.
5939///
5940/// This routine can only resolve template-ids that refer to a single function
5941/// template, where that template-id refers to a single template whose template
5942/// arguments are either provided by the template-id or have defaults,
5943/// as described in C++0x [temp.arg.explicit]p3.
5944FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5945 // C++ [over.over]p1:
5946 // [...] [Note: any redundant set of parentheses surrounding the
5947 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00005948 // C++ [over.over]p1:
5949 // [...] The overloaded function name can be preceded by the &
5950 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00005951
5952 if (From->getType() != Context.OverloadTy)
5953 return 0;
5954
5955 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor4b52e252009-12-21 23:17:24 +00005956
5957 // If we didn't actually find any template-ids, we're done.
John McCall7bb12da2010-02-02 06:20:04 +00005958 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00005959 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00005960
5961 TemplateArgumentListInfo ExplicitTemplateArgs;
5962 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor4b52e252009-12-21 23:17:24 +00005963
5964 // Look through all of the overloaded functions, searching for one
5965 // whose type matches exactly.
5966 FunctionDecl *Matched = 0;
John McCall7bb12da2010-02-02 06:20:04 +00005967 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5968 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00005969 // C++0x [temp.arg.explicit]p3:
5970 // [...] In contexts where deduction is done and fails, or in contexts
5971 // where deduction is not done, if a template argument list is
5972 // specified and it, along with any default template arguments,
5973 // identifies a single function template specialization, then the
5974 // template-id is an lvalue for the function template specialization.
5975 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
5976
5977 // C++ [over.over]p2:
5978 // If the name is a function template, template argument deduction is
5979 // done (14.8.2.2), and if the argument deduction succeeds, the
5980 // resulting template argument list is used to generate a single
5981 // function template specialization, which is added to the set of
5982 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00005983 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00005984 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00005985 if (TemplateDeductionResult Result
5986 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5987 Specialization, Info)) {
5988 // FIXME: make a note of the failed deduction for diagnostics.
5989 (void)Result;
5990 continue;
5991 }
5992
5993 // Multiple matches; we can't resolve to a single declaration.
5994 if (Matched)
5995 return 0;
5996
5997 Matched = Specialization;
5998 }
5999
6000 return Matched;
6001}
6002
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006003/// \brief Add a single candidate to the overload set.
6004static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00006005 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00006006 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006007 Expr **Args, unsigned NumArgs,
6008 OverloadCandidateSet &CandidateSet,
6009 bool PartialOverloading) {
John McCall9aa472c2010-03-19 07:35:19 +00006010 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00006011 if (isa<UsingShadowDecl>(Callee))
6012 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6013
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006014 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00006015 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCall9aa472c2010-03-19 07:35:19 +00006016 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00006017 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006018 return;
John McCallba135432009-11-21 08:51:07 +00006019 }
6020
6021 if (FunctionTemplateDecl *FuncTemplate
6022 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00006023 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6024 ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00006025 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00006026 return;
6027 }
6028
6029 assert(false && "unhandled case in overloaded call candidate");
6030
6031 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006032}
6033
6034/// \brief Add the overload candidates named by callee and/or found by argument
6035/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00006036void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006037 Expr **Args, unsigned NumArgs,
6038 OverloadCandidateSet &CandidateSet,
6039 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00006040
6041#ifndef NDEBUG
6042 // Verify that ArgumentDependentLookup is consistent with the rules
6043 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006044 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006045 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6046 // and let Y be the lookup set produced by argument dependent
6047 // lookup (defined as follows). If X contains
6048 //
6049 // -- a declaration of a class member, or
6050 //
6051 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00006052 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006053 //
6054 // -- a declaration that is neither a function or a function
6055 // template
6056 //
6057 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00006058
John McCall3b4294e2009-12-16 12:17:52 +00006059 if (ULE->requiresADL()) {
6060 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6061 E = ULE->decls_end(); I != E; ++I) {
6062 assert(!(*I)->getDeclContext()->isRecord());
6063 assert(isa<UsingShadowDecl>(*I) ||
6064 !(*I)->getDeclContext()->isFunctionOrMethod());
6065 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00006066 }
6067 }
6068#endif
6069
John McCall3b4294e2009-12-16 12:17:52 +00006070 // It would be nice to avoid this copy.
6071 TemplateArgumentListInfo TABuffer;
6072 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6073 if (ULE->hasExplicitTemplateArgs()) {
6074 ULE->copyTemplateArgumentsInto(TABuffer);
6075 ExplicitTemplateArgs = &TABuffer;
6076 }
6077
6078 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6079 E = ULE->decls_end(); I != E; ++I)
John McCall9aa472c2010-03-19 07:35:19 +00006080 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00006081 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006082 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00006083
John McCall3b4294e2009-12-16 12:17:52 +00006084 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00006085 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6086 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006087 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006088 CandidateSet,
6089 PartialOverloading);
6090}
John McCall578b69b2009-12-16 08:11:27 +00006091
John McCall3b4294e2009-12-16 12:17:52 +00006092static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
6093 Expr **Args, unsigned NumArgs) {
6094 Fn->Destroy(SemaRef.Context);
6095 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
6096 Args[Arg]->Destroy(SemaRef.Context);
6097 return SemaRef.ExprError();
6098}
6099
John McCall578b69b2009-12-16 08:11:27 +00006100/// Attempts to recover from a call where no functions were found.
6101///
6102/// Returns true if new candidates were found.
John McCall3b4294e2009-12-16 12:17:52 +00006103static Sema::OwningExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006104BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00006105 UnresolvedLookupExpr *ULE,
6106 SourceLocation LParenLoc,
6107 Expr **Args, unsigned NumArgs,
6108 SourceLocation *CommaLocs,
6109 SourceLocation RParenLoc) {
John McCall578b69b2009-12-16 08:11:27 +00006110
6111 CXXScopeSpec SS;
6112 if (ULE->getQualifier()) {
6113 SS.setScopeRep(ULE->getQualifier());
6114 SS.setRange(ULE->getQualifierRange());
6115 }
6116
John McCall3b4294e2009-12-16 12:17:52 +00006117 TemplateArgumentListInfo TABuffer;
6118 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6119 if (ULE->hasExplicitTemplateArgs()) {
6120 ULE->copyTemplateArgumentsInto(TABuffer);
6121 ExplicitTemplateArgs = &TABuffer;
6122 }
6123
John McCall578b69b2009-12-16 08:11:27 +00006124 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6125 Sema::LookupOrdinaryName);
Douglas Gregor91f7ac72010-05-18 16:14:23 +00006126 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCall3b4294e2009-12-16 12:17:52 +00006127 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCall578b69b2009-12-16 08:11:27 +00006128
John McCall3b4294e2009-12-16 12:17:52 +00006129 assert(!R.empty() && "lookup results empty despite recovery");
6130
6131 // Build an implicit member call if appropriate. Just drop the
6132 // casts and such from the call, we don't really care.
6133 Sema::OwningExprResult NewFn = SemaRef.ExprError();
6134 if ((*R.begin())->isCXXClassMember())
6135 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6136 else if (ExplicitTemplateArgs)
6137 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6138 else
6139 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6140
6141 if (NewFn.isInvalid())
6142 return Destroy(SemaRef, Fn, Args, NumArgs);
6143
6144 Fn->Destroy(SemaRef.Context);
6145
6146 // This shouldn't cause an infinite loop because we're giving it
6147 // an expression with non-empty lookup results, which should never
6148 // end up here.
6149 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
6150 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
6151 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00006152}
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006153
Douglas Gregorf6b89692008-11-26 05:54:23 +00006154/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00006155/// (which eventually refers to the declaration Func) and the call
6156/// arguments Args/NumArgs, attempt to resolve the function call down
6157/// to a specific function. If overload resolution succeeds, returns
6158/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00006159/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00006160/// arguments and Fn, and returns NULL.
John McCall3b4294e2009-12-16 12:17:52 +00006161Sema::OwningExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006162Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00006163 SourceLocation LParenLoc,
6164 Expr **Args, unsigned NumArgs,
6165 SourceLocation *CommaLocs,
6166 SourceLocation RParenLoc) {
6167#ifndef NDEBUG
6168 if (ULE->requiresADL()) {
6169 // To do ADL, we must have found an unqualified name.
6170 assert(!ULE->getQualifier() && "qualified name with ADL");
6171
6172 // We don't perform ADL for implicit declarations of builtins.
6173 // Verify that this was correctly set up.
6174 FunctionDecl *F;
6175 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6176 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6177 F->getBuiltinID() && F->isImplicit())
6178 assert(0 && "performing ADL for builtin");
6179
6180 // We don't perform ADL in C.
6181 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6182 }
6183#endif
6184
John McCall5769d612010-02-08 23:07:23 +00006185 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00006186
John McCall3b4294e2009-12-16 12:17:52 +00006187 // Add the functions denoted by the callee to the set of candidate
6188 // functions, including those from argument-dependent lookup.
6189 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00006190
6191 // If we found nothing, try to recover.
6192 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6193 // bailout out if it fails.
John McCall3b4294e2009-12-16 12:17:52 +00006194 if (CandidateSet.empty())
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006195 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00006196 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00006197
Douglas Gregorf6b89692008-11-26 05:54:23 +00006198 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006199 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00006200 case OR_Success: {
6201 FunctionDecl *FDecl = Best->Function;
John McCall9aa472c2010-03-19 07:35:19 +00006202 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00006203 DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00006204 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall3b4294e2009-12-16 12:17:52 +00006205 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6206 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00006207
6208 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00006209 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00006210 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00006211 << ULE->getName() << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006212 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00006213 break;
6214
6215 case OR_Ambiguous:
6216 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00006217 << ULE->getName() << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006218 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00006219 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006220
6221 case OR_Deleted:
6222 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6223 << Best->Function->isDeleted()
John McCall3b4294e2009-12-16 12:17:52 +00006224 << ULE->getName()
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006225 << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006226 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006227 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00006228 }
6229
6230 // Overload resolution failed. Destroy all of the subexpressions and
6231 // return NULL.
6232 Fn->Destroy(Context);
6233 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
6234 Args[Arg]->Destroy(Context);
John McCall3b4294e2009-12-16 12:17:52 +00006235 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00006236}
6237
John McCall6e266892010-01-26 03:27:55 +00006238static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00006239 return Functions.size() > 1 ||
6240 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6241}
6242
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006243/// \brief Create a unary operation that may resolve to an overloaded
6244/// operator.
6245///
6246/// \param OpLoc The location of the operator itself (e.g., '*').
6247///
6248/// \param OpcIn The UnaryOperator::Opcode that describes this
6249/// operator.
6250///
6251/// \param Functions The set of non-member functions that will be
6252/// considered by overload resolution. The caller needs to build this
6253/// set based on the context using, e.g.,
6254/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6255/// set should not contain any member functions; those will be added
6256/// by CreateOverloadedUnaryOp().
6257///
6258/// \param input The input argument.
John McCall6e266892010-01-26 03:27:55 +00006259Sema::OwningExprResult
6260Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6261 const UnresolvedSetImpl &Fns,
6262 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006263 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
6264 Expr *Input = (Expr *)input.get();
6265
6266 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6267 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6268 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6269
6270 Expr *Args[2] = { Input, 0 };
6271 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00006272
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006273 // For post-increment and post-decrement, add the implicit '0' as
6274 // the second argument, so that we know this is a post-increment or
6275 // post-decrement.
6276 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
6277 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump1eb44332009-09-09 15:08:12 +00006278 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006279 SourceLocation());
6280 NumArgs = 2;
6281 }
6282
6283 if (Input->isTypeDependent()) {
John McCallc373d482010-01-27 01:50:18 +00006284 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00006285 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00006286 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00006287 0, SourceRange(), OpName, OpLoc,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00006288 /*ADL*/ true, IsOverloaded(Fns),
6289 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006290 input.release();
6291 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6292 &Args[0], NumArgs,
6293 Context.DependentTy,
6294 OpLoc));
6295 }
6296
6297 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00006298 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006299
6300 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00006301 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006302
6303 // Add operator candidates that are member functions.
6304 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6305
John McCall6e266892010-01-26 03:27:55 +00006306 // Add candidates from ADL.
6307 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregordc81c882010-02-05 05:15:43 +00006308 Args, NumArgs,
John McCall6e266892010-01-26 03:27:55 +00006309 /*ExplicitTemplateArgs*/ 0,
6310 CandidateSet);
6311
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006312 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00006313 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006314
6315 // Perform overload resolution.
6316 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006317 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006318 case OR_Success: {
6319 // We found a built-in operator or an overloaded operator.
6320 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00006321
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006322 if (FnDecl) {
6323 // We matched an overloaded operator. Build a call to that
6324 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00006325
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006326 // Convert the arguments.
6327 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00006328 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00006329
John McCall6bb80172010-03-30 21:47:33 +00006330 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6331 Best->FoundDecl, Method))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006332 return ExprError();
6333 } else {
6334 // Convert the arguments.
Douglas Gregore1a5c172009-12-23 17:40:29 +00006335 OwningExprResult InputInit
6336 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregorbaecfed2009-12-23 00:02:00 +00006337 FnDecl->getParamDecl(0)),
Douglas Gregore1a5c172009-12-23 17:40:29 +00006338 SourceLocation(),
6339 move(input));
6340 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006341 return ExprError();
Douglas Gregorbaecfed2009-12-23 00:02:00 +00006342
Douglas Gregore1a5c172009-12-23 17:40:29 +00006343 input = move(InputInit);
Douglas Gregorbaecfed2009-12-23 00:02:00 +00006344 Input = (Expr *)input.get();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006345 }
6346
John McCallb697e082010-05-06 18:15:07 +00006347 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6348
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006349 // Determine the result type
Anders Carlsson26a2a072009-10-13 21:19:37 +00006350 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00006351
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006352 // Build the actual expression node.
6353 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6354 SourceLocation());
6355 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00006356
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006357 input.release();
Eli Friedman4c3b8962009-11-18 03:58:17 +00006358 Args[0] = Input;
Anders Carlsson26a2a072009-10-13 21:19:37 +00006359 ExprOwningPtr<CallExpr> TheCall(this,
6360 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman4c3b8962009-11-18 03:58:17 +00006361 Args, NumArgs, ResultTy, OpLoc));
John McCallb697e082010-05-06 18:15:07 +00006362
Anders Carlsson26a2a072009-10-13 21:19:37 +00006363 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6364 FnDecl))
6365 return ExprError();
6366
6367 return MaybeBindToTemporary(TheCall.release());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006368 } else {
6369 // We matched a built-in operator. Convert the arguments, then
6370 // break out so that we will build the appropriate built-in
6371 // operator node.
6372 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00006373 Best->Conversions[0], AA_Passing))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006374 return ExprError();
6375
6376 break;
6377 }
6378 }
6379
6380 case OR_No_Viable_Function:
6381 // No viable function; fall through to handling this as a
6382 // built-in operator, which will produce an error message for us.
6383 break;
6384
6385 case OR_Ambiguous:
6386 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6387 << UnaryOperator::getOpcodeStr(Opc)
6388 << Input->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006389 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00006390 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006391 return ExprError();
6392
6393 case OR_Deleted:
6394 Diag(OpLoc, diag::err_ovl_deleted_oper)
6395 << Best->Function->isDeleted()
6396 << UnaryOperator::getOpcodeStr(Opc)
6397 << Input->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006398 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006399 return ExprError();
6400 }
6401
6402 // Either we found no viable overloaded operator or we matched a
6403 // built-in operator. In either case, fall through to trying to
6404 // build a built-in operation.
6405 input.release();
6406 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
6407}
6408
Douglas Gregor063daf62009-03-13 18:40:31 +00006409/// \brief Create a binary operation that may resolve to an overloaded
6410/// operator.
6411///
6412/// \param OpLoc The location of the operator itself (e.g., '+').
6413///
6414/// \param OpcIn The BinaryOperator::Opcode that describes this
6415/// operator.
6416///
6417/// \param Functions The set of non-member functions that will be
6418/// considered by overload resolution. The caller needs to build this
6419/// set based on the context using, e.g.,
6420/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6421/// set should not contain any member functions; those will be added
6422/// by CreateOverloadedBinOp().
6423///
6424/// \param LHS Left-hand argument.
6425/// \param RHS Right-hand argument.
Mike Stump1eb44332009-09-09 15:08:12 +00006426Sema::OwningExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00006427Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006428 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00006429 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00006430 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00006431 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006432 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00006433
6434 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6435 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6436 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6437
6438 // If either side is type-dependent, create an appropriate dependent
6439 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006440 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00006441 if (Fns.empty()) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006442 // If there are no functions to store, just build a dependent
6443 // BinaryOperator or CompoundAssignment.
6444 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
6445 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6446 Context.DependentTy, OpLoc));
6447
6448 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6449 Context.DependentTy,
6450 Context.DependentTy,
6451 Context.DependentTy,
6452 OpLoc));
6453 }
John McCall6e266892010-01-26 03:27:55 +00006454
6455 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00006456 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00006457 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00006458 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00006459 0, SourceRange(), OpName, OpLoc,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00006460 /*ADL*/ true, IsOverloaded(Fns),
6461 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00006462 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00006463 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00006464 Context.DependentTy,
6465 OpLoc));
6466 }
6467
6468 // If this is the .* operator, which is not overloadable, just
6469 // create a built-in binary operator.
6470 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006471 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00006472
Sebastian Redl275c2b42009-11-18 23:10:33 +00006473 // If this is the assignment operator, we only perform overload resolution
6474 // if the left-hand side is a class or enumeration type. This is actually
6475 // a hack. The standard requires that we do overload resolution between the
6476 // various built-in candidates, but as DR507 points out, this can lead to
6477 // problems. So we do it this way, which pretty much follows what GCC does.
6478 // Note that we go the traditional code path for compound assignment forms.
6479 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006480 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00006481
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006482 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00006483 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00006484
6485 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00006486 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00006487
6488 // Add operator candidates that are member functions.
6489 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6490
John McCall6e266892010-01-26 03:27:55 +00006491 // Add candidates from ADL.
6492 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6493 Args, 2,
6494 /*ExplicitTemplateArgs*/ 0,
6495 CandidateSet);
6496
Douglas Gregor063daf62009-03-13 18:40:31 +00006497 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00006498 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00006499
6500 // Perform overload resolution.
6501 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006502 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00006503 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00006504 // We found a built-in operator or an overloaded operator.
6505 FunctionDecl *FnDecl = Best->Function;
6506
6507 if (FnDecl) {
6508 // We matched an overloaded operator. Build a call to that
6509 // operator.
6510
6511 // Convert the arguments.
6512 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00006513 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +00006514 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00006515
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006516 OwningExprResult Arg1
6517 = PerformCopyInitialization(
6518 InitializedEntity::InitializeParameter(
6519 FnDecl->getParamDecl(0)),
6520 SourceLocation(),
6521 Owned(Args[1]));
6522 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00006523 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006524
Douglas Gregor5fccd362010-03-03 23:55:11 +00006525 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00006526 Best->FoundDecl, Method))
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006527 return ExprError();
6528
6529 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00006530 } else {
6531 // Convert the arguments.
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006532 OwningExprResult Arg0
6533 = PerformCopyInitialization(
6534 InitializedEntity::InitializeParameter(
6535 FnDecl->getParamDecl(0)),
6536 SourceLocation(),
6537 Owned(Args[0]));
6538 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00006539 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006540
6541 OwningExprResult Arg1
6542 = PerformCopyInitialization(
6543 InitializedEntity::InitializeParameter(
6544 FnDecl->getParamDecl(1)),
6545 SourceLocation(),
6546 Owned(Args[1]));
6547 if (Arg1.isInvalid())
6548 return ExprError();
6549 Args[0] = LHS = Arg0.takeAs<Expr>();
6550 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00006551 }
6552
John McCallb697e082010-05-06 18:15:07 +00006553 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6554
Douglas Gregor063daf62009-03-13 18:40:31 +00006555 // Determine the result type
6556 QualType ResultTy
John McCall183700f2009-09-21 23:43:11 +00006557 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor063daf62009-03-13 18:40:31 +00006558 ResultTy = ResultTy.getNonReferenceType();
6559
6560 // Build the actual expression node.
6561 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00006562 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00006563 UsualUnaryConversions(FnExpr);
6564
Anders Carlsson15ea3782009-10-13 22:43:21 +00006565 ExprOwningPtr<CXXOperatorCallExpr>
6566 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6567 Args, 2, ResultTy,
6568 OpLoc));
6569
6570 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6571 FnDecl))
6572 return ExprError();
6573
6574 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor063daf62009-03-13 18:40:31 +00006575 } else {
6576 // We matched a built-in operator. Convert the arguments, then
6577 // break out so that we will build the appropriate built-in
6578 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006579 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00006580 Best->Conversions[0], AA_Passing) ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006581 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00006582 Best->Conversions[1], AA_Passing))
Douglas Gregor063daf62009-03-13 18:40:31 +00006583 return ExprError();
6584
6585 break;
6586 }
6587 }
6588
Douglas Gregor33074752009-09-30 21:46:01 +00006589 case OR_No_Viable_Function: {
6590 // C++ [over.match.oper]p9:
6591 // If the operator is the operator , [...] and there are no
6592 // viable functions, then the operator is assumed to be the
6593 // built-in operator and interpreted according to clause 5.
6594 if (Opc == BinaryOperator::Comma)
6595 break;
6596
Sebastian Redl8593c782009-05-21 11:50:50 +00006597 // For class as left operand for assignment or compound assigment operator
6598 // do not fall through to handling in built-in, but report that no overloaded
6599 // assignment operator found
Douglas Gregor33074752009-09-30 21:46:01 +00006600 OwningExprResult Result = ExprError();
6601 if (Args[0]->getType()->isRecordType() &&
6602 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00006603 Diag(OpLoc, diag::err_ovl_no_viable_oper)
6604 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006605 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00006606 } else {
6607 // No viable function; try to create a built-in operation, which will
6608 // produce an error. Then, show the non-viable candidates.
6609 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00006610 }
Douglas Gregor33074752009-09-30 21:46:01 +00006611 assert(Result.isInvalid() &&
6612 "C++ binary operator overloading is missing candidates!");
6613 if (Result.isInvalid())
John McCallcbce6062010-01-12 07:18:19 +00006614 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00006615 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00006616 return move(Result);
6617 }
Douglas Gregor063daf62009-03-13 18:40:31 +00006618
6619 case OR_Ambiguous:
6620 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6621 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006622 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006623 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00006624 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00006625 return ExprError();
6626
6627 case OR_Deleted:
6628 Diag(OpLoc, diag::err_ovl_deleted_oper)
6629 << Best->Function->isDeleted()
6630 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006631 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006632 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor063daf62009-03-13 18:40:31 +00006633 return ExprError();
John McCall1d318332010-01-12 00:44:57 +00006634 }
Douglas Gregor063daf62009-03-13 18:40:31 +00006635
Douglas Gregor33074752009-09-30 21:46:01 +00006636 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006637 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00006638}
6639
Sebastian Redlf322ed62009-10-29 20:17:01 +00006640Action::OwningExprResult
6641Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
6642 SourceLocation RLoc,
6643 ExprArg Base, ExprArg Idx) {
6644 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
6645 static_cast<Expr*>(Idx.get()) };
6646 DeclarationName OpName =
6647 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
6648
6649 // If either side is type-dependent, create an appropriate dependent
6650 // expression.
6651 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
6652
John McCallc373d482010-01-27 01:50:18 +00006653 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00006654 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00006655 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00006656 0, SourceRange(), OpName, LLoc,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00006657 /*ADL*/ true, /*Overloaded*/ false,
6658 UnresolvedSetIterator(),
6659 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +00006660 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00006661
6662 Base.release();
6663 Idx.release();
6664 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
6665 Args, 2,
6666 Context.DependentTy,
6667 RLoc));
6668 }
6669
6670 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00006671 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00006672
6673 // Subscript can only be overloaded as a member function.
6674
6675 // Add operator candidates that are member functions.
6676 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6677
6678 // Add builtin operator candidates.
6679 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6680
6681 // Perform overload resolution.
6682 OverloadCandidateSet::iterator Best;
6683 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
6684 case OR_Success: {
6685 // We found a built-in operator or an overloaded operator.
6686 FunctionDecl *FnDecl = Best->Function;
6687
6688 if (FnDecl) {
6689 // We matched an overloaded operator. Build a call to that
6690 // operator.
6691
John McCall9aa472c2010-03-19 07:35:19 +00006692 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00006693 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +00006694
Sebastian Redlf322ed62009-10-29 20:17:01 +00006695 // Convert the arguments.
6696 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregor5fccd362010-03-03 23:55:11 +00006697 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00006698 Best->FoundDecl, Method))
Sebastian Redlf322ed62009-10-29 20:17:01 +00006699 return ExprError();
6700
Anders Carlsson38f88ab2010-01-29 18:37:50 +00006701 // Convert the arguments.
6702 OwningExprResult InputInit
6703 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6704 FnDecl->getParamDecl(0)),
6705 SourceLocation(),
6706 Owned(Args[1]));
6707 if (InputInit.isInvalid())
6708 return ExprError();
6709
6710 Args[1] = InputInit.takeAs<Expr>();
6711
Sebastian Redlf322ed62009-10-29 20:17:01 +00006712 // Determine the result type
6713 QualType ResultTy
6714 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
6715 ResultTy = ResultTy.getNonReferenceType();
6716
6717 // Build the actual expression node.
6718 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6719 LLoc);
6720 UsualUnaryConversions(FnExpr);
6721
6722 Base.release();
6723 Idx.release();
6724 ExprOwningPtr<CXXOperatorCallExpr>
6725 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
6726 FnExpr, Args, 2,
6727 ResultTy, RLoc));
6728
6729 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
6730 FnDecl))
6731 return ExprError();
6732
6733 return MaybeBindToTemporary(TheCall.release());
6734 } else {
6735 // We matched a built-in operator. Convert the arguments, then
6736 // break out so that we will build the appropriate built-in
6737 // operator node.
6738 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00006739 Best->Conversions[0], AA_Passing) ||
Sebastian Redlf322ed62009-10-29 20:17:01 +00006740 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00006741 Best->Conversions[1], AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00006742 return ExprError();
6743
6744 break;
6745 }
6746 }
6747
6748 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00006749 if (CandidateSet.empty())
6750 Diag(LLoc, diag::err_ovl_no_oper)
6751 << Args[0]->getType() << /*subscript*/ 0
6752 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6753 else
6754 Diag(LLoc, diag::err_ovl_no_viable_subscript)
6755 << Args[0]->getType()
6756 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006757 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall1eb3e102010-01-07 02:04:15 +00006758 "[]", LLoc);
6759 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00006760 }
6761
6762 case OR_Ambiguous:
6763 Diag(LLoc, diag::err_ovl_ambiguous_oper)
6764 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006765 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redlf322ed62009-10-29 20:17:01 +00006766 "[]", LLoc);
6767 return ExprError();
6768
6769 case OR_Deleted:
6770 Diag(LLoc, diag::err_ovl_deleted_oper)
6771 << Best->Function->isDeleted() << "[]"
6772 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006773 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall81201622010-01-08 04:41:39 +00006774 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00006775 return ExprError();
6776 }
6777
6778 // We matched a built-in operator; build it.
6779 Base.release();
6780 Idx.release();
6781 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
6782 Owned(Args[1]), RLoc);
6783}
6784
Douglas Gregor88a35142008-12-22 05:46:06 +00006785/// BuildCallToMemberFunction - Build a call to a member
6786/// function. MemExpr is the expression that refers to the member
6787/// function (and includes the object parameter), Args/NumArgs are the
6788/// arguments to the function call (not including the object
6789/// parameter). The caller needs to validate that the member
6790/// expression refers to a member function or an overloaded member
6791/// function.
John McCallaa81e162009-12-01 22:10:20 +00006792Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00006793Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
6794 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor88a35142008-12-22 05:46:06 +00006795 unsigned NumArgs, SourceLocation *CommaLocs,
6796 SourceLocation RParenLoc) {
6797 // Dig out the member expression. This holds both the object
6798 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00006799 Expr *NakedMemExpr = MemExprE->IgnoreParens();
6800
John McCall129e2df2009-11-30 22:42:35 +00006801 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00006802 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +00006803 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +00006804 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +00006805 if (isa<MemberExpr>(NakedMemExpr)) {
6806 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00006807 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +00006808 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +00006809 Qualifier = MemExpr->getQualifier();
John McCall129e2df2009-11-30 22:42:35 +00006810 } else {
6811 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +00006812 Qualifier = UnresExpr->getQualifier();
6813
John McCall701c89e2009-12-03 04:06:58 +00006814 QualType ObjectType = UnresExpr->getBaseType();
John McCall129e2df2009-11-30 22:42:35 +00006815
Douglas Gregor88a35142008-12-22 05:46:06 +00006816 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +00006817 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00006818
John McCallaa81e162009-12-01 22:10:20 +00006819 // FIXME: avoid copy.
6820 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6821 if (UnresExpr->hasExplicitTemplateArgs()) {
6822 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6823 TemplateArgs = &TemplateArgsBuffer;
6824 }
6825
John McCall129e2df2009-11-30 22:42:35 +00006826 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6827 E = UnresExpr->decls_end(); I != E; ++I) {
6828
John McCall701c89e2009-12-03 04:06:58 +00006829 NamedDecl *Func = *I;
6830 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6831 if (isa<UsingShadowDecl>(Func))
6832 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6833
John McCall129e2df2009-11-30 22:42:35 +00006834 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006835 // If explicit template arguments were provided, we can't call a
6836 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00006837 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006838 continue;
6839
John McCall9aa472c2010-03-19 07:35:19 +00006840 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCall86820f52010-01-26 01:37:31 +00006841 Args, NumArgs,
John McCall701c89e2009-12-03 04:06:58 +00006842 CandidateSet, /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00006843 } else {
John McCall129e2df2009-11-30 22:42:35 +00006844 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +00006845 I.getPair(), ActingDC, TemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00006846 ObjectType, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00006847 CandidateSet,
6848 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00006849 }
Douglas Gregordec06662009-08-21 18:42:58 +00006850 }
Mike Stump1eb44332009-09-09 15:08:12 +00006851
John McCall129e2df2009-11-30 22:42:35 +00006852 DeclarationName DeclName = UnresExpr->getMemberName();
6853
Douglas Gregor88a35142008-12-22 05:46:06 +00006854 OverloadCandidateSet::iterator Best;
John McCall129e2df2009-11-30 22:42:35 +00006855 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00006856 case OR_Success:
6857 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00006858 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +00006859 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00006860 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +00006861 break;
6862
6863 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00006864 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00006865 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00006866 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006867 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00006868 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00006869 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006870
6871 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00006872 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00006873 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006874 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00006875 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00006876 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006877
6878 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00006879 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006880 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00006881 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006882 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006883 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00006884 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006885 }
6886
John McCall6bb80172010-03-30 21:47:33 +00006887 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +00006888
John McCallaa81e162009-12-01 22:10:20 +00006889 // If overload resolution picked a static member, build a
6890 // non-member call based on that function.
6891 if (Method->isStatic()) {
6892 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6893 Args, NumArgs, RParenLoc);
6894 }
6895
John McCall129e2df2009-11-30 22:42:35 +00006896 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00006897 }
6898
6899 assert(Method && "Member call to something that isn't a method?");
Mike Stump1eb44332009-09-09 15:08:12 +00006900 ExprOwningPtr<CXXMemberCallExpr>
John McCallaa81e162009-12-01 22:10:20 +00006901 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump1eb44332009-09-09 15:08:12 +00006902 NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00006903 Method->getResultType().getNonReferenceType(),
6904 RParenLoc));
6905
Anders Carlssoneed3e692009-10-10 00:06:20 +00006906 // Check for a valid return type.
6907 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6908 TheCall.get(), Method))
John McCallaa81e162009-12-01 22:10:20 +00006909 return ExprError();
Anders Carlssoneed3e692009-10-10 00:06:20 +00006910
Douglas Gregor88a35142008-12-22 05:46:06 +00006911 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +00006912 // We only need to do this if there was actually an overload; otherwise
6913 // it was done at lookup.
John McCallaa81e162009-12-01 22:10:20 +00006914 Expr *ObjectArg = MemExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00006915 if (!Method->isStatic() &&
John McCall6bb80172010-03-30 21:47:33 +00006916 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
6917 FoundDecl, Method))
John McCallaa81e162009-12-01 22:10:20 +00006918 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006919 MemExpr->setBase(ObjectArg);
6920
6921 // Convert the rest of the arguments
Douglas Gregor5f970ee2010-05-04 18:18:31 +00006922 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006923 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00006924 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00006925 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00006926
Anders Carlssond406bf02009-08-16 01:56:34 +00006927 if (CheckFunctionCall(Method, TheCall.get()))
John McCallaa81e162009-12-01 22:10:20 +00006928 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00006929
John McCallaa81e162009-12-01 22:10:20 +00006930 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor88a35142008-12-22 05:46:06 +00006931}
6932
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006933/// BuildCallToObjectOfClassType - Build a call to an object of class
6934/// type (C++ [over.call.object]), which can end up invoking an
6935/// overloaded function call operator (@c operator()) or performing a
6936/// user-defined conversion on the object argument.
Mike Stump1eb44332009-09-09 15:08:12 +00006937Sema::ExprResult
6938Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00006939 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006940 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00006941 SourceLocation *CommaLocs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006942 SourceLocation RParenLoc) {
6943 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00006944 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00006945
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006946 // C++ [over.call.object]p1:
6947 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00006948 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00006949 // candidate functions includes at least the function call
6950 // operators of T. The function call operators of T are obtained by
6951 // ordinary lookup of the name operator() in the context of
6952 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +00006953 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00006954 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00006955
6956 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006957 PDiag(diag::err_incomplete_object_call)
Douglas Gregor593564b2009-11-15 07:48:03 +00006958 << Object->getSourceRange()))
6959 return true;
6960
John McCalla24dc2e2009-11-17 02:14:36 +00006961 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
6962 LookupQualifiedName(R, Record->getDecl());
6963 R.suppressDiagnostics();
6964
Douglas Gregor593564b2009-11-15 07:48:03 +00006965 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00006966 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00006967 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCall86820f52010-01-26 01:37:31 +00006968 Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00006969 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00006970 }
Douglas Gregor4a27d702009-10-21 06:18:39 +00006971
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006972 // C++ [over.call.object]p2:
6973 // In addition, for each conversion function declared in T of the
6974 // form
6975 //
6976 // operator conversion-type-id () cv-qualifier;
6977 //
6978 // where cv-qualifier is the same cv-qualification as, or a
6979 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00006980 // denotes the type "pointer to function of (P1,...,Pn) returning
6981 // R", or the type "reference to pointer to function of
6982 // (P1,...,Pn) returning R", or the type "reference to function
6983 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006984 // is also considered as a candidate function. Similarly,
6985 // surrogate call functions are added to the set of candidate
6986 // functions for each conversion function declared in an
6987 // accessible base class provided the function is not hidden
6988 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +00006989 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00006990 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00006991 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00006992 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00006993 NamedDecl *D = *I;
6994 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6995 if (isa<UsingShadowDecl>(D))
6996 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6997
Douglas Gregor4a27d702009-10-21 06:18:39 +00006998 // Skip over templated conversion functions; they aren't
6999 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00007000 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00007001 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007002
John McCall701c89e2009-12-03 04:06:58 +00007003 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCallba135432009-11-21 08:51:07 +00007004
Douglas Gregor4a27d702009-10-21 06:18:39 +00007005 // Strip the reference type (if any) and then the pointer type (if
7006 // any) to get down to what might be a function type.
7007 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7008 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7009 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007010
Douglas Gregor4a27d702009-10-21 06:18:39 +00007011 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall9aa472c2010-03-19 07:35:19 +00007012 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall701c89e2009-12-03 04:06:58 +00007013 Object->getType(), Args, NumArgs,
7014 CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007015 }
Mike Stump1eb44332009-09-09 15:08:12 +00007016
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007017 // Perform overload resolution.
7018 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00007019 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007020 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007021 // Overload resolution succeeded; we'll build the appropriate call
7022 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007023 break;
7024
7025 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00007026 if (CandidateSet.empty())
7027 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7028 << Object->getType() << /*call*/ 1
7029 << Object->getSourceRange();
7030 else
7031 Diag(Object->getSourceRange().getBegin(),
7032 diag::err_ovl_no_viable_object_call)
7033 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007034 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007035 break;
7036
7037 case OR_Ambiguous:
7038 Diag(Object->getSourceRange().getBegin(),
7039 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00007040 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007041 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007042 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007043
7044 case OR_Deleted:
7045 Diag(Object->getSourceRange().getBegin(),
7046 diag::err_ovl_deleted_object_call)
7047 << Best->Function->isDeleted()
7048 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007049 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007050 break;
Mike Stump1eb44332009-09-09 15:08:12 +00007051 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007052
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007053 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007054 // We had an error; delete all of the subexpressions and return
7055 // the error.
Ted Kremenek8189cde2009-02-07 01:47:29 +00007056 Object->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007057 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek8189cde2009-02-07 01:47:29 +00007058 Args[ArgIdx]->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007059 return true;
7060 }
7061
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007062 if (Best->Function == 0) {
7063 // Since there is no function declaration, this is one of the
7064 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00007065 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007066 = cast<CXXConversionDecl>(
7067 Best->Conversions[0].UserDefined.ConversionFunction);
7068
John McCall9aa472c2010-03-19 07:35:19 +00007069 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007070 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00007071
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007072 // We selected one of the surrogate functions that converts the
7073 // object parameter to a function pointer. Perform the conversion
7074 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00007075
7076 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00007077 // and then call it.
John McCall6bb80172010-03-30 21:47:33 +00007078 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7079 Conv);
Fariborz Jahanianb7400232009-09-28 23:23:40 +00007080
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00007081 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00007082 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
Douglas Gregoraa0be172010-04-13 15:50:39 +00007083 CommaLocs, RParenLoc).result();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007084 }
7085
John McCall9aa472c2010-03-19 07:35:19 +00007086 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007087 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00007088
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007089 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7090 // that calls this method, using Object for the implicit object
7091 // parameter and passing along the remaining arguments.
7092 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall183700f2009-09-21 23:43:11 +00007093 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007094
7095 unsigned NumArgsInProto = Proto->getNumArgs();
7096 unsigned NumArgsToCheck = NumArgs;
7097
7098 // Build the full argument list for the method call (the
7099 // implicit object parameter is placed at the beginning of the
7100 // list).
7101 Expr **MethodArgs;
7102 if (NumArgs < NumArgsInProto) {
7103 NumArgsToCheck = NumArgsInProto;
7104 MethodArgs = new Expr*[NumArgsInProto + 1];
7105 } else {
7106 MethodArgs = new Expr*[NumArgs + 1];
7107 }
7108 MethodArgs[0] = Object;
7109 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7110 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00007111
7112 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00007113 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007114 UsualUnaryConversions(NewFn);
7115
7116 // Once we've built TheCall, all of the expressions are properly
7117 // owned.
7118 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump1eb44332009-09-09 15:08:12 +00007119 ExprOwningPtr<CXXOperatorCallExpr>
7120 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor063daf62009-03-13 18:40:31 +00007121 MethodArgs, NumArgs + 1,
Ted Kremenek8189cde2009-02-07 01:47:29 +00007122 ResultTy, RParenLoc));
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007123 delete [] MethodArgs;
7124
Anders Carlsson07d68f12009-10-13 21:49:31 +00007125 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
7126 Method))
7127 return true;
7128
Douglas Gregor518fda12009-01-13 05:10:00 +00007129 // We may have default arguments. If so, we need to allocate more
7130 // slots in the call for them.
7131 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00007132 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00007133 else if (NumArgs > NumArgsInProto)
7134 NumArgsToCheck = NumArgsInProto;
7135
Chris Lattner312531a2009-04-12 08:11:20 +00007136 bool IsError = false;
7137
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007138 // Initialize the implicit object parameter.
Douglas Gregor5fccd362010-03-03 23:55:11 +00007139 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007140 Best->FoundDecl, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007141 TheCall->setArg(0, Object);
7142
Chris Lattner312531a2009-04-12 08:11:20 +00007143
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007144 // Check the argument types.
7145 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007146 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00007147 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007148 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00007149
Douglas Gregor518fda12009-01-13 05:10:00 +00007150 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +00007151
7152 OwningExprResult InputInit
7153 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7154 Method->getParamDecl(i)),
7155 SourceLocation(), Owned(Arg));
7156
7157 IsError |= InputInit.isInvalid();
7158 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00007159 } else {
Douglas Gregord47c47d2009-11-09 19:27:57 +00007160 OwningExprResult DefArg
7161 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7162 if (DefArg.isInvalid()) {
7163 IsError = true;
7164 break;
7165 }
7166
7167 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00007168 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007169
7170 TheCall->setArg(i + 1, Arg);
7171 }
7172
7173 // If this is a variadic call, handle args passed through "...".
7174 if (Proto->isVariadic()) {
7175 // Promote the arguments (C99 6.5.2.2p7).
7176 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7177 Expr *Arg = Args[i];
Chris Lattner40378332010-05-16 04:01:30 +00007178 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007179 TheCall->setArg(i + 1, Arg);
7180 }
7181 }
7182
Chris Lattner312531a2009-04-12 08:11:20 +00007183 if (IsError) return true;
7184
Anders Carlssond406bf02009-08-16 01:56:34 +00007185 if (CheckFunctionCall(Method, TheCall.get()))
7186 return true;
7187
Douglas Gregoraa0be172010-04-13 15:50:39 +00007188 return MaybeBindToTemporary(TheCall.release()).result();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007189}
7190
Douglas Gregor8ba10742008-11-20 16:27:02 +00007191/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00007192/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00007193/// @c Member is the name of the member we're trying to find.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007194Sema::OwningExprResult
7195Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
7196 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor8ba10742008-11-20 16:27:02 +00007197 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00007198
John McCall5769d612010-02-08 23:07:23 +00007199 SourceLocation Loc = Base->getExprLoc();
7200
Douglas Gregor8ba10742008-11-20 16:27:02 +00007201 // C++ [over.ref]p1:
7202 //
7203 // [...] An expression x->m is interpreted as (x.operator->())->m
7204 // for a class object x of type T if T::operator->() exists and if
7205 // the operator is selected as the best match function by the
7206 // overload resolution mechanism (13.3).
Douglas Gregor8ba10742008-11-20 16:27:02 +00007207 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +00007208 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +00007209 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007210
John McCall5769d612010-02-08 23:07:23 +00007211 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +00007212 PDiag(diag::err_typecheck_incomplete_tag)
7213 << Base->getSourceRange()))
7214 return ExprError();
7215
John McCalla24dc2e2009-11-17 02:14:36 +00007216 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7217 LookupQualifiedName(R, BaseRecord->getDecl());
7218 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00007219
7220 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00007221 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00007222 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00007223 /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00007224 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00007225
7226 // Perform overload resolution.
7227 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00007228 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00007229 case OR_Success:
7230 // Overload resolution succeeded; we'll build the call below.
7231 break;
7232
7233 case OR_No_Viable_Function:
7234 if (CandidateSet.empty())
7235 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007236 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007237 else
7238 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007239 << "operator->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007240 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007241 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007242
7243 case OR_Ambiguous:
7244 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlssone30572a2009-09-10 23:18:36 +00007245 << "->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007246 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007247 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007248
7249 case OR_Deleted:
7250 Diag(OpLoc, diag::err_ovl_deleted_oper)
7251 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00007252 << "->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007253 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007254 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007255 }
7256
John McCall9aa472c2010-03-19 07:35:19 +00007257 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007258 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +00007259
Douglas Gregor8ba10742008-11-20 16:27:02 +00007260 // Convert the object parameter.
7261 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00007262 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7263 Best->FoundDecl, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007264 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00007265
7266 // No concerns about early exits now.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007267 BaseIn.release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007268
7269 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00007270 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7271 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00007272 UsualUnaryConversions(FnExpr);
Anders Carlsson15ea3782009-10-13 22:43:21 +00007273
7274 QualType ResultTy = Method->getResultType().getNonReferenceType();
7275 ExprOwningPtr<CXXOperatorCallExpr>
7276 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7277 &Base, 1, ResultTy, OpLoc));
7278
7279 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
7280 Method))
7281 return ExprError();
7282 return move(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00007283}
7284
Douglas Gregor904eed32008-11-10 20:40:00 +00007285/// FixOverloadedFunctionReference - E is an expression that refers to
7286/// a C++ overloaded function (possibly with some parentheses and
7287/// perhaps a '&' around it). We have resolved the overloaded function
7288/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00007289/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +00007290Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +00007291 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00007292 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00007293 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7294 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00007295 if (SubExpr == PE->getSubExpr())
7296 return PE->Retain();
7297
7298 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7299 }
7300
7301 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00007302 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7303 Found, Fn);
Douglas Gregor097bfb12009-10-23 22:18:25 +00007304 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00007305 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00007306 "Implicit cast type cannot be determined from overload");
Douglas Gregor699ee522009-11-20 19:42:02 +00007307 if (SubExpr == ICE->getSubExpr())
7308 return ICE->Retain();
7309
7310 return new (Context) ImplicitCastExpr(ICE->getType(),
7311 ICE->getCastKind(),
Anders Carlssonf1b48b72010-04-24 16:57:13 +00007312 SubExpr, CXXBaseSpecifierArray(),
Douglas Gregor699ee522009-11-20 19:42:02 +00007313 ICE->isLvalueCast());
7314 }
7315
7316 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007317 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00007318 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00007319 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7320 if (Method->isStatic()) {
7321 // Do nothing: static member functions aren't any different
7322 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00007323 } else {
John McCallf7a1a742009-11-24 19:00:30 +00007324 // Fix the sub expression, which really has to be an
7325 // UnresolvedLookupExpr holding an overloaded member function
7326 // or template.
John McCall6bb80172010-03-30 21:47:33 +00007327 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7328 Found, Fn);
John McCallba135432009-11-21 08:51:07 +00007329 if (SubExpr == UnOp->getSubExpr())
7330 return UnOp->Retain();
Douglas Gregor699ee522009-11-20 19:42:02 +00007331
John McCallba135432009-11-21 08:51:07 +00007332 assert(isa<DeclRefExpr>(SubExpr)
7333 && "fixed to something other than a decl ref");
7334 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7335 && "fixed to a member ref with no nested name qualifier");
7336
7337 // We have taken the address of a pointer to member
7338 // function. Perform the computation here so that we get the
7339 // appropriate pointer to member type.
7340 QualType ClassType
7341 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7342 QualType MemPtrType
7343 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7344
7345 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7346 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00007347 }
7348 }
John McCall6bb80172010-03-30 21:47:33 +00007349 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7350 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00007351 if (SubExpr == UnOp->getSubExpr())
7352 return UnOp->Retain();
Anders Carlsson96ad5332009-10-21 17:16:23 +00007353
Douglas Gregor699ee522009-11-20 19:42:02 +00007354 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7355 Context.getPointerType(SubExpr->getType()),
7356 UnOp->getOperatorLoc());
Douglas Gregor699ee522009-11-20 19:42:02 +00007357 }
John McCallba135432009-11-21 08:51:07 +00007358
7359 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00007360 // FIXME: avoid copy.
7361 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00007362 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00007363 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7364 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00007365 }
7366
John McCallba135432009-11-21 08:51:07 +00007367 return DeclRefExpr::Create(Context,
7368 ULE->getQualifier(),
7369 ULE->getQualifierRange(),
7370 Fn,
7371 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00007372 Fn->getType(),
7373 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00007374 }
7375
John McCall129e2df2009-11-30 22:42:35 +00007376 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00007377 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00007378 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7379 if (MemExpr->hasExplicitTemplateArgs()) {
7380 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7381 TemplateArgs = &TemplateArgsBuffer;
7382 }
John McCalld5532b62009-11-23 01:53:49 +00007383
John McCallaa81e162009-12-01 22:10:20 +00007384 Expr *Base;
7385
7386 // If we're filling in
7387 if (MemExpr->isImplicitAccess()) {
7388 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7389 return DeclRefExpr::Create(Context,
7390 MemExpr->getQualifier(),
7391 MemExpr->getQualifierRange(),
7392 Fn,
7393 MemExpr->getMemberLoc(),
7394 Fn->getType(),
7395 TemplateArgs);
Douglas Gregor828a1972010-01-07 23:12:05 +00007396 } else {
7397 SourceLocation Loc = MemExpr->getMemberLoc();
7398 if (MemExpr->getQualifier())
7399 Loc = MemExpr->getQualifierRange().getBegin();
7400 Base = new (Context) CXXThisExpr(Loc,
7401 MemExpr->getBaseType(),
7402 /*isImplicit=*/true);
7403 }
John McCallaa81e162009-12-01 22:10:20 +00007404 } else
7405 Base = MemExpr->getBase()->Retain();
7406
7407 return MemberExpr::Create(Context, Base,
Douglas Gregor699ee522009-11-20 19:42:02 +00007408 MemExpr->isArrow(),
7409 MemExpr->getQualifier(),
7410 MemExpr->getQualifierRange(),
7411 Fn,
John McCall6bb80172010-03-30 21:47:33 +00007412 Found,
John McCalld5532b62009-11-23 01:53:49 +00007413 MemExpr->getMemberLoc(),
John McCallaa81e162009-12-01 22:10:20 +00007414 TemplateArgs,
Douglas Gregor699ee522009-11-20 19:42:02 +00007415 Fn->getType());
7416 }
7417
Douglas Gregor699ee522009-11-20 19:42:02 +00007418 assert(false && "Invalid reference to overloaded function");
7419 return E->Retain();
Douglas Gregor904eed32008-11-10 20:40:00 +00007420}
7421
Douglas Gregor20093b42009-12-09 23:02:17 +00007422Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCall161755a2010-04-06 21:38:20 +00007423 DeclAccessPair Found,
Douglas Gregor20093b42009-12-09 23:02:17 +00007424 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +00007425 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +00007426}
7427
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007428} // end namespace clang