blob: 9f02dae9f8dd35a8425f1ebac76ecb1a13039cd8 [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 McCallddb0ce72010-06-11 10:04:22 +0000158 (getFromType()->isPointerType() ||
159 getFromType()->isObjCObjectPointerType() ||
160 getFromType()->isBlockPointerType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000161 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
162 return true;
163
164 return false;
165}
166
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000167/// isPointerConversionToVoidPointer - Determines whether this
168/// conversion is a conversion of a pointer to a void pointer. This is
169/// used as part of the ranking of standard conversion sequences (C++
170/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000171bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000172StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000173isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000174 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000175 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000176
177 // Note that FromType has not necessarily been transformed by the
178 // array-to-pointer implicit conversion, so check for its presence
179 // and redo the conversion to get a pointer.
180 if (First == ICK_Array_To_Pointer)
181 FromType = Context.getArrayDecayedType(FromType);
182
Douglas Gregor01919692009-12-13 21:37:05 +0000183 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000184 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000185 return ToPtrType->getPointeeType()->isVoidType();
186
187 return false;
188}
189
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000190/// DebugPrint - Print this standard conversion sequence to standard
191/// error. Useful for debugging overloading issues.
192void StandardConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000193 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000194 bool PrintedSomething = false;
195 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000196 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000197 PrintedSomething = true;
198 }
199
200 if (Second != ICK_Identity) {
201 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000202 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000203 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000204 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000205
206 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000207 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000208 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000209 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000210 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000211 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000212 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000213 PrintedSomething = true;
214 }
215
216 if (Third != ICK_Identity) {
217 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000218 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000219 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000220 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000221 PrintedSomething = true;
222 }
223
224 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000225 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000226 }
227}
228
229/// DebugPrint - Print this user-defined conversion sequence to standard
230/// error. Useful for debugging overloading issues.
231void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000232 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000233 if (Before.First || Before.Second || Before.Third) {
234 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000235 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000236 }
Benjamin Kramer900fc632010-04-17 09:33:03 +0000237 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000238 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000239 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000240 After.DebugPrint();
241 }
242}
243
244/// DebugPrint - Print this implicit conversion sequence to standard
245/// error. Useful for debugging overloading issues.
246void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000247 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000248 switch (ConversionKind) {
249 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000250 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000251 Standard.DebugPrint();
252 break;
253 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000254 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000255 UserDefined.DebugPrint();
256 break;
257 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000258 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000259 break;
John McCall1d318332010-01-12 00:44:57 +0000260 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000261 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000262 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000263 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000264 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000265 break;
266 }
267
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000268 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000269}
270
John McCall1d318332010-01-12 00:44:57 +0000271void AmbiguousConversionSequence::construct() {
272 new (&conversions()) ConversionSet();
273}
274
275void AmbiguousConversionSequence::destruct() {
276 conversions().~ConversionSet();
277}
278
279void
280AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
281 FromTypePtr = O.FromTypePtr;
282 ToTypePtr = O.ToTypePtr;
283 new (&conversions()) ConversionSet(O.conversions());
284}
285
Douglas Gregora9333192010-05-08 17:41:32 +0000286namespace {
287 // Structure used by OverloadCandidate::DeductionFailureInfo to store
288 // template parameter and template argument information.
289 struct DFIParamWithArguments {
290 TemplateParameter Param;
291 TemplateArgument FirstArg;
292 TemplateArgument SecondArg;
293 };
294}
295
296/// \brief Convert from Sema's representation of template deduction information
297/// to the form used in overload-candidate information.
298OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000299static MakeDeductionFailureInfo(ASTContext &Context,
300 Sema::TemplateDeductionResult TDK,
Douglas Gregorec20f462010-05-08 20:07:26 +0000301 Sema::TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000302 OverloadCandidate::DeductionFailureInfo Result;
303 Result.Result = static_cast<unsigned>(TDK);
304 Result.Data = 0;
305 switch (TDK) {
306 case Sema::TDK_Success:
307 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000308 case Sema::TDK_TooManyArguments:
309 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000310 break;
311
312 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000313 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000314 Result.Data = Info.Param.getOpaqueValue();
315 break;
316
Douglas Gregora9333192010-05-08 17:41:32 +0000317 case Sema::TDK_Inconsistent:
318 case Sema::TDK_InconsistentQuals: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000319 // FIXME: Should allocate from normal heap so that we can free this later.
320 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000321 Saved->Param = Info.Param;
322 Saved->FirstArg = Info.FirstArg;
323 Saved->SecondArg = Info.SecondArg;
324 Result.Data = Saved;
325 break;
326 }
327
328 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000329 Result.Data = Info.take();
330 break;
331
Douglas Gregora9333192010-05-08 17:41:32 +0000332 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000333 case Sema::TDK_FailedOverloadResolution:
334 break;
335 }
336
337 return Result;
338}
John McCall1d318332010-01-12 00:44:57 +0000339
Douglas Gregora9333192010-05-08 17:41:32 +0000340void OverloadCandidate::DeductionFailureInfo::Destroy() {
341 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
342 case Sema::TDK_Success:
343 case Sema::TDK_InstantiationDepth:
344 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000345 case Sema::TDK_TooManyArguments:
346 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000347 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000348 break;
349
Douglas Gregora9333192010-05-08 17:41:32 +0000350 case Sema::TDK_Inconsistent:
351 case Sema::TDK_InconsistentQuals:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000352 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000353 Data = 0;
354 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000355
356 case Sema::TDK_SubstitutionFailure:
357 // FIXME: Destroy the template arugment list?
358 Data = 0;
359 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000360
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000361 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000362 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000363 case Sema::TDK_FailedOverloadResolution:
364 break;
365 }
366}
367
368TemplateParameter
369OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
370 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
371 case Sema::TDK_Success:
372 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000373 case Sema::TDK_TooManyArguments:
374 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000375 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000376 return TemplateParameter();
377
378 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000379 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000380 return TemplateParameter::getFromOpaqueValue(Data);
381
382 case Sema::TDK_Inconsistent:
383 case Sema::TDK_InconsistentQuals:
384 return static_cast<DFIParamWithArguments*>(Data)->Param;
385
386 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000387 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000388 case Sema::TDK_FailedOverloadResolution:
389 break;
390 }
391
392 return TemplateParameter();
393}
Douglas Gregorec20f462010-05-08 20:07:26 +0000394
395TemplateArgumentList *
396OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
397 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
398 case Sema::TDK_Success:
399 case Sema::TDK_InstantiationDepth:
400 case Sema::TDK_TooManyArguments:
401 case Sema::TDK_TooFewArguments:
402 case Sema::TDK_Incomplete:
403 case Sema::TDK_InvalidExplicitArguments:
404 case Sema::TDK_Inconsistent:
405 case Sema::TDK_InconsistentQuals:
406 return 0;
407
408 case Sema::TDK_SubstitutionFailure:
409 return static_cast<TemplateArgumentList*>(Data);
410
411 // Unhandled
412 case Sema::TDK_NonDeducedMismatch:
413 case Sema::TDK_FailedOverloadResolution:
414 break;
415 }
416
417 return 0;
418}
419
Douglas Gregora9333192010-05-08 17:41:32 +0000420const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
421 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
422 case Sema::TDK_Success:
423 case Sema::TDK_InstantiationDepth:
424 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000425 case Sema::TDK_TooManyArguments:
426 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000427 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000428 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000429 return 0;
430
Douglas Gregora9333192010-05-08 17:41:32 +0000431 case Sema::TDK_Inconsistent:
432 case Sema::TDK_InconsistentQuals:
433 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
434
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000435 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000436 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000437 case Sema::TDK_FailedOverloadResolution:
438 break;
439 }
440
441 return 0;
442}
443
444const TemplateArgument *
445OverloadCandidate::DeductionFailureInfo::getSecondArg() {
446 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
447 case Sema::TDK_Success:
448 case Sema::TDK_InstantiationDepth:
449 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000450 case Sema::TDK_TooManyArguments:
451 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000452 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000453 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000454 return 0;
455
Douglas Gregora9333192010-05-08 17:41:32 +0000456 case Sema::TDK_Inconsistent:
457 case Sema::TDK_InconsistentQuals:
458 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
459
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000460 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000461 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000462 case Sema::TDK_FailedOverloadResolution:
463 break;
464 }
465
466 return 0;
467}
468
469void OverloadCandidateSet::clear() {
Douglas Gregora9333192010-05-08 17:41:32 +0000470 inherited::clear();
471 Functions.clear();
472}
473
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000474// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000475// overload of the declarations in Old. This routine returns false if
476// New and Old cannot be overloaded, e.g., if New has the same
477// signature as some function in Old (C++ 1.3.10) or if the Old
478// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000479// it does return false, MatchedDecl will point to the decl that New
480// cannot be overloaded with. This decl may be a UsingShadowDecl on
481// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000482//
483// Example: Given the following input:
484//
485// void f(int, float); // #1
486// void f(int, int); // #2
487// int f(int, int); // #3
488//
489// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000490// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000491//
John McCall51fa86f2009-12-02 08:47:38 +0000492// When we process #2, Old contains only the FunctionDecl for #1. By
493// comparing the parameter types, we see that #1 and #2 are overloaded
494// (since they have different signatures), so this routine returns
495// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000496//
John McCall51fa86f2009-12-02 08:47:38 +0000497// When we process #3, Old is an overload set containing #1 and #2. We
498// compare the signatures of #3 to #1 (they're overloaded, so we do
499// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
500// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000501// signature), IsOverload returns false and MatchedDecl will be set to
502// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000503//
504// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
505// into a class by a using declaration. The rules for whether to hide
506// shadow declarations ignore some properties which otherwise figure
507// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000508Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000509Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
510 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000511 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000512 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000513 NamedDecl *OldD = *I;
514
515 bool OldIsUsingDecl = false;
516 if (isa<UsingShadowDecl>(OldD)) {
517 OldIsUsingDecl = true;
518
519 // We can always introduce two using declarations into the same
520 // context, even if they have identical signatures.
521 if (NewIsUsingDecl) continue;
522
523 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
524 }
525
526 // If either declaration was introduced by a using declaration,
527 // we'll need to use slightly different rules for matching.
528 // Essentially, these rules are the normal rules, except that
529 // function templates hide function templates with different
530 // return types or template parameter lists.
531 bool UseMemberUsingDeclRules =
532 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
533
John McCall51fa86f2009-12-02 08:47:38 +0000534 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000535 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
536 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
537 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
538 continue;
539 }
540
John McCall871b2e72009-12-09 03:35:25 +0000541 Match = *I;
542 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000543 }
John McCall51fa86f2009-12-02 08:47:38 +0000544 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000545 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
546 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
547 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
548 continue;
549 }
550
John McCall871b2e72009-12-09 03:35:25 +0000551 Match = *I;
552 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000553 }
John McCall9f54ad42009-12-10 09:41:52 +0000554 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
555 // We can overload with these, which can show up when doing
556 // redeclaration checks for UsingDecls.
557 assert(Old.getLookupKind() == LookupUsingDeclName);
558 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
559 // Optimistically assume that an unresolved using decl will
560 // overload; if it doesn't, we'll have to diagnose during
561 // template instantiation.
562 } else {
John McCall68263142009-11-18 22:49:29 +0000563 // (C++ 13p1):
564 // Only function declarations can be overloaded; object and type
565 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000566 Match = *I;
567 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000568 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000569 }
John McCall68263142009-11-18 22:49:29 +0000570
John McCall871b2e72009-12-09 03:35:25 +0000571 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000572}
573
John McCallad00b772010-06-16 08:42:20 +0000574bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
575 bool UseUsingDeclRules) {
John McCall68263142009-11-18 22:49:29 +0000576 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
577 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
578
579 // C++ [temp.fct]p2:
580 // A function template can be overloaded with other function templates
581 // and with normal (non-template) functions.
582 if ((OldTemplate == 0) != (NewTemplate == 0))
583 return true;
584
585 // Is the function New an overload of the function Old?
586 QualType OldQType = Context.getCanonicalType(Old->getType());
587 QualType NewQType = Context.getCanonicalType(New->getType());
588
589 // Compare the signatures (C++ 1.3.10) of the two functions to
590 // determine whether they are overloads. If we find any mismatch
591 // in the signature, they are overloads.
592
593 // If either of these functions is a K&R-style function (no
594 // prototype), then we consider them to have matching signatures.
595 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
596 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
597 return false;
598
599 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
600 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
601
602 // The signature of a function includes the types of its
603 // parameters (C++ 1.3.10), which includes the presence or absence
604 // of the ellipsis; see C++ DR 357).
605 if (OldQType != NewQType &&
606 (OldType->getNumArgs() != NewType->getNumArgs() ||
607 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000608 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000609 return true;
610
611 // C++ [temp.over.link]p4:
612 // The signature of a function template consists of its function
613 // signature, its return type and its template parameter list. The names
614 // of the template parameters are significant only for establishing the
615 // relationship between the template parameters and the rest of the
616 // signature.
617 //
618 // We check the return type and template parameter lists for function
619 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +0000620 //
621 // However, we don't consider either of these when deciding whether
622 // a member introduced by a shadow declaration is hidden.
623 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +0000624 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
625 OldTemplate->getTemplateParameters(),
626 false, TPL_TemplateMatch) ||
627 OldType->getResultType() != NewType->getResultType()))
628 return true;
629
630 // If the function is a class member, its signature includes the
631 // cv-qualifiers (if any) on the function itself.
632 //
633 // As part of this, also check whether one of the member functions
634 // is static, in which case they are not overloads (C++
635 // 13.1p2). While not part of the definition of the signature,
636 // this check is important to determine whether these functions
637 // can be overloaded.
638 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
639 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
640 if (OldMethod && NewMethod &&
641 !OldMethod->isStatic() && !NewMethod->isStatic() &&
642 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
643 return true;
644
645 // The signatures match; this is not an overload.
646 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000647}
648
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000649/// TryImplicitConversion - Attempt to perform an implicit conversion
650/// from the given expression (Expr) to the given type (ToType). This
651/// function returns an implicit conversion sequence that can be used
652/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000653///
654/// void f(float f);
655/// void g(int i) { f(i); }
656///
657/// this routine would produce an implicit conversion sequence to
658/// describe the initialization of f from i, which will be a standard
659/// conversion sequence containing an lvalue-to-rvalue conversion (C++
660/// 4.1) followed by a floating-integral conversion (C++ 4.9).
661//
662/// Note that this routine only determines how the conversion can be
663/// performed; it does not actually perform the conversion. As such,
664/// it will not produce any diagnostics if no conversion is available,
665/// but will instead return an implicit conversion sequence of kind
666/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000667///
668/// If @p SuppressUserConversions, then user-defined conversions are
669/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000670/// If @p AllowExplicit, then explicit user-defined conversions are
671/// permitted.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000672ImplicitConversionSequence
Anders Carlsson2974b5c2009-08-27 17:14:02 +0000673Sema::TryImplicitConversion(Expr* From, QualType ToType,
674 bool SuppressUserConversions,
Douglas Gregor74e386e2010-04-16 18:00:29 +0000675 bool AllowExplicit,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000676 bool InOverloadResolution) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000677 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +0000678 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
John McCall1d318332010-01-12 00:44:57 +0000679 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +0000680 return ICS;
681 }
682
683 if (!getLangOptions().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +0000684 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +0000685 return ICS;
686 }
687
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000688 if (SuppressUserConversions) {
689 // C++ [over.ics.user]p4:
690 // A conversion of an expression of class type to the same class
691 // type is given Exact Match rank, and a conversion of an
692 // expression of class type to a base class of that type is
693 // given Conversion rank, in spite of the fact that a copy/move
694 // constructor (i.e., a user-defined conversion function) is
695 // called for those cases.
696 QualType FromType = From->getType();
697 if (!ToType->getAs<RecordType>() || !FromType->getAs<RecordType>() ||
698 !(Context.hasSameUnqualifiedType(FromType, ToType) ||
699 IsDerivedFrom(FromType, ToType))) {
700 // We're not in the case above, so there is no conversion that
701 // we can perform.
702 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
703 return ICS;
704 }
705
706 ICS.setStandard();
707 ICS.Standard.setAsIdentityConversion();
708 ICS.Standard.setFromType(FromType);
709 ICS.Standard.setAllToTypes(ToType);
710
711 // We don't actually check at this point whether there is a valid
712 // copy/move constructor, since overloading just assumes that it
713 // exists. When we actually perform initialization, we'll find the
714 // appropriate constructor to copy the returned object, if needed.
715 ICS.Standard.CopyConstructor = 0;
716
717 // Determine whether this is considered a derived-to-base conversion.
718 if (!Context.hasSameUnqualifiedType(FromType, ToType))
719 ICS.Standard.Second = ICK_Derived_To_Base;
720
721 return ICS;
722 }
723
724 // Attempt user-defined conversion.
John McCall5769d612010-02-08 23:07:23 +0000725 OverloadCandidateSet Conversions(From->getExprLoc());
726 OverloadingResult UserDefResult
727 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000728 AllowExplicit);
John McCall5769d612010-02-08 23:07:23 +0000729
730 if (UserDefResult == OR_Success) {
John McCall1d318332010-01-12 00:44:57 +0000731 ICS.setUserDefined();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000732 // C++ [over.ics.user]p4:
733 // A conversion of an expression of class type to the same class
734 // type is given Exact Match rank, and a conversion of an
735 // expression of class type to a base class of that type is
736 // given Conversion rank, in spite of the fact that a copy
737 // constructor (i.e., a user-defined conversion function) is
738 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000739 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000740 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000741 QualType FromCanon
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000742 = Context.getCanonicalType(From->getType().getUnqualifiedType());
743 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor9e9199d2009-12-22 00:34:07 +0000744 if (Constructor->isCopyConstructor() &&
Douglas Gregor0d6d12b2009-12-22 00:21:20 +0000745 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000746 // Turn this into a "standard" conversion sequence, so that it
747 // gets ranked with standard conversion sequences.
John McCall1d318332010-01-12 00:44:57 +0000748 ICS.setStandard();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000749 ICS.Standard.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +0000750 ICS.Standard.setFromType(From->getType());
Douglas Gregorad323a82010-01-27 03:51:04 +0000751 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000752 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000753 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000754 ICS.Standard.Second = ICK_Derived_To_Base;
755 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000756 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000757
758 // C++ [over.best.ics]p4:
759 // However, when considering the argument of a user-defined
760 // conversion function that is a candidate by 13.3.1.3 when
761 // invoked for the copying of the temporary in the second step
762 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
763 // 13.3.1.6 in all cases, only standard conversion sequences and
764 // ellipsis conversion sequences are allowed.
John McCalladbb8f82010-01-13 09:16:55 +0000765 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCallb1bdc622010-02-25 01:37:24 +0000766 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCalladbb8f82010-01-13 09:16:55 +0000767 }
John McCallcefd3ad2010-01-13 22:30:33 +0000768 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall1d318332010-01-12 00:44:57 +0000769 ICS.setAmbiguous();
770 ICS.Ambiguous.setFromType(From->getType());
771 ICS.Ambiguous.setToType(ToType);
772 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
773 Cand != Conversions.end(); ++Cand)
774 if (Cand->Viable)
775 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000776 } else {
John McCallb1bdc622010-02-25 01:37:24 +0000777 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000778 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000779
780 return ICS;
781}
782
Douglas Gregor575c63a2010-04-16 22:27:05 +0000783/// PerformImplicitConversion - Perform an implicit conversion of the
784/// expression From to the type ToType. Returns true if there was an
785/// error, false otherwise. The expression From is replaced with the
786/// converted expression. Flavor is the kind of conversion we're
787/// performing, used in the error message. If @p AllowExplicit,
788/// explicit user-defined conversions are permitted.
789bool
790Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
791 AssignmentAction Action, bool AllowExplicit) {
792 ImplicitConversionSequence ICS;
793 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
794}
795
796bool
797Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
798 AssignmentAction Action, bool AllowExplicit,
799 ImplicitConversionSequence& ICS) {
800 ICS = TryImplicitConversion(From, ToType,
801 /*SuppressUserConversions=*/false,
802 AllowExplicit,
803 /*InOverloadResolution=*/false);
804 return PerformImplicitConversion(From, ToType, ICS, Action);
805}
806
Douglas Gregor43c79c22009-12-09 00:47:37 +0000807/// \brief Determine whether the conversion from FromType to ToType is a valid
808/// conversion that strips "noreturn" off the nested function type.
809static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
810 QualType ToType, QualType &ResultTy) {
811 if (Context.hasSameUnqualifiedType(FromType, ToType))
812 return false;
813
814 // Strip the noreturn off the type we're converting from; noreturn can
815 // safely be removed.
816 FromType = Context.getNoReturnType(FromType, false);
817 if (!Context.hasSameUnqualifiedType(FromType, ToType))
818 return false;
819
820 ResultTy = FromType;
821 return true;
822}
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000823
824/// \brief Determine whether the conversion from FromType to ToType is a valid
825/// vector conversion.
826///
827/// \param ICK Will be set to the vector conversion kind, if this is a vector
828/// conversion.
829static bool IsVectorConversion(ASTContext &Context, QualType FromType,
830 QualType ToType, ImplicitConversionKind &ICK) {
831 // We need at least one of these types to be a vector type to have a vector
832 // conversion.
833 if (!ToType->isVectorType() && !FromType->isVectorType())
834 return false;
835
836 // Identical types require no conversions.
837 if (Context.hasSameUnqualifiedType(FromType, ToType))
838 return false;
839
840 // There are no conversions between extended vector types, only identity.
841 if (ToType->isExtVectorType()) {
842 // There are no conversions between extended vector types other than the
843 // identity conversion.
844 if (FromType->isExtVectorType())
845 return false;
846
847 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +0000848 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000849 ICK = ICK_Vector_Splat;
850 return true;
851 }
852 }
853
854 // If lax vector conversions are permitted and the vector types are of the
855 // same size, we can perform the conversion.
856 if (Context.getLangOptions().LaxVectorConversions &&
857 FromType->isVectorType() && ToType->isVectorType() &&
858 Context.getTypeSize(FromType) == Context.getTypeSize(ToType)) {
859 ICK = ICK_Vector_Conversion;
860 return true;
861 }
862
863 return false;
864}
Douglas Gregor43c79c22009-12-09 00:47:37 +0000865
Douglas Gregor60d62c22008-10-31 16:23:19 +0000866/// IsStandardConversion - Determines whether there is a standard
867/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
868/// expression From to the type ToType. Standard conversion sequences
869/// only consider non-class types; for conversions that involve class
870/// types, use TryImplicitConversion. If a conversion exists, SCS will
871/// contain the standard conversion sequence required to perform this
872/// conversion and this routine will return true. Otherwise, this
873/// routine will return false and the value of SCS is unspecified.
Mike Stump1eb44332009-09-09 15:08:12 +0000874bool
875Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000876 bool InOverloadResolution,
Mike Stump1eb44332009-09-09 15:08:12 +0000877 StandardConversionSequence &SCS) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000878 QualType FromType = From->getType();
879
Douglas Gregor60d62c22008-10-31 16:23:19 +0000880 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000881 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +0000882 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000883 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +0000884 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000885 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000886
Douglas Gregorf9201e02009-02-11 23:02:49 +0000887 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +0000888 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +0000889 if (FromType->isRecordType() || ToType->isRecordType()) {
890 if (getLangOptions().CPlusPlus)
891 return false;
892
Mike Stump1eb44332009-09-09 15:08:12 +0000893 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000894 }
895
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000896 // The first conversion can be an lvalue-to-rvalue conversion,
897 // array-to-pointer conversion, or function-to-pointer conversion
898 // (C++ 4p1).
899
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000900 if (FromType == Context.OverloadTy) {
901 DeclAccessPair AccessPair;
902 if (FunctionDecl *Fn
903 = ResolveAddressOfOverloadedFunction(From, ToType, false,
904 AccessPair)) {
905 // We were able to resolve the address of the overloaded function,
906 // so we can convert to the type of that function.
907 FromType = Fn->getType();
908 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
909 if (!Method->isStatic()) {
910 Type *ClassType
911 = Context.getTypeDeclType(Method->getParent()).getTypePtr();
912 FromType = Context.getMemberPointerType(FromType, ClassType);
913 }
914 }
915
916 // If the "from" expression takes the address of the overloaded
917 // function, update the type of the resulting expression accordingly.
918 if (FromType->getAs<FunctionType>())
919 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
920 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
921 FromType = Context.getPointerType(FromType);
922
923 // Check that we've computed the proper type after overload resolution.
924 assert(Context.hasSameType(FromType,
925 FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
926 } else {
927 return false;
928 }
929 }
Mike Stump1eb44332009-09-09 15:08:12 +0000930 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000931 // An lvalue (3.10) of a non-function, non-array type T can be
932 // converted to an rvalue.
933 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000934 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000935 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor063daf62009-03-13 18:40:31 +0000936 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000937 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000938
939 // If T is a non-class type, the type of the rvalue is the
940 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +0000941 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
942 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000943 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000944 } else if (FromType->isArrayType()) {
945 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000946 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000947
948 // An lvalue or rvalue of type "array of N T" or "array of unknown
949 // bound of T" can be converted to an rvalue of type "pointer to
950 // T" (C++ 4.2p1).
951 FromType = Context.getArrayDecayedType(FromType);
952
953 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
954 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +0000955 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000956
957 // For the purpose of ranking in overload resolution
958 // (13.3.3.1.1), this conversion is considered an
959 // array-to-pointer conversion followed by a qualification
960 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000961 SCS.Second = ICK_Identity;
962 SCS.Third = ICK_Qualification;
Douglas Gregorad323a82010-01-27 03:51:04 +0000963 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000964 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000965 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000966 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
967 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000968 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000969
970 // An lvalue of function type T can be converted to an rvalue of
971 // type "pointer to T." The result is a pointer to the
972 // function. (C++ 4.3p1).
973 FromType = Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000974 } else {
975 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000976 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000977 }
Douglas Gregorad323a82010-01-27 03:51:04 +0000978 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000979
980 // The second conversion can be an integral promotion, floating
981 // point promotion, integral conversion, floating point conversion,
982 // floating-integral conversion, pointer conversion,
983 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +0000984 // For overloading in C, this can also be a "compatible-type"
985 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +0000986 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000987 ImplicitConversionKind SecondICK = ICK_Identity;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000988 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000989 // The unqualified versions of the types are the same: there's no
990 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000991 SCS.Second = ICK_Identity;
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000992 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000993 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000994 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000995 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000996 } else if (IsFloatingPointPromotion(FromType, ToType)) {
997 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000998 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000999 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001000 } else if (IsComplexPromotion(FromType, ToType)) {
1001 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001002 SCS.Second = ICK_Complex_Promotion;
1003 FromType = ToType.getUnqualifiedType();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001004 } else if (FromType->isIntegralOrEnumerationType() &&
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001005 ToType->isIntegralType(Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001006 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001007 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001008 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001009 } else if (FromType->isComplexType() && ToType->isComplexType()) {
1010 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001011 SCS.Second = ICK_Complex_Conversion;
1012 FromType = ToType.getUnqualifiedType();
Chandler Carruth23a370f2010-02-25 07:20:54 +00001013 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
1014 (ToType->isComplexType() && FromType->isArithmeticType())) {
1015 // Complex-real conversions (C99 6.3.1.7)
1016 SCS.Second = ICK_Complex_Real;
1017 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001018 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001019 // Floating point conversions (C++ 4.8).
1020 SCS.Second = ICK_Floating_Conversion;
1021 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001022 } else if ((FromType->isRealFloatingType() &&
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001023 ToType->isIntegralType(Context) && !ToType->isBooleanType()) ||
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001024 (FromType->isIntegralOrEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001025 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001026 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001027 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001028 FromType = ToType.getUnqualifiedType();
Anders Carlsson08972922009-08-28 15:33:32 +00001029 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1030 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001031 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001032 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001033 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregorce940492009-09-25 04:25:58 +00001034 } else if (IsMemberPointerConversion(From, FromType, ToType,
1035 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001036 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001037 SCS.Second = ICK_Pointer_Member;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001038 } else if (ToType->isBooleanType() &&
1039 (FromType->isArithmeticType() ||
1040 FromType->isEnumeralType() ||
Fariborz Jahanian1f7711d2009-12-11 21:23:13 +00001041 FromType->isAnyPointerType() ||
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001042 FromType->isBlockPointerType() ||
1043 FromType->isMemberPointerType() ||
Douglas Gregor00619622010-06-22 23:41:02 +00001044 FromType->isNullPtrType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001045 // Boolean conversions (C++ 4.12).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001046 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001047 FromType = Context.BoolTy;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001048 } else if (IsVectorConversion(Context, FromType, ToType, SecondICK)) {
1049 SCS.Second = SecondICK;
1050 FromType = ToType.getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00001051 } else if (!getLangOptions().CPlusPlus &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001052 Context.typesAreCompatible(ToType, FromType)) {
1053 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001054 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001055 FromType = ToType.getUnqualifiedType();
Douglas Gregor43c79c22009-12-09 00:47:37 +00001056 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
1057 // Treat a conversion that strips "noreturn" as an identity conversion.
1058 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001059 } else {
1060 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001061 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001062 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001063 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001064
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001065 QualType CanonFrom;
1066 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001067 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +00001068 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001069 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001070 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001071 CanonFrom = Context.getCanonicalType(FromType);
1072 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001073 } else {
1074 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001075 SCS.Third = ICK_Identity;
1076
Mike Stump1eb44332009-09-09 15:08:12 +00001077 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001078 // [...] Any difference in top-level cv-qualification is
1079 // subsumed by the initialization itself and does not constitute
1080 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001081 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +00001082 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00001083 if (CanonFrom.getLocalUnqualifiedType()
1084 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001085 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1086 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001087 FromType = ToType;
1088 CanonFrom = CanonTo;
1089 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001090 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001091 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001092
1093 // If we have not converted the argument type to the parameter type,
1094 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001095 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001096 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001097
Douglas Gregor60d62c22008-10-31 16:23:19 +00001098 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001099}
1100
1101/// IsIntegralPromotion - Determines whether the conversion from the
1102/// expression From (whose potentially-adjusted type is FromType) to
1103/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1104/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001105bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001106 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001107 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001108 if (!To) {
1109 return false;
1110 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001111
1112 // An rvalue of type char, signed char, unsigned char, short int, or
1113 // unsigned short int can be converted to an rvalue of type int if
1114 // int can represent all the values of the source type; otherwise,
1115 // the source rvalue can be converted to an rvalue of type unsigned
1116 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001117 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1118 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001119 if (// We can promote any signed, promotable integer type to an int
1120 (FromType->isSignedIntegerType() ||
1121 // We can promote any unsigned integer type whose size is
1122 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001123 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001124 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001125 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001126 }
1127
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001128 return To->getKind() == BuiltinType::UInt;
1129 }
1130
1131 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
1132 // can be converted to an rvalue of the first of the following types
1133 // that can represent all the values of its underlying type: int,
1134 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall842aef82009-12-09 09:09:27 +00001135
1136 // We pre-calculate the promotion type for enum types.
1137 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
1138 if (ToType->isIntegerType())
1139 return Context.hasSameUnqualifiedType(ToType,
1140 FromEnumType->getDecl()->getPromotionType());
1141
1142 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001143 // Determine whether the type we're converting from is signed or
1144 // unsigned.
1145 bool FromIsSigned;
1146 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall842aef82009-12-09 09:09:27 +00001147
1148 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1149 FromIsSigned = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001150
1151 // The types we'll try to promote to, in the appropriate
1152 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001153 QualType PromoteTypes[6] = {
1154 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001155 Context.LongTy, Context.UnsignedLongTy ,
1156 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001157 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001158 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001159 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1160 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001161 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001162 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1163 // We found the type that we can promote to. If this is the
1164 // type we wanted, we have a promotion. Otherwise, no
1165 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001166 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001167 }
1168 }
1169 }
1170
1171 // An rvalue for an integral bit-field (9.6) can be converted to an
1172 // rvalue of type int if int can represent all the values of the
1173 // bit-field; otherwise, it can be converted to unsigned int if
1174 // unsigned int can represent all the values of the bit-field. If
1175 // the bit-field is larger yet, no integral promotion applies to
1176 // it. If the bit-field has an enumerated type, it is treated as any
1177 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001178 // FIXME: We should delay checking of bit-fields until we actually perform the
1179 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001180 using llvm::APSInt;
1181 if (From)
1182 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001183 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001184 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001185 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1186 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1187 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001188
Douglas Gregor86f19402008-12-20 23:49:58 +00001189 // Are we promoting to an int from a bitfield that fits in an int?
1190 if (BitWidth < ToSize ||
1191 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1192 return To->getKind() == BuiltinType::Int;
1193 }
Mike Stump1eb44332009-09-09 15:08:12 +00001194
Douglas Gregor86f19402008-12-20 23:49:58 +00001195 // Are we promoting to an unsigned int from an unsigned bitfield
1196 // that fits into an unsigned int?
1197 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1198 return To->getKind() == BuiltinType::UInt;
1199 }
Mike Stump1eb44332009-09-09 15:08:12 +00001200
Douglas Gregor86f19402008-12-20 23:49:58 +00001201 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001202 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001203 }
Mike Stump1eb44332009-09-09 15:08:12 +00001204
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001205 // An rvalue of type bool can be converted to an rvalue of type int,
1206 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001207 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001208 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001209 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001210
1211 return false;
1212}
1213
1214/// IsFloatingPointPromotion - Determines whether the conversion from
1215/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1216/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001217bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001218 /// An rvalue of type float can be converted to an rvalue of type
1219 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +00001220 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1221 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001222 if (FromBuiltin->getKind() == BuiltinType::Float &&
1223 ToBuiltin->getKind() == BuiltinType::Double)
1224 return true;
1225
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001226 // C99 6.3.1.5p1:
1227 // When a float is promoted to double or long double, or a
1228 // double is promoted to long double [...].
1229 if (!getLangOptions().CPlusPlus &&
1230 (FromBuiltin->getKind() == BuiltinType::Float ||
1231 FromBuiltin->getKind() == BuiltinType::Double) &&
1232 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1233 return true;
1234 }
1235
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001236 return false;
1237}
1238
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001239/// \brief Determine if a conversion is a complex promotion.
1240///
1241/// A complex promotion is defined as a complex -> complex conversion
1242/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001243/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001244bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001245 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001246 if (!FromComplex)
1247 return false;
1248
John McCall183700f2009-09-21 23:43:11 +00001249 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001250 if (!ToComplex)
1251 return false;
1252
1253 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001254 ToComplex->getElementType()) ||
1255 IsIntegralPromotion(0, FromComplex->getElementType(),
1256 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001257}
1258
Douglas Gregorcb7de522008-11-26 23:31:11 +00001259/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1260/// the pointer type FromPtr to a pointer to type ToPointee, with the
1261/// same type qualifiers as FromPtr has on its pointee type. ToType,
1262/// if non-empty, will be a pointer to ToType that may or may not have
1263/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +00001264static QualType
1265BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001266 QualType ToPointee, QualType ToType,
1267 ASTContext &Context) {
1268 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1269 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001270 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001271
1272 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001273 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001274 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001275 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001276 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001277
1278 // Build a pointer to ToPointee. It has the right qualifiers
1279 // already.
1280 return Context.getPointerType(ToPointee);
1281 }
1282
1283 // Just build a canonical type that has the right qualifiers.
John McCall0953e762009-09-24 19:53:00 +00001284 return Context.getPointerType(
Douglas Gregora4923eb2009-11-16 21:35:15 +00001285 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1286 Quals));
Douglas Gregorcb7de522008-11-26 23:31:11 +00001287}
1288
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001289/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1290/// the FromType, which is an objective-c pointer, to ToType, which may or may
1291/// not have the right set of qualifiers.
1292static QualType
1293BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1294 QualType ToType,
1295 ASTContext &Context) {
1296 QualType CanonFromType = Context.getCanonicalType(FromType);
1297 QualType CanonToType = Context.getCanonicalType(ToType);
1298 Qualifiers Quals = CanonFromType.getQualifiers();
1299
1300 // Exact qualifier match -> return the pointer type we're converting to.
1301 if (CanonToType.getLocalQualifiers() == Quals)
1302 return ToType;
1303
1304 // Just build a canonical type that has the right qualifiers.
1305 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1306}
1307
Mike Stump1eb44332009-09-09 15:08:12 +00001308static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001309 bool InOverloadResolution,
1310 ASTContext &Context) {
1311 // Handle value-dependent integral null pointer constants correctly.
1312 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1313 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001314 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001315 return !InOverloadResolution;
1316
Douglas Gregorce940492009-09-25 04:25:58 +00001317 return Expr->isNullPointerConstant(Context,
1318 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1319 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001320}
Mike Stump1eb44332009-09-09 15:08:12 +00001321
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001322/// IsPointerConversion - Determines whether the conversion of the
1323/// expression From, which has the (possibly adjusted) type FromType,
1324/// can be converted to the type ToType via a pointer conversion (C++
1325/// 4.10). If so, returns true and places the converted type (that
1326/// might differ from ToType in its cv-qualifiers at some level) into
1327/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001328///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001329/// This routine also supports conversions to and from block pointers
1330/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1331/// pointers to interfaces. FIXME: Once we've determined the
1332/// appropriate overloading rules for Objective-C, we may want to
1333/// split the Objective-C checks into a different routine; however,
1334/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001335/// conversions, so for now they live here. IncompatibleObjC will be
1336/// set if the conversion is an allowed Objective-C conversion that
1337/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001338bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001339 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001340 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001341 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001342 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +00001343 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1344 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001345
Mike Stump1eb44332009-09-09 15:08:12 +00001346 // Conversion from a null pointer constant to any Objective-C pointer type.
1347 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001348 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001349 ConvertedType = ToType;
1350 return true;
1351 }
1352
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001353 // Blocks: Block pointers can be converted to void*.
1354 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001355 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001356 ConvertedType = ToType;
1357 return true;
1358 }
1359 // Blocks: A null pointer constant can be converted to a block
1360 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001361 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001362 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001363 ConvertedType = ToType;
1364 return true;
1365 }
1366
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001367 // If the left-hand-side is nullptr_t, the right side can be a null
1368 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001369 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001370 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001371 ConvertedType = ToType;
1372 return true;
1373 }
1374
Ted Kremenek6217b802009-07-29 21:53:49 +00001375 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001376 if (!ToTypePtr)
1377 return false;
1378
1379 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001380 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001381 ConvertedType = ToType;
1382 return true;
1383 }
Sebastian Redl07779722008-10-31 14:43:28 +00001384
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001385 // Beyond this point, both types need to be pointers
1386 // , including objective-c pointers.
1387 QualType ToPointeeType = ToTypePtr->getPointeeType();
1388 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1389 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1390 ToType, Context);
1391 return true;
1392
1393 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001394 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001395 if (!FromTypePtr)
1396 return false;
1397
1398 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001399
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001400 // An rvalue of type "pointer to cv T," where T is an object type,
1401 // can be converted to an rvalue of type "pointer to cv void" (C++
1402 // 4.10p2).
Douglas Gregorbad0e652009-03-24 20:32:41 +00001403 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001404 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001405 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001406 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001407 return true;
1408 }
1409
Douglas Gregorf9201e02009-02-11 23:02:49 +00001410 // When we're overloading in C, we allow a special kind of pointer
1411 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001412 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001413 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001414 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001415 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001416 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001417 return true;
1418 }
1419
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001420 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001421 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001422 // An rvalue of type "pointer to cv D," where D is a class type,
1423 // can be converted to an rvalue of type "pointer to cv B," where
1424 // B is a base class (clause 10) of D. If B is an inaccessible
1425 // (clause 11) or ambiguous (10.2) base class of D, a program that
1426 // necessitates this conversion is ill-formed. The result of the
1427 // conversion is a pointer to the base class sub-object of the
1428 // derived class object. The null pointer value is converted to
1429 // the null pointer value of the destination type.
1430 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001431 // Note that we do not check for ambiguity or inaccessibility
1432 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001433 if (getLangOptions().CPlusPlus &&
1434 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001435 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001436 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001437 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001438 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001439 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001440 ToType, Context);
1441 return true;
1442 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001443
Douglas Gregorc7887512008-12-19 19:13:09 +00001444 return false;
1445}
1446
1447/// isObjCPointerConversion - Determines whether this is an
1448/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1449/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001450bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001451 QualType& ConvertedType,
1452 bool &IncompatibleObjC) {
1453 if (!getLangOptions().ObjC1)
1454 return false;
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001455
Steve Naroff14108da2009-07-10 23:34:53 +00001456 // First, we handle all conversions on ObjC object pointer types.
John McCall183700f2009-09-21 23:43:11 +00001457 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001458 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001459 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001460
Steve Naroff14108da2009-07-10 23:34:53 +00001461 if (ToObjCPtr && FromObjCPtr) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00001462 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001463 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001464 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001465 ConvertedType = ToType;
1466 return true;
1467 }
1468 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001469 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001470 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001471 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001472 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001473 ConvertedType = ToType;
1474 return true;
1475 }
1476 // Objective C++: We're able to convert from a pointer to an
1477 // interface to a pointer to a different interface.
1478 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00001479 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1480 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1481 if (getLangOptions().CPlusPlus && LHS && RHS &&
1482 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1483 FromObjCPtr->getPointeeType()))
1484 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00001485 ConvertedType = ToType;
1486 return true;
1487 }
1488
1489 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1490 // Okay: this is some kind of implicit downcast of Objective-C
1491 // interfaces, which is permitted. However, we're going to
1492 // complain about it.
1493 IncompatibleObjC = true;
1494 ConvertedType = FromType;
1495 return true;
1496 }
Mike Stump1eb44332009-09-09 15:08:12 +00001497 }
Steve Naroff14108da2009-07-10 23:34:53 +00001498 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001499 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001500 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001501 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001502 else if (const BlockPointerType *ToBlockPtr =
1503 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00001504 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001505 // to a block pointer type.
1506 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1507 ConvertedType = ToType;
1508 return true;
1509 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001510 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001511 }
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001512 else if (FromType->getAs<BlockPointerType>() &&
1513 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1514 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00001515 // pointer to any object.
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001516 ConvertedType = ToType;
1517 return true;
1518 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001519 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001520 return false;
1521
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001522 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001523 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001524 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001525 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001526 FromPointeeType = FromBlockPtr->getPointeeType();
1527 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001528 return false;
1529
Douglas Gregorc7887512008-12-19 19:13:09 +00001530 // If we have pointers to pointers, recursively check whether this
1531 // is an Objective-C conversion.
1532 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1533 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1534 IncompatibleObjC)) {
1535 // We always complain about this conversion.
1536 IncompatibleObjC = true;
1537 ConvertedType = ToType;
1538 return true;
1539 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001540 // Allow conversion of pointee being objective-c pointer to another one;
1541 // as in I* to id.
1542 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1543 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1544 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1545 IncompatibleObjC)) {
1546 ConvertedType = ToType;
1547 return true;
1548 }
1549
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001550 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001551 // differences in the argument and result types are in Objective-C
1552 // pointer conversions. If so, we permit the conversion (but
1553 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001554 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001555 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001556 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001557 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001558 if (FromFunctionType && ToFunctionType) {
1559 // If the function types are exactly the same, this isn't an
1560 // Objective-C pointer conversion.
1561 if (Context.getCanonicalType(FromPointeeType)
1562 == Context.getCanonicalType(ToPointeeType))
1563 return false;
1564
1565 // Perform the quick checks that will tell us whether these
1566 // function types are obviously different.
1567 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1568 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1569 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1570 return false;
1571
1572 bool HasObjCConversion = false;
1573 if (Context.getCanonicalType(FromFunctionType->getResultType())
1574 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1575 // Okay, the types match exactly. Nothing to do.
1576 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1577 ToFunctionType->getResultType(),
1578 ConvertedType, IncompatibleObjC)) {
1579 // Okay, we have an Objective-C pointer conversion.
1580 HasObjCConversion = true;
1581 } else {
1582 // Function types are too different. Abort.
1583 return false;
1584 }
Mike Stump1eb44332009-09-09 15:08:12 +00001585
Douglas Gregorc7887512008-12-19 19:13:09 +00001586 // Check argument types.
1587 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1588 ArgIdx != NumArgs; ++ArgIdx) {
1589 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1590 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1591 if (Context.getCanonicalType(FromArgType)
1592 == Context.getCanonicalType(ToArgType)) {
1593 // Okay, the types match exactly. Nothing to do.
1594 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1595 ConvertedType, IncompatibleObjC)) {
1596 // Okay, we have an Objective-C pointer conversion.
1597 HasObjCConversion = true;
1598 } else {
1599 // Argument types are too different. Abort.
1600 return false;
1601 }
1602 }
1603
1604 if (HasObjCConversion) {
1605 // We had an Objective-C conversion. Allow this pointer
1606 // conversion, but complain about it.
1607 ConvertedType = ToType;
1608 IncompatibleObjC = true;
1609 return true;
1610 }
1611 }
1612
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001613 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001614}
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001615
1616/// FunctionArgTypesAreEqual - This routine checks two function proto types
1617/// for equlity of their argument types. Caller has already checked that
1618/// they have same number of arguments. This routine assumes that Objective-C
1619/// pointer types which only differ in their protocol qualifiers are equal.
1620bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1621 FunctionProtoType* NewType){
1622 if (!getLangOptions().ObjC1)
1623 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1624 NewType->arg_type_begin());
1625
1626 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1627 N = NewType->arg_type_begin(),
1628 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1629 QualType ToType = (*O);
1630 QualType FromType = (*N);
1631 if (ToType != FromType) {
1632 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1633 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00001634 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1635 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1636 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1637 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001638 continue;
1639 }
John McCallc12c5bb2010-05-15 11:32:37 +00001640 else if (const ObjCObjectPointerType *PTTo =
1641 ToType->getAs<ObjCObjectPointerType>()) {
1642 if (const ObjCObjectPointerType *PTFr =
1643 FromType->getAs<ObjCObjectPointerType>())
1644 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1645 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001646 }
1647 return false;
1648 }
1649 }
1650 return true;
1651}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001652
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001653/// CheckPointerConversion - Check the pointer conversion from the
1654/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001655/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001656/// conversions for which IsPointerConversion has already returned
1657/// true. It returns true and produces a diagnostic if there was an
1658/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001659bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001660 CastExpr::CastKind &Kind,
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001661 CXXBaseSpecifierArray& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001662 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001663 QualType FromType = From->getType();
1664
Douglas Gregord7a95972010-06-08 17:35:15 +00001665 if (CXXBoolLiteralExpr* LitBool
1666 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
1667 if (LitBool->getValue() == false)
1668 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1669 << ToType;
1670
Ted Kremenek6217b802009-07-29 21:53:49 +00001671 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1672 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001673 QualType FromPointeeType = FromPtrType->getPointeeType(),
1674 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001675
Douglas Gregor5fccd362010-03-03 23:55:11 +00001676 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1677 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001678 // We must have a derived-to-base conversion. Check an
1679 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001680 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1681 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001682 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001683 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001684 return true;
1685
1686 // The conversion was successful.
1687 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001688 }
1689 }
Mike Stump1eb44332009-09-09 15:08:12 +00001690 if (const ObjCObjectPointerType *FromPtrType =
John McCall183700f2009-09-21 23:43:11 +00001691 FromType->getAs<ObjCObjectPointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001692 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00001693 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001694 // Objective-C++ conversions are always okay.
1695 // FIXME: We should have a different class of conversions for the
1696 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001697 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001698 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001699
Steve Naroff14108da2009-07-10 23:34:53 +00001700 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001701 return false;
1702}
1703
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001704/// IsMemberPointerConversion - Determines whether the conversion of the
1705/// expression From, which has the (possibly adjusted) type FromType, can be
1706/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1707/// If so, returns true and places the converted type (that might differ from
1708/// ToType in its cv-qualifiers at some level) into ConvertedType.
1709bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregorce940492009-09-25 04:25:58 +00001710 QualType ToType,
1711 bool InOverloadResolution,
1712 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001713 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001714 if (!ToTypePtr)
1715 return false;
1716
1717 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00001718 if (From->isNullPointerConstant(Context,
1719 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1720 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001721 ConvertedType = ToType;
1722 return true;
1723 }
1724
1725 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001726 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001727 if (!FromTypePtr)
1728 return false;
1729
1730 // A pointer to member of B can be converted to a pointer to member of D,
1731 // where D is derived from B (C++ 4.11p2).
1732 QualType FromClass(FromTypePtr->getClass(), 0);
1733 QualType ToClass(ToTypePtr->getClass(), 0);
1734 // FIXME: What happens when these are dependent? Is this function even called?
1735
1736 if (IsDerivedFrom(ToClass, FromClass)) {
1737 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1738 ToClass.getTypePtr());
1739 return true;
1740 }
1741
1742 return false;
1743}
Douglas Gregor43c79c22009-12-09 00:47:37 +00001744
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001745/// CheckMemberPointerConversion - Check the member pointer conversion from the
1746/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00001747/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001748/// for which IsMemberPointerConversion has already returned true. It returns
1749/// true and produces a diagnostic if there was an error, or returns false
1750/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001751bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001752 CastExpr::CastKind &Kind,
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001753 CXXBaseSpecifierArray &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001754 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001755 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001756 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001757 if (!FromPtrType) {
1758 // This must be a null pointer to member pointer conversion
Douglas Gregorce940492009-09-25 04:25:58 +00001759 assert(From->isNullPointerConstant(Context,
1760 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001761 "Expr must be null pointer constant!");
1762 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001763 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001764 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001765
Ted Kremenek6217b802009-07-29 21:53:49 +00001766 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001767 assert(ToPtrType && "No member pointer cast has a target type "
1768 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001769
Sebastian Redl21593ac2009-01-28 18:33:18 +00001770 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1771 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001772
Sebastian Redl21593ac2009-01-28 18:33:18 +00001773 // FIXME: What about dependent types?
1774 assert(FromClass->isRecordType() && "Pointer into non-class.");
1775 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001776
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001777 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001778 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00001779 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1780 assert(DerivationOkay &&
1781 "Should not have been called if derivation isn't OK.");
1782 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001783
Sebastian Redl21593ac2009-01-28 18:33:18 +00001784 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1785 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001786 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1787 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1788 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1789 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001790 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001791
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001792 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001793 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1794 << FromClass << ToClass << QualType(VBase, 0)
1795 << From->getSourceRange();
1796 return true;
1797 }
1798
John McCall6b2accb2010-02-10 09:31:12 +00001799 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00001800 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1801 Paths.front(),
1802 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00001803
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001804 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001805 BuildBasePathArray(Paths, BasePath);
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001806 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001807 return false;
1808}
1809
Douglas Gregor98cd5992008-10-21 23:43:52 +00001810/// IsQualificationConversion - Determines whether the conversion from
1811/// an rvalue of type FromType to ToType is a qualification conversion
1812/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001813bool
1814Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001815 FromType = Context.getCanonicalType(FromType);
1816 ToType = Context.getCanonicalType(ToType);
1817
1818 // If FromType and ToType are the same type, this is not a
1819 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00001820 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00001821 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001822
Douglas Gregor98cd5992008-10-21 23:43:52 +00001823 // (C++ 4.4p4):
1824 // A conversion can add cv-qualifiers at levels other than the first
1825 // in multi-level pointers, subject to the following rules: [...]
1826 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001827 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00001828 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001829 // Within each iteration of the loop, we check the qualifiers to
1830 // determine if this still looks like a qualification
1831 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001832 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001833 // until there are no more pointers or pointers-to-members left to
1834 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001835 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001836
1837 // -- for every j > 0, if const is in cv 1,j then const is in cv
1838 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001839 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001840 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001841
Douglas Gregor98cd5992008-10-21 23:43:52 +00001842 // -- if the cv 1,j and cv 2,j are different, then const is in
1843 // every cv for 0 < k < j.
1844 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001845 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001846 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001847
Douglas Gregor98cd5992008-10-21 23:43:52 +00001848 // Keep track of whether all prior cv-qualifiers in the "to" type
1849 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00001850 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00001851 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001852 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001853
1854 // We are left with FromType and ToType being the pointee types
1855 // after unwrapping the original FromType and ToType the same number
1856 // of types. If we unwrapped any pointers, and if FromType and
1857 // ToType have the same unqualified type (since we checked
1858 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001859 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00001860}
1861
Douglas Gregor734d9862009-01-30 23:27:23 +00001862/// Determines whether there is a user-defined conversion sequence
1863/// (C++ [over.ics.user]) that converts expression From to the type
1864/// ToType. If such a conversion exists, User will contain the
1865/// user-defined conversion sequence that performs such a conversion
1866/// and this routine will return true. Otherwise, this routine returns
1867/// false and User is unspecified.
1868///
Douglas Gregor734d9862009-01-30 23:27:23 +00001869/// \param AllowExplicit true if the conversion should consider C++0x
1870/// "explicit" conversion functions as well as non-explicit conversion
1871/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor20093b42009-12-09 23:02:17 +00001872OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1873 UserDefinedConversionSequence& User,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001874 OverloadCandidateSet& CandidateSet,
1875 bool AllowExplicit) {
1876 // Whether we will only visit constructors.
1877 bool ConstructorsOnly = false;
1878
1879 // If the type we are conversion to is a class type, enumerate its
1880 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00001881 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001882 // C++ [over.match.ctor]p1:
1883 // When objects of class type are direct-initialized (8.5), or
1884 // copy-initialized from an expression of the same or a
1885 // derived class type (8.5), overload resolution selects the
1886 // constructor. [...] For copy-initialization, the candidate
1887 // functions are all the converting constructors (12.3.1) of
1888 // that class. The argument list is the expression-list within
1889 // the parentheses of the initializer.
1890 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1891 (From->getType()->getAs<RecordType>() &&
1892 IsDerivedFrom(From->getType(), ToType)))
1893 ConstructorsOnly = true;
1894
Douglas Gregor393896f2009-11-05 13:06:35 +00001895 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1896 // We're not going to find any constructors.
1897 } else if (CXXRecordDecl *ToRecordDecl
1898 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001899 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00001900 for (llvm::tie(Con, ConEnd) = LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001901 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00001902 NamedDecl *D = *Con;
1903 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1904
Douglas Gregordec06662009-08-21 18:42:58 +00001905 // Find the constructor (which may be a template).
1906 CXXConstructorDecl *Constructor = 0;
1907 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00001908 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00001909 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00001910 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00001911 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1912 else
John McCall9aa472c2010-03-19 07:35:19 +00001913 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001914
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00001915 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00001916 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001917 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00001918 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001919 /*ExplicitArgs*/ 0,
John McCalld5532b62009-11-23 01:53:49 +00001920 &From, 1, CandidateSet,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001921 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00001922 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001923 // Allow one user-defined conversion when user specifies a
1924 // From->ToType conversion via an static cast (c-style, etc).
John McCall9aa472c2010-03-19 07:35:19 +00001925 AddOverloadCandidate(Constructor, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001926 &From, 1, CandidateSet,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001927 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00001928 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001929 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001930 }
1931 }
1932
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001933 // Enumerate conversion functions, if we're allowed to.
1934 if (ConstructorsOnly) {
Mike Stump1eb44332009-09-09 15:08:12 +00001935 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001936 PDiag(0) << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00001937 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00001938 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001939 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001940 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001941 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1942 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00001943 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00001944 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001945 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001946 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00001947 DeclAccessPair FoundDecl = I.getPair();
1948 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00001949 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1950 if (isa<UsingShadowDecl>(D))
1951 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1952
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001953 CXXConversionDecl *Conv;
1954 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00001955 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1956 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001957 else
John McCall32daa422010-03-31 01:36:47 +00001958 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001959
1960 if (AllowExplicit || !Conv->isExplicit()) {
1961 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00001962 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001963 ActingContext, From, ToType,
1964 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001965 else
John McCall9aa472c2010-03-19 07:35:19 +00001966 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCall86820f52010-01-26 01:37:31 +00001967 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001968 }
1969 }
1970 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001971 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001972
1973 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001974 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001975 case OR_Success:
1976 // Record the standard conversion we used and the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00001977 if (CXXConstructorDecl *Constructor
Douglas Gregor60d62c22008-10-31 16:23:19 +00001978 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1979 // C++ [over.ics.user]p1:
1980 // If the user-defined conversion is specified by a
1981 // constructor (12.3.1), the initial standard conversion
1982 // sequence converts the source type to the type required by
1983 // the argument of the constructor.
1984 //
Douglas Gregor60d62c22008-10-31 16:23:19 +00001985 QualType ThisType = Constructor->getThisType(Context);
John McCall1d318332010-01-12 00:44:57 +00001986 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian966256a2009-11-06 00:23:08 +00001987 User.EllipsisConversion = true;
1988 else {
1989 User.Before = Best->Conversions[0].Standard;
1990 User.EllipsisConversion = false;
1991 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001992 User.ConversionFunction = Constructor;
1993 User.After.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +00001994 User.After.setFromType(
1995 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregorad323a82010-01-27 03:51:04 +00001996 User.After.setAllToTypes(ToType);
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00001997 return OR_Success;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001998 } else if (CXXConversionDecl *Conversion
1999 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2000 // C++ [over.ics.user]p1:
2001 //
2002 // [...] If the user-defined conversion is specified by a
2003 // conversion function (12.3.2), the initial standard
2004 // conversion sequence converts the source type to the
2005 // implicit object parameter of the conversion function.
2006 User.Before = Best->Conversions[0].Standard;
2007 User.ConversionFunction = Conversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002008 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002009
2010 // C++ [over.ics.user]p2:
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002011 // The second standard conversion sequence converts the
2012 // result of the user-defined conversion to the target type
2013 // for the sequence. Since an implicit conversion sequence
2014 // is an initialization, the special rules for
2015 // initialization by user-defined conversion apply when
2016 // selecting the best user-defined conversion for a
2017 // user-defined conversion sequence (see 13.3.3 and
2018 // 13.3.3.1).
2019 User.After = Best->FinalConversion;
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002020 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002021 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002022 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002023 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002024 }
Mike Stump1eb44332009-09-09 15:08:12 +00002025
Douglas Gregor60d62c22008-10-31 16:23:19 +00002026 case OR_No_Viable_Function:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002027 return OR_No_Viable_Function;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002028 case OR_Deleted:
Douglas Gregor60d62c22008-10-31 16:23:19 +00002029 // No conversion here! We're done.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002030 return OR_Deleted;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002031
2032 case OR_Ambiguous:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002033 return OR_Ambiguous;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002034 }
2035
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002036 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002037}
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002038
2039bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002040Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002041 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00002042 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002043 OverloadingResult OvResult =
2044 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002045 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002046 if (OvResult == OR_Ambiguous)
2047 Diag(From->getSourceRange().getBegin(),
2048 diag::err_typecheck_ambiguous_condition)
2049 << From->getType() << ToType << From->getSourceRange();
2050 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2051 Diag(From->getSourceRange().getBegin(),
2052 diag::err_typecheck_nonviable_condition)
2053 << From->getType() << ToType << From->getSourceRange();
2054 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002055 return false;
John McCallcbce6062010-01-12 07:18:19 +00002056 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002057 return true;
2058}
Douglas Gregor60d62c22008-10-31 16:23:19 +00002059
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002060/// CompareImplicitConversionSequences - Compare two implicit
2061/// conversion sequences to determine whether one is better than the
2062/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump1eb44332009-09-09 15:08:12 +00002063ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002064Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
2065 const ImplicitConversionSequence& ICS2)
2066{
2067 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2068 // conversion sequences (as defined in 13.3.3.1)
2069 // -- a standard conversion sequence (13.3.3.1.1) is a better
2070 // conversion sequence than a user-defined conversion sequence or
2071 // an ellipsis conversion sequence, and
2072 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2073 // conversion sequence than an ellipsis conversion sequence
2074 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002075 //
John McCall1d318332010-01-12 00:44:57 +00002076 // C++0x [over.best.ics]p10:
2077 // For the purpose of ranking implicit conversion sequences as
2078 // described in 13.3.3.2, the ambiguous conversion sequence is
2079 // treated as a user-defined sequence that is indistinguishable
2080 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002081 if (ICS1.getKindRank() < ICS2.getKindRank())
2082 return ImplicitConversionSequence::Better;
2083 else if (ICS2.getKindRank() < ICS1.getKindRank())
2084 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002085
Benjamin Kramerb6eee072010-04-18 12:05:54 +00002086 // The following checks require both conversion sequences to be of
2087 // the same kind.
2088 if (ICS1.getKind() != ICS2.getKind())
2089 return ImplicitConversionSequence::Indistinguishable;
2090
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002091 // Two implicit conversion sequences of the same form are
2092 // indistinguishable conversion sequences unless one of the
2093 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00002094 if (ICS1.isStandard())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002095 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00002096 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002097 // User-defined conversion sequence U1 is a better conversion
2098 // sequence than another user-defined conversion sequence U2 if
2099 // they contain the same user-defined conversion function or
2100 // constructor and if the second standard conversion sequence of
2101 // U1 is better than the second standard conversion sequence of
2102 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002103 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002104 ICS2.UserDefined.ConversionFunction)
2105 return CompareStandardConversionSequences(ICS1.UserDefined.After,
2106 ICS2.UserDefined.After);
2107 }
2108
2109 return ImplicitConversionSequence::Indistinguishable;
2110}
2111
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002112static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2113 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2114 Qualifiers Quals;
2115 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2116 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2117 }
2118
2119 return Context.hasSameUnqualifiedType(T1, T2);
2120}
2121
Douglas Gregorad323a82010-01-27 03:51:04 +00002122// Per 13.3.3.2p3, compare the given standard conversion sequences to
2123// determine if one is a proper subset of the other.
2124static ImplicitConversionSequence::CompareKind
2125compareStandardConversionSubsets(ASTContext &Context,
2126 const StandardConversionSequence& SCS1,
2127 const StandardConversionSequence& SCS2) {
2128 ImplicitConversionSequence::CompareKind Result
2129 = ImplicitConversionSequence::Indistinguishable;
2130
Douglas Gregorae65f4b2010-05-23 22:10:15 +00002131 // the identity conversion sequence is considered to be a subsequence of
2132 // any non-identity conversion sequence
2133 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2134 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2135 return ImplicitConversionSequence::Better;
2136 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2137 return ImplicitConversionSequence::Worse;
2138 }
2139
Douglas Gregorad323a82010-01-27 03:51:04 +00002140 if (SCS1.Second != SCS2.Second) {
2141 if (SCS1.Second == ICK_Identity)
2142 Result = ImplicitConversionSequence::Better;
2143 else if (SCS2.Second == ICK_Identity)
2144 Result = ImplicitConversionSequence::Worse;
2145 else
2146 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002147 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00002148 return ImplicitConversionSequence::Indistinguishable;
2149
2150 if (SCS1.Third == SCS2.Third) {
2151 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2152 : ImplicitConversionSequence::Indistinguishable;
2153 }
2154
2155 if (SCS1.Third == ICK_Identity)
2156 return Result == ImplicitConversionSequence::Worse
2157 ? ImplicitConversionSequence::Indistinguishable
2158 : ImplicitConversionSequence::Better;
2159
2160 if (SCS2.Third == ICK_Identity)
2161 return Result == ImplicitConversionSequence::Better
2162 ? ImplicitConversionSequence::Indistinguishable
2163 : ImplicitConversionSequence::Worse;
2164
2165 return ImplicitConversionSequence::Indistinguishable;
2166}
2167
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002168/// CompareStandardConversionSequences - Compare two standard
2169/// conversion sequences to determine whether one is better than the
2170/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002171ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002172Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
2173 const StandardConversionSequence& SCS2)
2174{
2175 // Standard conversion sequence S1 is a better conversion sequence
2176 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2177
2178 // -- S1 is a proper subsequence of S2 (comparing the conversion
2179 // sequences in the canonical form defined by 13.3.3.1.1,
2180 // excluding any Lvalue Transformation; the identity conversion
2181 // sequence is considered to be a subsequence of any
2182 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00002183 if (ImplicitConversionSequence::CompareKind CK
2184 = compareStandardConversionSubsets(Context, SCS1, SCS2))
2185 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002186
2187 // -- the rank of S1 is better than the rank of S2 (by the rules
2188 // defined below), or, if not that,
2189 ImplicitConversionRank Rank1 = SCS1.getRank();
2190 ImplicitConversionRank Rank2 = SCS2.getRank();
2191 if (Rank1 < Rank2)
2192 return ImplicitConversionSequence::Better;
2193 else if (Rank2 < Rank1)
2194 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002195
Douglas Gregor57373262008-10-22 14:17:15 +00002196 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2197 // are indistinguishable unless one of the following rules
2198 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00002199
Douglas Gregor57373262008-10-22 14:17:15 +00002200 // A conversion that is not a conversion of a pointer, or
2201 // pointer to member, to bool is better than another conversion
2202 // that is such a conversion.
2203 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2204 return SCS2.isPointerConversionToBool()
2205 ? ImplicitConversionSequence::Better
2206 : ImplicitConversionSequence::Worse;
2207
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002208 // C++ [over.ics.rank]p4b2:
2209 //
2210 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002211 // conversion of B* to A* is better than conversion of B* to
2212 // void*, and conversion of A* to void* is better than conversion
2213 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00002214 bool SCS1ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002215 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002216 bool SCS2ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002217 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002218 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2219 // Exactly one of the conversion sequences is a conversion to
2220 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002221 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2222 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002223 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2224 // Neither conversion sequence converts to a void pointer; compare
2225 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002226 if (ImplicitConversionSequence::CompareKind DerivedCK
2227 = CompareDerivedToBaseConversions(SCS1, SCS2))
2228 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002229 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2230 // Both conversion sequences are conversions to void
2231 // pointers. Compare the source types to determine if there's an
2232 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00002233 QualType FromType1 = SCS1.getFromType();
2234 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002235
2236 // Adjust the types we're converting from via the array-to-pointer
2237 // conversion, if we need to.
2238 if (SCS1.First == ICK_Array_To_Pointer)
2239 FromType1 = Context.getArrayDecayedType(FromType1);
2240 if (SCS2.First == ICK_Array_To_Pointer)
2241 FromType2 = Context.getArrayDecayedType(FromType2);
2242
Douglas Gregor01919692009-12-13 21:37:05 +00002243 QualType FromPointee1
2244 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2245 QualType FromPointee2
2246 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002247
Douglas Gregor01919692009-12-13 21:37:05 +00002248 if (IsDerivedFrom(FromPointee2, FromPointee1))
2249 return ImplicitConversionSequence::Better;
2250 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2251 return ImplicitConversionSequence::Worse;
2252
2253 // Objective-C++: If one interface is more specific than the
2254 // other, it is the better one.
John McCallc12c5bb2010-05-15 11:32:37 +00002255 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2256 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor01919692009-12-13 21:37:05 +00002257 if (FromIface1 && FromIface1) {
2258 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2259 return ImplicitConversionSequence::Better;
2260 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2261 return ImplicitConversionSequence::Worse;
2262 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002263 }
Douglas Gregor57373262008-10-22 14:17:15 +00002264
2265 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2266 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00002267 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00002268 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002269 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00002270
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002271 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002272 // C++0x [over.ics.rank]p3b4:
2273 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2274 // implicit object parameter of a non-static member function declared
2275 // without a ref-qualifier, and S1 binds an rvalue reference to an
2276 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00002277 // FIXME: We don't know if we're dealing with the implicit object parameter,
2278 // or if the member function in this case has a ref qualifier.
2279 // (Of course, we don't have ref qualifiers yet.)
2280 if (SCS1.RRefBinding != SCS2.RRefBinding)
2281 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2282 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002283
2284 // C++ [over.ics.rank]p3b4:
2285 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2286 // which the references refer are the same type except for
2287 // top-level cv-qualifiers, and the type to which the reference
2288 // initialized by S2 refers is more cv-qualified than the type
2289 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00002290 QualType T1 = SCS1.getToType(2);
2291 QualType T2 = SCS2.getToType(2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002292 T1 = Context.getCanonicalType(T1);
2293 T2 = Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002294 Qualifiers T1Quals, T2Quals;
2295 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2296 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2297 if (UnqualT1 == UnqualT2) {
2298 // If the type is an array type, promote the element qualifiers to the type
2299 // for comparison.
2300 if (isa<ArrayType>(T1) && T1Quals)
2301 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2302 if (isa<ArrayType>(T2) && T2Quals)
2303 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002304 if (T2.isMoreQualifiedThan(T1))
2305 return ImplicitConversionSequence::Better;
2306 else if (T1.isMoreQualifiedThan(T2))
2307 return ImplicitConversionSequence::Worse;
2308 }
2309 }
Douglas Gregor57373262008-10-22 14:17:15 +00002310
2311 return ImplicitConversionSequence::Indistinguishable;
2312}
2313
2314/// CompareQualificationConversions - Compares two standard conversion
2315/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00002316/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2317ImplicitConversionSequence::CompareKind
Douglas Gregor57373262008-10-22 14:17:15 +00002318Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump1eb44332009-09-09 15:08:12 +00002319 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00002320 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00002321 // -- S1 and S2 differ only in their qualification conversion and
2322 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2323 // cv-qualification signature of type T1 is a proper subset of
2324 // the cv-qualification signature of type T2, and S1 is not the
2325 // deprecated string literal array-to-pointer conversion (4.2).
2326 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2327 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2328 return ImplicitConversionSequence::Indistinguishable;
2329
2330 // FIXME: the example in the standard doesn't use a qualification
2331 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00002332 QualType T1 = SCS1.getToType(2);
2333 QualType T2 = SCS2.getToType(2);
Douglas Gregor57373262008-10-22 14:17:15 +00002334 T1 = Context.getCanonicalType(T1);
2335 T2 = Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002336 Qualifiers T1Quals, T2Quals;
2337 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2338 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00002339
2340 // If the types are the same, we won't learn anything by unwrapped
2341 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00002342 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00002343 return ImplicitConversionSequence::Indistinguishable;
2344
Chandler Carruth28e318c2009-12-29 07:16:59 +00002345 // If the type is an array type, promote the element qualifiers to the type
2346 // for comparison.
2347 if (isa<ArrayType>(T1) && T1Quals)
2348 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2349 if (isa<ArrayType>(T2) && T2Quals)
2350 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2351
Mike Stump1eb44332009-09-09 15:08:12 +00002352 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00002353 = ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002354 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00002355 // Within each iteration of the loop, we check the qualifiers to
2356 // determine if this still looks like a qualification
2357 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002358 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00002359 // until there are no more pointers or pointers-to-members left
2360 // to unwrap. This essentially mimics what
2361 // IsQualificationConversion does, but here we're checking for a
2362 // strict subset of qualifiers.
2363 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2364 // The qualifiers are the same, so this doesn't tell us anything
2365 // about how the sequences rank.
2366 ;
2367 else if (T2.isMoreQualifiedThan(T1)) {
2368 // T1 has fewer qualifiers, so it could be the better sequence.
2369 if (Result == ImplicitConversionSequence::Worse)
2370 // Neither has qualifiers that are a subset of the other's
2371 // qualifiers.
2372 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002373
Douglas Gregor57373262008-10-22 14:17:15 +00002374 Result = ImplicitConversionSequence::Better;
2375 } else if (T1.isMoreQualifiedThan(T2)) {
2376 // T2 has fewer qualifiers, so it could be the better sequence.
2377 if (Result == ImplicitConversionSequence::Better)
2378 // Neither has qualifiers that are a subset of the other's
2379 // qualifiers.
2380 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002381
Douglas Gregor57373262008-10-22 14:17:15 +00002382 Result = ImplicitConversionSequence::Worse;
2383 } else {
2384 // Qualifiers are disjoint.
2385 return ImplicitConversionSequence::Indistinguishable;
2386 }
2387
2388 // If the types after this point are equivalent, we're done.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002389 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00002390 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002391 }
2392
Douglas Gregor57373262008-10-22 14:17:15 +00002393 // Check that the winning standard conversion sequence isn't using
2394 // the deprecated string literal array to pointer conversion.
2395 switch (Result) {
2396 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00002397 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002398 Result = ImplicitConversionSequence::Indistinguishable;
2399 break;
2400
2401 case ImplicitConversionSequence::Indistinguishable:
2402 break;
2403
2404 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00002405 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002406 Result = ImplicitConversionSequence::Indistinguishable;
2407 break;
2408 }
2409
2410 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002411}
2412
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002413/// CompareDerivedToBaseConversions - Compares two standard conversion
2414/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00002415/// various kinds of derived-to-base conversions (C++
2416/// [over.ics.rank]p4b3). As part of these checks, we also look at
2417/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002418ImplicitConversionSequence::CompareKind
2419Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2420 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00002421 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002422 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00002423 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002424 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002425
2426 // Adjust the types we're converting from via the array-to-pointer
2427 // conversion, if we need to.
2428 if (SCS1.First == ICK_Array_To_Pointer)
2429 FromType1 = Context.getArrayDecayedType(FromType1);
2430 if (SCS2.First == ICK_Array_To_Pointer)
2431 FromType2 = Context.getArrayDecayedType(FromType2);
2432
2433 // Canonicalize all of the types.
2434 FromType1 = Context.getCanonicalType(FromType1);
2435 ToType1 = Context.getCanonicalType(ToType1);
2436 FromType2 = Context.getCanonicalType(FromType2);
2437 ToType2 = Context.getCanonicalType(ToType2);
2438
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002439 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002440 //
2441 // If class B is derived directly or indirectly from class A and
2442 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002443 //
2444 // For Objective-C, we let A, B, and C also be Objective-C
2445 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002446
2447 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00002448 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00002449 SCS2.Second == ICK_Pointer_Conversion &&
2450 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2451 FromType1->isPointerType() && FromType2->isPointerType() &&
2452 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002453 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002454 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002455 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002456 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002457 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002458 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002459 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002460 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002461
John McCallc12c5bb2010-05-15 11:32:37 +00002462 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2463 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2464 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2465 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002466
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002467 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002468 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2469 if (IsDerivedFrom(ToPointee1, ToPointee2))
2470 return ImplicitConversionSequence::Better;
2471 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2472 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00002473
2474 if (ToIface1 && ToIface2) {
2475 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2476 return ImplicitConversionSequence::Better;
2477 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2478 return ImplicitConversionSequence::Worse;
2479 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002480 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002481
2482 // -- conversion of B* to A* is better than conversion of C* to A*,
2483 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2484 if (IsDerivedFrom(FromPointee2, FromPointee1))
2485 return ImplicitConversionSequence::Better;
2486 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2487 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00002488
Douglas Gregorcb7de522008-11-26 23:31:11 +00002489 if (FromIface1 && FromIface2) {
2490 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2491 return ImplicitConversionSequence::Better;
2492 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2493 return ImplicitConversionSequence::Worse;
2494 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002495 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002496 }
2497
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002498 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002499 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2500 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2501 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2502 const MemberPointerType * FromMemPointer1 =
2503 FromType1->getAs<MemberPointerType>();
2504 const MemberPointerType * ToMemPointer1 =
2505 ToType1->getAs<MemberPointerType>();
2506 const MemberPointerType * FromMemPointer2 =
2507 FromType2->getAs<MemberPointerType>();
2508 const MemberPointerType * ToMemPointer2 =
2509 ToType2->getAs<MemberPointerType>();
2510 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2511 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2512 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2513 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2514 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2515 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2516 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2517 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002518 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002519 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2520 if (IsDerivedFrom(ToPointee1, ToPointee2))
2521 return ImplicitConversionSequence::Worse;
2522 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2523 return ImplicitConversionSequence::Better;
2524 }
2525 // conversion of B::* to C::* is better than conversion of A::* to C::*
2526 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2527 if (IsDerivedFrom(FromPointee1, FromPointee2))
2528 return ImplicitConversionSequence::Better;
2529 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2530 return ImplicitConversionSequence::Worse;
2531 }
2532 }
2533
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002534 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002535 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00002536 // -- binding of an expression of type C to a reference of type
2537 // B& is better than binding an expression of type C to a
2538 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002539 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2540 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002541 if (IsDerivedFrom(ToType1, ToType2))
2542 return ImplicitConversionSequence::Better;
2543 else if (IsDerivedFrom(ToType2, ToType1))
2544 return ImplicitConversionSequence::Worse;
2545 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002546
Douglas Gregor225c41e2008-11-03 19:09:14 +00002547 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00002548 // -- binding of an expression of type B to a reference of type
2549 // A& is better than binding an expression of type C to a
2550 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002551 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2552 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002553 if (IsDerivedFrom(FromType2, FromType1))
2554 return ImplicitConversionSequence::Better;
2555 else if (IsDerivedFrom(FromType1, FromType2))
2556 return ImplicitConversionSequence::Worse;
2557 }
2558 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002559
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002560 return ImplicitConversionSequence::Indistinguishable;
2561}
2562
Douglas Gregorabe183d2010-04-13 16:31:36 +00002563/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2564/// determine whether they are reference-related,
2565/// reference-compatible, reference-compatible with added
2566/// qualification, or incompatible, for use in C++ initialization by
2567/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2568/// type, and the first type (T1) is the pointee type of the reference
2569/// type being initialized.
2570Sema::ReferenceCompareResult
2571Sema::CompareReferenceRelationship(SourceLocation Loc,
2572 QualType OrigT1, QualType OrigT2,
2573 bool& DerivedToBase) {
2574 assert(!OrigT1->isReferenceType() &&
2575 "T1 must be the pointee type of the reference type");
2576 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2577
2578 QualType T1 = Context.getCanonicalType(OrigT1);
2579 QualType T2 = Context.getCanonicalType(OrigT2);
2580 Qualifiers T1Quals, T2Quals;
2581 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2582 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2583
2584 // C++ [dcl.init.ref]p4:
2585 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2586 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2587 // T1 is a base class of T2.
2588 if (UnqualT1 == UnqualT2)
2589 DerivedToBase = false;
Douglas Gregor6b6d01f2010-05-07 19:42:26 +00002590 else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00002591 IsDerivedFrom(UnqualT2, UnqualT1))
2592 DerivedToBase = true;
2593 else
2594 return Ref_Incompatible;
2595
2596 // At this point, we know that T1 and T2 are reference-related (at
2597 // least).
2598
2599 // If the type is an array type, promote the element qualifiers to the type
2600 // for comparison.
2601 if (isa<ArrayType>(T1) && T1Quals)
2602 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2603 if (isa<ArrayType>(T2) && T2Quals)
2604 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2605
2606 // C++ [dcl.init.ref]p4:
2607 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2608 // reference-related to T2 and cv1 is the same cv-qualification
2609 // as, or greater cv-qualification than, cv2. For purposes of
2610 // overload resolution, cases for which cv1 is greater
2611 // cv-qualification than cv2 are identified as
2612 // reference-compatible with added qualification (see 13.3.3.2).
2613 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2614 return Ref_Compatible;
2615 else if (T1.isMoreQualifiedThan(T2))
2616 return Ref_Compatible_With_Added_Qualification;
2617 else
2618 return Ref_Related;
2619}
2620
Sebastian Redl4680bf22010-06-30 18:13:39 +00002621/// \brief Look for a user-defined conversion to an lvalue reference-compatible
2622/// with DeclType. Return true if something definite is found.
2623static bool
2624FindConversionToLValue(Sema &S, ImplicitConversionSequence &ICS,
2625 QualType DeclType, SourceLocation DeclLoc,
2626 Expr *Init, QualType T2, bool AllowExplicit) {
2627 assert(T2->isRecordType() && "Can only find conversions of record types.");
2628 CXXRecordDecl *T2RecordDecl
2629 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2630
2631 OverloadCandidateSet CandidateSet(DeclLoc);
2632 const UnresolvedSetImpl *Conversions
2633 = T2RecordDecl->getVisibleConversionFunctions();
2634 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2635 E = Conversions->end(); I != E; ++I) {
2636 NamedDecl *D = *I;
2637 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2638 if (isa<UsingShadowDecl>(D))
2639 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2640
2641 FunctionTemplateDecl *ConvTemplate
2642 = dyn_cast<FunctionTemplateDecl>(D);
2643 CXXConversionDecl *Conv;
2644 if (ConvTemplate)
2645 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2646 else
2647 Conv = cast<CXXConversionDecl>(D);
2648
2649 // If the conversion function doesn't return a reference type,
2650 // it can't be considered for this conversion. An rvalue reference
2651 // is only acceptable if its referencee is a function type.
2652 const ReferenceType *RefType =
2653 Conv->getConversionType()->getAs<ReferenceType>();
2654 if (RefType && (RefType->isLValueReferenceType() ||
2655 RefType->getPointeeType()->isFunctionType()) &&
2656 (AllowExplicit || !Conv->isExplicit())) {
2657 if (ConvTemplate)
2658 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2659 Init, DeclType, CandidateSet);
2660 else
2661 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2662 DeclType, CandidateSet);
2663 }
2664 }
2665
2666 OverloadCandidateSet::iterator Best;
2667 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2668 case OR_Success:
2669 // C++ [over.ics.ref]p1:
2670 //
2671 // [...] If the parameter binds directly to the result of
2672 // applying a conversion function to the argument
2673 // expression, the implicit conversion sequence is a
2674 // user-defined conversion sequence (13.3.3.1.2), with the
2675 // second standard conversion sequence either an identity
2676 // conversion or, if the conversion function returns an
2677 // entity of a type that is a derived class of the parameter
2678 // type, a derived-to-base Conversion.
2679 if (!Best->FinalConversion.DirectBinding)
2680 return false;
2681
2682 ICS.setUserDefined();
2683 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2684 ICS.UserDefined.After = Best->FinalConversion;
2685 ICS.UserDefined.ConversionFunction = Best->Function;
2686 ICS.UserDefined.EllipsisConversion = false;
2687 assert(ICS.UserDefined.After.ReferenceBinding &&
2688 ICS.UserDefined.After.DirectBinding &&
2689 "Expected a direct reference binding!");
2690 return true;
2691
2692 case OR_Ambiguous:
2693 ICS.setAmbiguous();
2694 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2695 Cand != CandidateSet.end(); ++Cand)
2696 if (Cand->Viable)
2697 ICS.Ambiguous.addConversion(Cand->Function);
2698 return true;
2699
2700 case OR_No_Viable_Function:
2701 case OR_Deleted:
2702 // There was no suitable conversion, or we found a deleted
2703 // conversion; continue with other checks.
2704 return false;
2705 }
Eric Christopher1c3d5022010-06-30 18:36:32 +00002706
2707 return false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002708}
2709
Douglas Gregorabe183d2010-04-13 16:31:36 +00002710/// \brief Compute an implicit conversion sequence for reference
2711/// initialization.
2712static ImplicitConversionSequence
2713TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2714 SourceLocation DeclLoc,
2715 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00002716 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002717 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2718
2719 // Most paths end in a failed conversion.
2720 ImplicitConversionSequence ICS;
2721 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2722
2723 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2724 QualType T2 = Init->getType();
2725
2726 // If the initializer is the address of an overloaded function, try
2727 // to resolve the overloaded function. If all goes well, T2 is the
2728 // type of the resulting function.
2729 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2730 DeclAccessPair Found;
2731 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2732 false, Found))
2733 T2 = Fn->getType();
2734 }
2735
2736 // Compute some basic properties of the types and the initializer.
2737 bool isRValRef = DeclType->isRValueReferenceType();
2738 bool DerivedToBase = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002739 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002740 Sema::ReferenceCompareResult RefRelationship
2741 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
2742
Douglas Gregorabe183d2010-04-13 16:31:36 +00002743
Sebastian Redl4680bf22010-06-30 18:13:39 +00002744 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00002745 // A reference to type "cv1 T1" is initialized by an expression
2746 // of type "cv2 T2" as follows:
2747
Sebastian Redl4680bf22010-06-30 18:13:39 +00002748 // -- If reference is an lvalue reference and the initializer expression
2749 // The next bullet point (T1 is a function) is pretty much equivalent to this
2750 // one, so it's handled here.
2751 if (!isRValRef || T1->isFunctionType()) {
2752 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2753 // reference-compatible with "cv2 T2," or
2754 //
2755 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2756 if (InitCategory.isLValue() &&
2757 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002758 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00002759 // When a parameter of reference type binds directly (8.5.3)
2760 // to an argument expression, the implicit conversion sequence
2761 // is the identity conversion, unless the argument expression
2762 // has a type that is a derived class of the parameter type,
2763 // in which case the implicit conversion sequence is a
2764 // derived-to-base Conversion (13.3.3.1).
2765 ICS.setStandard();
2766 ICS.Standard.First = ICK_Identity;
2767 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2768 ICS.Standard.Third = ICK_Identity;
2769 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2770 ICS.Standard.setToType(0, T2);
2771 ICS.Standard.setToType(1, T1);
2772 ICS.Standard.setToType(2, T1);
2773 ICS.Standard.ReferenceBinding = true;
2774 ICS.Standard.DirectBinding = true;
2775 ICS.Standard.RRefBinding = isRValRef;
2776 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002777
Sebastian Redl4680bf22010-06-30 18:13:39 +00002778 // Nothing more to do: the inaccessibility/ambiguity check for
2779 // derived-to-base conversions is suppressed when we're
2780 // computing the implicit conversion sequence (C++
2781 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00002782 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002783 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00002784
Sebastian Redl4680bf22010-06-30 18:13:39 +00002785 // -- has a class type (i.e., T2 is a class type), where T1 is
2786 // not reference-related to T2, and can be implicitly
2787 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2788 // is reference-compatible with "cv3 T3" 92) (this
2789 // conversion is selected by enumerating the applicable
2790 // conversion functions (13.3.1.6) and choosing the best
2791 // one through overload resolution (13.3)),
2792 if (!SuppressUserConversions && T2->isRecordType() &&
2793 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2794 RefRelationship == Sema::Ref_Incompatible) {
2795 if (FindConversionToLValue(S, ICS, DeclType, DeclLoc,
2796 Init, T2, AllowExplicit))
2797 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002798 }
2799 }
2800
Sebastian Redl4680bf22010-06-30 18:13:39 +00002801 // -- Otherwise, the reference shall be an lvalue reference to a
2802 // non-volatile const type (i.e., cv1 shall be const), or the reference
2803 // shall be an rvalue reference and the initializer expression shall be
2804 // an rvalue or have a function type.
Douglas Gregor66821b52010-04-18 09:22:00 +00002805 //
2806 // We actually handle one oddity of C++ [over.ics.ref] at this
2807 // point, which is that, due to p2 (which short-circuits reference
2808 // binding by only attempting a simple conversion for non-direct
2809 // bindings) and p3's strange wording, we allow a const volatile
2810 // reference to bind to an rvalue. Hence the check for the presence
2811 // of "const" rather than checking for "const" being the only
2812 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00002813 // This is also the point where rvalue references and lvalue inits no longer
2814 // go together.
2815 if ((!isRValRef && !T1.isConstQualified()) ||
2816 (isRValRef && InitCategory.isLValue()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00002817 return ICS;
2818
Sebastian Redl4680bf22010-06-30 18:13:39 +00002819 // -- If T1 is a function type, then
2820 // -- if T2 is the same type as T1, the reference is bound to the
2821 // initializer expression lvalue;
2822 // -- if T2 is a class type and the initializer expression can be
2823 // implicitly converted to an lvalue of type T1 [...], the
2824 // reference is bound to the function lvalue that is the result
2825 // of the conversion;
2826 // This is the same as for the lvalue case above, so it was handled there.
2827 // -- otherwise, the program is ill-formed.
2828 // This is the one difference to the lvalue case.
2829 if (T1->isFunctionType())
2830 return ICS;
2831
2832 // -- Otherwise, if T2 is a class type and
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002833 // -- the initializer expression is an rvalue and "cv1 T1"
2834 // is reference-compatible with "cv2 T2," or
Douglas Gregorabe183d2010-04-13 16:31:36 +00002835 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002836 // -- T1 is not reference-related to T2 and the initializer
2837 // expression can be implicitly converted to an rvalue
2838 // of type "cv3 T3" (this conversion is selected by
2839 // enumerating the applicable conversion functions
2840 // (13.3.1.6) and choosing the best one through overload
2841 // resolution (13.3)),
Douglas Gregorabe183d2010-04-13 16:31:36 +00002842 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002843 // then the reference is bound to the initializer
2844 // expression rvalue in the first case and to the object
2845 // that is the result of the conversion in the second case
2846 // (or, in either case, to the appropriate base class
2847 // subobject of the object).
Douglas Gregorabe183d2010-04-13 16:31:36 +00002848 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002849 // We're only checking the first case here, which is a direct
2850 // binding in C++0x but not in C++03.
Sebastian Redl4680bf22010-06-30 18:13:39 +00002851 if (InitCategory.isRValue() && T2->isRecordType() &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00002852 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2853 ICS.setStandard();
2854 ICS.Standard.First = ICK_Identity;
2855 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2856 ICS.Standard.Third = ICK_Identity;
2857 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2858 ICS.Standard.setToType(0, T2);
2859 ICS.Standard.setToType(1, T1);
2860 ICS.Standard.setToType(2, T1);
2861 ICS.Standard.ReferenceBinding = true;
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002862 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002863 ICS.Standard.RRefBinding = isRValRef;
2864 ICS.Standard.CopyConstructor = 0;
2865 return ICS;
2866 }
2867
2868 // -- Otherwise, a temporary of type "cv1 T1" is created and
2869 // initialized from the initializer expression using the
2870 // rules for a non-reference copy initialization (8.5). The
2871 // reference is then bound to the temporary. If T1 is
2872 // reference-related to T2, cv1 must be the same
2873 // cv-qualification as, or greater cv-qualification than,
2874 // cv2; otherwise, the program is ill-formed.
2875 if (RefRelationship == Sema::Ref_Related) {
2876 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2877 // we would be reference-compatible or reference-compatible with
2878 // added qualification. But that wasn't the case, so the reference
2879 // initialization fails.
2880 return ICS;
2881 }
2882
2883 // If at least one of the types is a class type, the types are not
2884 // related, and we aren't allowed any user conversions, the
2885 // reference binding fails. This case is important for breaking
2886 // recursion, since TryImplicitConversion below will attempt to
2887 // create a temporary through the use of a copy constructor.
2888 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2889 (T1->isRecordType() || T2->isRecordType()))
2890 return ICS;
2891
2892 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00002893 // When a parameter of reference type is not bound directly to
2894 // an argument expression, the conversion sequence is the one
2895 // required to convert the argument expression to the
2896 // underlying type of the reference according to
2897 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2898 // to copy-initializing a temporary of the underlying type with
2899 // the argument expression. Any difference in top-level
2900 // cv-qualification is subsumed by the initialization itself
2901 // and does not constitute a conversion.
2902 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2903 /*AllowExplicit=*/false,
Douglas Gregorabe183d2010-04-13 16:31:36 +00002904 /*InOverloadResolution=*/false);
2905
2906 // Of course, that's still a reference binding.
2907 if (ICS.isStandard()) {
2908 ICS.Standard.ReferenceBinding = true;
2909 ICS.Standard.RRefBinding = isRValRef;
2910 } else if (ICS.isUserDefined()) {
2911 ICS.UserDefined.After.ReferenceBinding = true;
2912 ICS.UserDefined.After.RRefBinding = isRValRef;
2913 }
2914 return ICS;
2915}
2916
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002917/// TryCopyInitialization - Try to copy-initialize a value of type
2918/// ToType from the expression From. Return the implicit conversion
2919/// sequence required to pass this argument, which may be a bad
2920/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00002921/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00002922/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00002923static ImplicitConversionSequence
2924TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregorb7f9e6a2010-04-16 17:53:55 +00002925 bool SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00002926 bool InOverloadResolution) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002927 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00002928 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00002929 /*FIXME:*/From->getLocStart(),
2930 SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00002931 /*AllowExplicit=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002932
Douglas Gregor74eb6582010-04-16 17:51:22 +00002933 return S.TryImplicitConversion(From, ToType,
2934 SuppressUserConversions,
2935 /*AllowExplicit=*/false,
Douglas Gregor74eb6582010-04-16 17:51:22 +00002936 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002937}
2938
Douglas Gregor96176b32008-11-18 23:14:02 +00002939/// TryObjectArgumentInitialization - Try to initialize the object
2940/// parameter of the given member function (@c Method) from the
2941/// expression @p From.
2942ImplicitConversionSequence
John McCall651f3ee2010-01-14 03:28:57 +00002943Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall701c89e2009-12-03 04:06:58 +00002944 CXXMethodDecl *Method,
2945 CXXRecordDecl *ActingContext) {
2946 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002947 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2948 // const volatile object.
2949 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2950 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2951 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00002952
2953 // Set up the conversion sequence as a "bad" conversion, to allow us
2954 // to exit early.
2955 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00002956
2957 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00002958 QualType FromType = OrigFromType;
Ted Kremenek6217b802009-07-29 21:53:49 +00002959 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00002960 FromType = PT->getPointeeType();
2961
2962 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00002963
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00002964 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor96176b32008-11-18 23:14:02 +00002965 // where X is the class of which the function is a member
2966 // (C++ [over.match.funcs]p4). However, when finding an implicit
2967 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00002968 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00002969 // (C++ [over.match.funcs]p5). We perform a simplified version of
2970 // reference binding here, that allows class rvalues to bind to
2971 // non-constant references.
2972
2973 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2974 // with the implicit object parameter (C++ [over.match.funcs]p5).
2975 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00002976 if (ImplicitParamType.getCVRQualifiers()
2977 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00002978 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00002979 ICS.setBad(BadConversionSequence::bad_qualifiers,
2980 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002981 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00002982 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002983
2984 // Check that we have either the same type or a derived type. It
2985 // affects the conversion rank.
2986 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00002987 ImplicitConversionKind SecondKind;
2988 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2989 SecondKind = ICK_Identity;
2990 } else if (IsDerivedFrom(FromType, ClassType))
2991 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00002992 else {
John McCallb1bdc622010-02-25 01:37:24 +00002993 ICS.setBad(BadConversionSequence::unrelated_class,
2994 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00002995 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00002996 }
Douglas Gregor96176b32008-11-18 23:14:02 +00002997
2998 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00002999 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00003000 ICS.Standard.setAsIdentityConversion();
3001 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00003002 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003003 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003004 ICS.Standard.ReferenceBinding = true;
3005 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00003006 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003007 return ICS;
3008}
3009
3010/// PerformObjectArgumentInitialization - Perform initialization of
3011/// the implicit object parameter for the given Method with the given
3012/// expression.
3013bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00003014Sema::PerformObjectArgumentInitialization(Expr *&From,
3015 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00003016 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00003017 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003018 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00003019 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00003020 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003021
Ted Kremenek6217b802009-07-29 21:53:49 +00003022 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003023 FromRecordType = PT->getPointeeType();
3024 DestType = Method->getThisType(Context);
3025 } else {
3026 FromRecordType = From->getType();
3027 DestType = ImplicitParamRecordType;
3028 }
3029
John McCall701c89e2009-12-03 04:06:58 +00003030 // Note that we always use the true parent context when performing
3031 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003032 ImplicitConversionSequence ICS
John McCall701c89e2009-12-03 04:06:58 +00003033 = TryObjectArgumentInitialization(From->getType(), Method,
3034 Method->getParent());
John McCall1d318332010-01-12 00:44:57 +00003035 if (ICS.isBad())
Douglas Gregor96176b32008-11-18 23:14:02 +00003036 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003037 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00003038 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003039
Douglas Gregor5fccd362010-03-03 23:55:11 +00003040 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall6bb80172010-03-30 21:47:33 +00003041 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor96176b32008-11-18 23:14:02 +00003042
Douglas Gregor5fccd362010-03-03 23:55:11 +00003043 if (!Context.hasSameType(From->getType(), DestType))
Anders Carlssonf1b48b72010-04-24 16:57:13 +00003044 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
Sebastian Redl906082e2010-07-20 04:20:21 +00003045 From->getType()->isPointerType() ?
3046 ImplicitCastExpr::RValue : ImplicitCastExpr::LValue);
Douglas Gregor96176b32008-11-18 23:14:02 +00003047 return false;
3048}
3049
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003050/// TryContextuallyConvertToBool - Attempt to contextually convert the
3051/// expression From to bool (C++0x [conv]p3).
3052ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00003053 // FIXME: This is pretty broken.
Mike Stump1eb44332009-09-09 15:08:12 +00003054 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00003055 // FIXME: Are these flags correct?
3056 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00003057 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00003058 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003059}
3060
3061/// PerformContextuallyConvertToBool - Perform a contextual conversion
3062/// of the expression From to bool (C++0x [conv]p3).
3063bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
3064 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall1d318332010-01-12 00:44:57 +00003065 if (!ICS.isBad())
3066 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003067
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003068 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003069 return Diag(From->getSourceRange().getBegin(),
3070 diag::err_typecheck_bool_condition)
3071 << From->getType() << From->getSourceRange();
3072 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003073}
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003074
3075/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3076/// expression From to 'id'.
3077ImplicitConversionSequence Sema::TryContextuallyConvertToObjCId(Expr *From) {
John McCallc12c5bb2010-05-15 11:32:37 +00003078 QualType Ty = Context.getObjCIdType();
3079 return TryImplicitConversion(From, Ty,
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003080 // FIXME: Are these flags correct?
3081 /*SuppressUserConversions=*/false,
3082 /*AllowExplicit=*/true,
3083 /*InOverloadResolution=*/false);
3084}
3085
3086/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3087/// of the expression From to 'id'.
3088bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCallc12c5bb2010-05-15 11:32:37 +00003089 QualType Ty = Context.getObjCIdType();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003090 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(From);
3091 if (!ICS.isBad())
3092 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3093 return true;
3094}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003095
Douglas Gregorc30614b2010-06-29 23:17:37 +00003096/// \brief Attempt to convert the given expression to an integral or
3097/// enumeration type.
3098///
3099/// This routine will attempt to convert an expression of class type to an
3100/// integral or enumeration type, if that class type only has a single
3101/// conversion to an integral or enumeration type.
3102///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003103/// \param Loc The source location of the construct that requires the
3104/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00003105///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003106/// \param FromE The expression we're converting from.
3107///
3108/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3109/// have integral or enumeration type.
3110///
3111/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3112/// incomplete class type.
3113///
3114/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3115/// explicit conversion function (because no implicit conversion functions
3116/// were available). This is a recovery mode.
3117///
3118/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3119/// showing which conversion was picked.
3120///
3121/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3122/// conversion function that could convert to integral or enumeration type.
3123///
3124/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3125/// usable conversion function.
3126///
3127/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3128/// function, which may be an extension in this case.
3129///
3130/// \returns The expression, converted to an integral or enumeration type if
3131/// successful.
Douglas Gregorc30614b2010-06-29 23:17:37 +00003132Sema::OwningExprResult
3133Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, ExprArg FromE,
3134 const PartialDiagnostic &NotIntDiag,
3135 const PartialDiagnostic &IncompleteDiag,
3136 const PartialDiagnostic &ExplicitConvDiag,
3137 const PartialDiagnostic &ExplicitConvNote,
3138 const PartialDiagnostic &AmbigDiag,
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003139 const PartialDiagnostic &AmbigNote,
3140 const PartialDiagnostic &ConvDiag) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00003141 Expr *From = static_cast<Expr *>(FromE.get());
3142
3143 // We can't perform any more checking for type-dependent expressions.
3144 if (From->isTypeDependent())
3145 return move(FromE);
3146
3147 // If the expression already has integral or enumeration type, we're golden.
3148 QualType T = From->getType();
3149 if (T->isIntegralOrEnumerationType())
3150 return move(FromE);
3151
3152 // FIXME: Check for missing '()' if T is a function type?
3153
3154 // If we don't have a class type in C++, there's no way we can get an
3155 // expression of integral or enumeration type.
3156 const RecordType *RecordTy = T->getAs<RecordType>();
3157 if (!RecordTy || !getLangOptions().CPlusPlus) {
3158 Diag(Loc, NotIntDiag)
3159 << T << From->getSourceRange();
Douglas Gregoracb0bd82010-06-29 23:25:20 +00003160 return move(FromE);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003161 }
3162
3163 // We must have a complete class type.
3164 if (RequireCompleteType(Loc, T, IncompleteDiag))
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003165 return move(FromE);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003166
3167 // Look for a conversion to an integral or enumeration type.
3168 UnresolvedSet<4> ViableConversions;
3169 UnresolvedSet<4> ExplicitConversions;
3170 const UnresolvedSetImpl *Conversions
3171 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3172
3173 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3174 E = Conversions->end();
3175 I != E;
3176 ++I) {
3177 if (CXXConversionDecl *Conversion
3178 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3179 if (Conversion->getConversionType().getNonReferenceType()
3180 ->isIntegralOrEnumerationType()) {
3181 if (Conversion->isExplicit())
3182 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3183 else
3184 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3185 }
3186 }
3187
3188 switch (ViableConversions.size()) {
3189 case 0:
3190 if (ExplicitConversions.size() == 1) {
3191 DeclAccessPair Found = ExplicitConversions[0];
3192 CXXConversionDecl *Conversion
3193 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3194
3195 // The user probably meant to invoke the given explicit
3196 // conversion; use it.
3197 QualType ConvTy
3198 = Conversion->getConversionType().getNonReferenceType();
3199 std::string TypeStr;
3200 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3201
3202 Diag(Loc, ExplicitConvDiag)
3203 << T << ConvTy
3204 << FixItHint::CreateInsertion(From->getLocStart(),
3205 "static_cast<" + TypeStr + ">(")
3206 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3207 ")");
3208 Diag(Conversion->getLocation(), ExplicitConvNote)
3209 << ConvTy->isEnumeralType() << ConvTy;
3210
3211 // If we aren't in a SFINAE context, build a call to the
3212 // explicit conversion function.
3213 if (isSFINAEContext())
3214 return ExprError();
3215
3216 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
3217 From = BuildCXXMemberCallExpr(FromE.takeAs<Expr>(), Found, Conversion);
3218 FromE = Owned(From);
3219 }
3220
3221 // We'll complain below about a non-integral condition type.
3222 break;
3223
3224 case 1: {
3225 // Apply this conversion.
3226 DeclAccessPair Found = ViableConversions[0];
3227 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003228
3229 CXXConversionDecl *Conversion
3230 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3231 QualType ConvTy
3232 = Conversion->getConversionType().getNonReferenceType();
3233 if (ConvDiag.getDiagID()) {
3234 if (isSFINAEContext())
3235 return ExprError();
3236
3237 Diag(Loc, ConvDiag)
3238 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3239 }
3240
Douglas Gregorc30614b2010-06-29 23:17:37 +00003241 From = BuildCXXMemberCallExpr(FromE.takeAs<Expr>(), Found,
3242 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
3243 FromE = Owned(From);
3244 break;
3245 }
3246
3247 default:
3248 Diag(Loc, AmbigDiag)
3249 << T << From->getSourceRange();
3250 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3251 CXXConversionDecl *Conv
3252 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3253 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3254 Diag(Conv->getLocation(), AmbigNote)
3255 << ConvTy->isEnumeralType() << ConvTy;
3256 }
Douglas Gregoracb0bd82010-06-29 23:25:20 +00003257 return move(FromE);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003258 }
3259
Douglas Gregoracb0bd82010-06-29 23:25:20 +00003260 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorc30614b2010-06-29 23:17:37 +00003261 Diag(Loc, NotIntDiag)
3262 << From->getType() << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00003263
3264 return move(FromE);
3265}
3266
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003267/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00003268/// candidate functions, using the given function call arguments. If
3269/// @p SuppressUserConversions, then don't allow user-defined
3270/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003271///
3272/// \para PartialOverloading true if we are performing "partial" overloading
3273/// based on an incomplete set of function arguments. This feature is used by
3274/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00003275void
3276Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00003277 DeclAccessPair FoundDecl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003278 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00003279 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00003280 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003281 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00003282 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003283 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003284 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00003285 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00003286 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00003287
Douglas Gregor88a35142008-12-22 05:46:06 +00003288 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003289 if (!isa<CXXConstructorDecl>(Method)) {
3290 // If we get here, it's because we're calling a member function
3291 // that is named without a member access expression (e.g.,
3292 // "this->f") that was either written explicitly or created
3293 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00003294 // function, e.g., X::f(). We use an empty type for the implied
3295 // object argument (C++ [over.call.func]p3), and the acting context
3296 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00003297 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall701c89e2009-12-03 04:06:58 +00003298 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003299 SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003300 return;
3301 }
3302 // We treat a constructor like a non-member function, since its object
3303 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00003304 }
3305
Douglas Gregorfd476482009-11-13 23:59:09 +00003306 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00003307 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00003308
Douglas Gregor7edfb692009-11-23 12:27:39 +00003309 // Overload resolution is always an unevaluated context.
3310 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3311
Douglas Gregor66724ea2009-11-14 01:20:54 +00003312 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3313 // C++ [class.copy]p3:
3314 // A member function template is never instantiated to perform the copy
3315 // of a class object to an object of its class type.
3316 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3317 if (NumArgs == 1 &&
3318 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor12116062010-02-21 18:30:38 +00003319 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3320 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00003321 return;
3322 }
3323
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003324 // Add this candidate
3325 CandidateSet.push_back(OverloadCandidate());
3326 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003327 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003328 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00003329 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003330 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003331 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003332
3333 unsigned NumArgsInProto = Proto->getNumArgs();
3334
3335 // (C++ 13.3.2p2): A candidate function having fewer than m
3336 // parameters is viable only if it has an ellipsis in its parameter
3337 // list (8.3.5).
Douglas Gregor5bd1a112009-09-23 14:56:09 +00003338 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3339 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003340 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003341 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003342 return;
3343 }
3344
3345 // (C++ 13.3.2p2): A candidate function having more than m parameters
3346 // is viable only if the (m+1)st parameter has a default argument
3347 // (8.3.6). For the purposes of overload resolution, the
3348 // parameter list is truncated on the right, so that there are
3349 // exactly m parameters.
3350 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003351 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003352 // Not enough arguments.
3353 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003354 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003355 return;
3356 }
3357
3358 // Determine the implicit conversion sequences for each of the
3359 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003360 Candidate.Conversions.resize(NumArgs);
3361 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3362 if (ArgIdx < NumArgsInProto) {
3363 // (C++ 13.3.2p3): for F to be a viable function, there shall
3364 // exist for each argument an implicit conversion sequence
3365 // (13.3.3.1) that converts that argument to the corresponding
3366 // parameter of F.
3367 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003368 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003369 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003370 SuppressUserConversions,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003371 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003372 if (Candidate.Conversions[ArgIdx].isBad()) {
3373 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003374 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00003375 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00003376 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003377 } else {
3378 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3379 // argument for which there is no corresponding parameter is
3380 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003381 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003382 }
3383 }
3384}
3385
Douglas Gregor063daf62009-03-13 18:40:31 +00003386/// \brief Add all of the function declarations in the given function set to
3387/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00003388void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00003389 Expr **Args, unsigned NumArgs,
3390 OverloadCandidateSet& CandidateSet,
3391 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00003392 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00003393 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3394 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003395 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003396 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003397 cast<CXXMethodDecl>(FD)->getParent(),
3398 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003399 CandidateSet, SuppressUserConversions);
3400 else
John McCall9aa472c2010-03-19 07:35:19 +00003401 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00003402 SuppressUserConversions);
3403 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003404 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00003405 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3406 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003407 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003408 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00003409 /*FIXME: explicit args */ 0,
John McCall701c89e2009-12-03 04:06:58 +00003410 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003411 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00003412 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00003413 else
John McCall9aa472c2010-03-19 07:35:19 +00003414 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCalld5532b62009-11-23 01:53:49 +00003415 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00003416 Args, NumArgs, CandidateSet,
3417 SuppressUserConversions);
3418 }
Douglas Gregor364e0212009-06-27 21:05:07 +00003419 }
Douglas Gregor063daf62009-03-13 18:40:31 +00003420}
3421
John McCall314be4e2009-11-17 07:50:12 +00003422/// AddMethodCandidate - Adds a named decl (which is some kind of
3423/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00003424void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003425 QualType ObjectType,
John McCall314be4e2009-11-17 07:50:12 +00003426 Expr **Args, unsigned NumArgs,
3427 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003428 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00003429 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003430 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00003431
3432 if (isa<UsingShadowDecl>(Decl))
3433 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3434
3435 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3436 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3437 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00003438 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3439 /*ExplicitArgs*/ 0,
John McCall701c89e2009-12-03 04:06:58 +00003440 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00003441 CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003442 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003443 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003444 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall701c89e2009-12-03 04:06:58 +00003445 ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003446 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003447 }
3448}
3449
Douglas Gregor96176b32008-11-18 23:14:02 +00003450/// AddMethodCandidate - Adds the given C++ member function to the set
3451/// of candidate functions, using the given function call arguments
3452/// and the object argument (@c Object). For example, in a call
3453/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3454/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3455/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00003456/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00003457void
John McCall9aa472c2010-03-19 07:35:19 +00003458Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003459 CXXRecordDecl *ActingContext, QualType ObjectType,
3460 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00003461 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003462 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00003463 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003464 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00003465 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003466 assert(!isa<CXXConstructorDecl>(Method) &&
3467 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00003468
Douglas Gregor3f396022009-09-28 04:47:19 +00003469 if (!CandidateSet.isNewCandidate(Method))
3470 return;
3471
Douglas Gregor7edfb692009-11-23 12:27:39 +00003472 // Overload resolution is always an unevaluated context.
3473 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3474
Douglas Gregor96176b32008-11-18 23:14:02 +00003475 // Add this candidate
3476 CandidateSet.push_back(OverloadCandidate());
3477 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003478 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00003479 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003480 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003481 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003482
3483 unsigned NumArgsInProto = Proto->getNumArgs();
3484
3485 // (C++ 13.3.2p2): A candidate function having fewer than m
3486 // parameters is viable only if it has an ellipsis in its parameter
3487 // list (8.3.5).
3488 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3489 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003490 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003491 return;
3492 }
3493
3494 // (C++ 13.3.2p2): A candidate function having more than m parameters
3495 // is viable only if the (m+1)st parameter has a default argument
3496 // (8.3.6). For the purposes of overload resolution, the
3497 // parameter list is truncated on the right, so that there are
3498 // exactly m parameters.
3499 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3500 if (NumArgs < MinRequiredArgs) {
3501 // Not enough arguments.
3502 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003503 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003504 return;
3505 }
3506
3507 Candidate.Viable = true;
3508 Candidate.Conversions.resize(NumArgs + 1);
3509
John McCall701c89e2009-12-03 04:06:58 +00003510 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00003511 // The implicit object argument is ignored.
3512 Candidate.IgnoreObjectArgument = true;
3513 else {
3514 // Determine the implicit conversion sequence for the object
3515 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00003516 Candidate.Conversions[0]
3517 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00003518 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003519 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003520 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00003521 return;
3522 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003523 }
3524
3525 // Determine the implicit conversion sequences for each of the
3526 // arguments.
3527 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3528 if (ArgIdx < NumArgsInProto) {
3529 // (C++ 13.3.2p3): for F to be a viable function, there shall
3530 // exist for each argument an implicit conversion sequence
3531 // (13.3.3.1) that converts that argument to the corresponding
3532 // parameter of F.
3533 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003534 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003535 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003536 SuppressUserConversions,
Anders Carlsson08972922009-08-28 15:33:32 +00003537 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003538 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00003539 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003540 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00003541 break;
3542 }
3543 } else {
3544 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3545 // argument for which there is no corresponding parameter is
3546 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003547 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00003548 }
3549 }
3550}
Douglas Gregora9333192010-05-08 17:41:32 +00003551
Douglas Gregor6b906862009-08-21 00:16:32 +00003552/// \brief Add a C++ member function template as a candidate to the candidate
3553/// set, using template argument deduction to produce an appropriate member
3554/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003555void
Douglas Gregor6b906862009-08-21 00:16:32 +00003556Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00003557 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003558 CXXRecordDecl *ActingContext,
John McCalld5532b62009-11-23 01:53:49 +00003559 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00003560 QualType ObjectType,
3561 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003562 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003563 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003564 if (!CandidateSet.isNewCandidate(MethodTmpl))
3565 return;
3566
Douglas Gregor6b906862009-08-21 00:16:32 +00003567 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003568 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00003569 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003570 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00003571 // candidate functions in the usual way.113) A given name can refer to one
3572 // or more function templates and also to a set of overloaded non-template
3573 // functions. In such a case, the candidate functions generated from each
3574 // function template are combined with the set of non-template candidate
3575 // functions.
John McCall5769d612010-02-08 23:07:23 +00003576 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00003577 FunctionDecl *Specialization = 0;
3578 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003579 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003580 Args, NumArgs, Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003581 CandidateSet.push_back(OverloadCandidate());
3582 OverloadCandidate &Candidate = CandidateSet.back();
3583 Candidate.FoundDecl = FoundDecl;
3584 Candidate.Function = MethodTmpl->getTemplatedDecl();
3585 Candidate.Viable = false;
3586 Candidate.FailureKind = ovl_fail_bad_deduction;
3587 Candidate.IsSurrogate = false;
3588 Candidate.IgnoreObjectArgument = false;
3589 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3590 Info);
3591 return;
3592 }
Mike Stump1eb44332009-09-09 15:08:12 +00003593
Douglas Gregor6b906862009-08-21 00:16:32 +00003594 // Add the function template specialization produced by template argument
3595 // deduction as a candidate.
3596 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00003597 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00003598 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00003599 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003600 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003601 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00003602}
3603
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003604/// \brief Add a C++ function template specialization as a candidate
3605/// in the candidate set, using template argument deduction to produce
3606/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003607void
Douglas Gregore53060f2009-06-25 22:08:12 +00003608Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003609 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00003610 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00003611 Expr **Args, unsigned NumArgs,
3612 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003613 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003614 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3615 return;
3616
Douglas Gregore53060f2009-06-25 22:08:12 +00003617 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003618 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00003619 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003620 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00003621 // candidate functions in the usual way.113) A given name can refer to one
3622 // or more function templates and also to a set of overloaded non-template
3623 // functions. In such a case, the candidate functions generated from each
3624 // function template are combined with the set of non-template candidate
3625 // functions.
John McCall5769d612010-02-08 23:07:23 +00003626 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00003627 FunctionDecl *Specialization = 0;
3628 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003629 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003630 Args, NumArgs, Specialization, Info)) {
John McCall578b69b2009-12-16 08:11:27 +00003631 CandidateSet.push_back(OverloadCandidate());
3632 OverloadCandidate &Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003633 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00003634 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3635 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003636 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00003637 Candidate.IsSurrogate = false;
3638 Candidate.IgnoreObjectArgument = false;
Douglas Gregorff5adac2010-05-08 20:18:54 +00003639 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3640 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00003641 return;
3642 }
Mike Stump1eb44332009-09-09 15:08:12 +00003643
Douglas Gregore53060f2009-06-25 22:08:12 +00003644 // Add the function template specialization produced by template argument
3645 // deduction as a candidate.
3646 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003647 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003648 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00003649}
Mike Stump1eb44332009-09-09 15:08:12 +00003650
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003651/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00003652/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003653/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00003654/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003655/// (which may or may not be the same type as the type that the
3656/// conversion function produces).
3657void
3658Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003659 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003660 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003661 Expr *From, QualType ToType,
3662 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003663 assert(!Conversion->getDescribedFunctionTemplate() &&
3664 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003665 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00003666 if (!CandidateSet.isNewCandidate(Conversion))
3667 return;
3668
Douglas Gregor7edfb692009-11-23 12:27:39 +00003669 // Overload resolution is always an unevaluated context.
3670 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3671
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003672 // Add this candidate
3673 CandidateSet.push_back(OverloadCandidate());
3674 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003675 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003676 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003677 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003678 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003679 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003680 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003681 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003682
Douglas Gregor96176b32008-11-18 23:14:02 +00003683 // Determine the implicit conversion sequence for the implicit
3684 // object parameter.
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003685 Candidate.Viable = true;
3686 Candidate.Conversions.resize(1);
John McCall701c89e2009-12-03 04:06:58 +00003687 Candidate.Conversions[0]
3688 = TryObjectArgumentInitialization(From->getType(), Conversion,
3689 ActingContext);
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00003690 // Conversion functions to a different type in the base class is visible in
3691 // the derived class. So, a derived to base conversion should not participate
3692 // in overload resolution.
3693 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
3694 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall1d318332010-01-12 00:44:57 +00003695 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003696 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003697 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003698 return;
3699 }
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003700
3701 // We won't go through a user-define type conversion function to convert a
3702 // derived to base as such conversions are given Conversion Rank. They only
3703 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3704 QualType FromCanon
3705 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3706 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3707 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3708 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003709 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003710 return;
3711 }
3712
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003713 // To determine what the conversion from the result of calling the
3714 // conversion function to the type we're eventually trying to
3715 // convert to (ToType), we need to synthesize a call to the
3716 // conversion function and attempt copy initialization from it. This
3717 // makes sure that we get the right semantics with respect to
3718 // lvalues/rvalues and the type. Fortunately, we can allocate this
3719 // call on the stack and we don't need its arguments to be
3720 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00003721 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003722 From->getLocStart());
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003723 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman73c39ab2009-10-20 08:27:19 +00003724 CastExpr::CK_FunctionToPointerDecay,
Sebastian Redl906082e2010-07-20 04:20:21 +00003725 &ConversionRef, CXXBaseSpecifierArray(),
3726 ImplicitCastExpr::RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00003727
3728 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00003729 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3730 // allocator).
Mike Stump1eb44332009-09-09 15:08:12 +00003731 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregor63982352010-07-13 18:40:04 +00003732 Conversion->getConversionType().getNonLValueExprType(Context),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003733 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00003734 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00003735 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00003736 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003737 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00003738
John McCall1d318332010-01-12 00:44:57 +00003739 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003740 case ImplicitConversionSequence::StandardConversion:
3741 Candidate.FinalConversion = ICS.Standard;
Douglas Gregorc520c842010-04-12 23:42:09 +00003742
3743 // C++ [over.ics.user]p3:
3744 // If the user-defined conversion is specified by a specialization of a
3745 // conversion function template, the second standard conversion sequence
3746 // shall have exact match rank.
3747 if (Conversion->getPrimaryTemplate() &&
3748 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3749 Candidate.Viable = false;
3750 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3751 }
3752
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003753 break;
3754
3755 case ImplicitConversionSequence::BadConversion:
3756 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003757 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003758 break;
3759
3760 default:
Mike Stump1eb44332009-09-09 15:08:12 +00003761 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003762 "Can only end up with a standard conversion sequence or failure");
3763 }
3764}
3765
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003766/// \brief Adds a conversion function template specialization
3767/// candidate to the overload set, using template argument deduction
3768/// to deduce the template arguments of the conversion function
3769/// template from the type that we are converting to (C++
3770/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00003771void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003772Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003773 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003774 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003775 Expr *From, QualType ToType,
3776 OverloadCandidateSet &CandidateSet) {
3777 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3778 "Only conversion function templates permitted here");
3779
Douglas Gregor3f396022009-09-28 04:47:19 +00003780 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3781 return;
3782
John McCall5769d612010-02-08 23:07:23 +00003783 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003784 CXXConversionDecl *Specialization = 0;
3785 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00003786 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003787 Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003788 CandidateSet.push_back(OverloadCandidate());
3789 OverloadCandidate &Candidate = CandidateSet.back();
3790 Candidate.FoundDecl = FoundDecl;
3791 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3792 Candidate.Viable = false;
3793 Candidate.FailureKind = ovl_fail_bad_deduction;
3794 Candidate.IsSurrogate = false;
3795 Candidate.IgnoreObjectArgument = false;
3796 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3797 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003798 return;
3799 }
Mike Stump1eb44332009-09-09 15:08:12 +00003800
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003801 // Add the conversion function template specialization produced by
3802 // template argument deduction as a candidate.
3803 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003804 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00003805 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003806}
3807
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003808/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3809/// converts the given @c Object to a function pointer via the
3810/// conversion function @c Conversion, and then attempts to call it
3811/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3812/// the type of function that we'll eventually be calling.
3813void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003814 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003815 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00003816 const FunctionProtoType *Proto,
John McCall701c89e2009-12-03 04:06:58 +00003817 QualType ObjectType,
3818 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003819 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003820 if (!CandidateSet.isNewCandidate(Conversion))
3821 return;
3822
Douglas Gregor7edfb692009-11-23 12:27:39 +00003823 // Overload resolution is always an unevaluated context.
3824 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3825
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003826 CandidateSet.push_back(OverloadCandidate());
3827 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003828 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003829 Candidate.Function = 0;
3830 Candidate.Surrogate = Conversion;
3831 Candidate.Viable = true;
3832 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003833 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003834 Candidate.Conversions.resize(NumArgs + 1);
3835
3836 // Determine the implicit conversion sequence for the implicit
3837 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00003838 ImplicitConversionSequence ObjectInit
John McCall701c89e2009-12-03 04:06:58 +00003839 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00003840 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003841 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003842 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00003843 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003844 return;
3845 }
3846
3847 // The first conversion is actually a user-defined conversion whose
3848 // first conversion is ObjectInit's standard conversion (which is
3849 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00003850 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003851 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00003852 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003853 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00003854 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003855 = Candidate.Conversions[0].UserDefined.Before;
3856 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3857
Mike Stump1eb44332009-09-09 15:08:12 +00003858 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003859 unsigned NumArgsInProto = Proto->getNumArgs();
3860
3861 // (C++ 13.3.2p2): A candidate function having fewer than m
3862 // parameters is viable only if it has an ellipsis in its parameter
3863 // list (8.3.5).
3864 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3865 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003866 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003867 return;
3868 }
3869
3870 // Function types don't have any default arguments, so just check if
3871 // we have enough arguments.
3872 if (NumArgs < NumArgsInProto) {
3873 // Not enough arguments.
3874 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003875 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003876 return;
3877 }
3878
3879 // Determine the implicit conversion sequences for each of the
3880 // arguments.
3881 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3882 if (ArgIdx < NumArgsInProto) {
3883 // (C++ 13.3.2p3): for F to be a viable function, there shall
3884 // exist for each argument an implicit conversion sequence
3885 // (13.3.3.1) that converts that argument to the corresponding
3886 // parameter of F.
3887 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003888 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003889 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00003890 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003891 /*InOverloadResolution=*/false);
John McCall1d318332010-01-12 00:44:57 +00003892 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003893 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003894 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003895 break;
3896 }
3897 } else {
3898 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3899 // argument for which there is no corresponding parameter is
3900 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003901 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003902 }
3903 }
3904}
3905
Douglas Gregor063daf62009-03-13 18:40:31 +00003906/// \brief Add overload candidates for overloaded operators that are
3907/// member functions.
3908///
3909/// Add the overloaded operator candidates that are member functions
3910/// for the operator Op that was used in an operator expression such
3911/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3912/// CandidateSet will store the added overload candidates. (C++
3913/// [over.match.oper]).
3914void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3915 SourceLocation OpLoc,
3916 Expr **Args, unsigned NumArgs,
3917 OverloadCandidateSet& CandidateSet,
3918 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00003919 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3920
3921 // C++ [over.match.oper]p3:
3922 // For a unary operator @ with an operand of a type whose
3923 // cv-unqualified version is T1, and for a binary operator @ with
3924 // a left operand of a type whose cv-unqualified version is T1 and
3925 // a right operand of a type whose cv-unqualified version is T2,
3926 // three sets of candidate functions, designated member
3927 // candidates, non-member candidates and built-in candidates, are
3928 // constructed as follows:
3929 QualType T1 = Args[0]->getType();
3930 QualType T2;
3931 if (NumArgs > 1)
3932 T2 = Args[1]->getType();
3933
3934 // -- If T1 is a class type, the set of member candidates is the
3935 // result of the qualified lookup of T1::operator@
3936 // (13.3.1.1.1); otherwise, the set of member candidates is
3937 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00003938 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003939 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00003940 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003941 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003942
John McCalla24dc2e2009-11-17 02:14:36 +00003943 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3944 LookupQualifiedName(Operators, T1Rec->getDecl());
3945 Operators.suppressDiagnostics();
3946
Mike Stump1eb44332009-09-09 15:08:12 +00003947 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00003948 OperEnd = Operators.end();
3949 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00003950 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00003951 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall701c89e2009-12-03 04:06:58 +00003952 Args + 1, NumArgs - 1, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00003953 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00003954 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003955}
3956
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003957/// AddBuiltinCandidate - Add a candidate for a built-in
3958/// operator. ResultTy and ParamTys are the result and parameter types
3959/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003960/// arguments being passed to the candidate. IsAssignmentOperator
3961/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003962/// operator. NumContextualBoolArguments is the number of arguments
3963/// (at the beginning of the argument list) that will be contextually
3964/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00003965void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003966 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003967 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003968 bool IsAssignmentOperator,
3969 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00003970 // Overload resolution is always an unevaluated context.
3971 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3972
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003973 // Add this candidate
3974 CandidateSet.push_back(OverloadCandidate());
3975 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003976 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003977 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003978 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003979 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003980 Candidate.BuiltinTypes.ResultTy = ResultTy;
3981 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3982 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3983
3984 // Determine the implicit conversion sequences for each of the
3985 // arguments.
3986 Candidate.Viable = true;
3987 Candidate.Conversions.resize(NumArgs);
3988 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003989 // C++ [over.match.oper]p4:
3990 // For the built-in assignment operators, conversions of the
3991 // left operand are restricted as follows:
3992 // -- no temporaries are introduced to hold the left operand, and
3993 // -- no user-defined conversions are applied to the left
3994 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00003995 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00003996 //
3997 // We block these conversions by turning off user-defined
3998 // conversions, since that is the only way that initialization of
3999 // a reference to a non-class type can occur from something that
4000 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004001 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00004002 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004003 "Contextual conversion to bool requires bool type");
4004 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
4005 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00004006 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004007 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00004008 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00004009 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004010 }
John McCall1d318332010-01-12 00:44:57 +00004011 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004012 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004013 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00004014 break;
4015 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004016 }
4017}
4018
4019/// BuiltinCandidateTypeSet - A set of types that will be used for the
4020/// candidate operator functions for built-in operators (C++
4021/// [over.built]). The types are separated into pointer types and
4022/// enumeration types.
4023class BuiltinCandidateTypeSet {
4024 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004025 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004026
4027 /// PointerTypes - The set of pointer types that will be used in the
4028 /// built-in candidates.
4029 TypeSet PointerTypes;
4030
Sebastian Redl78eb8742009-04-19 21:53:20 +00004031 /// MemberPointerTypes - The set of member pointer types that will be
4032 /// used in the built-in candidates.
4033 TypeSet MemberPointerTypes;
4034
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004035 /// EnumerationTypes - The set of enumeration types that will be
4036 /// used in the built-in candidates.
4037 TypeSet EnumerationTypes;
4038
Douglas Gregor26bcf672010-05-19 03:21:00 +00004039 /// \brief The set of vector types that will be used in the built-in
4040 /// candidates.
4041 TypeSet VectorTypes;
4042
Douglas Gregor5842ba92009-08-24 15:23:48 +00004043 /// Sema - The semantic analysis instance where we are building the
4044 /// candidate type set.
4045 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00004046
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004047 /// Context - The AST context in which we will build the type sets.
4048 ASTContext &Context;
4049
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004050 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4051 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00004052 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004053
4054public:
4055 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004056 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004057
Mike Stump1eb44332009-09-09 15:08:12 +00004058 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor5842ba92009-08-24 15:23:48 +00004059 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004060
Douglas Gregor573d9c32009-10-21 23:19:44 +00004061 void AddTypesConvertedFrom(QualType Ty,
4062 SourceLocation Loc,
4063 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004064 bool AllowExplicitConversions,
4065 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004066
4067 /// pointer_begin - First pointer type found;
4068 iterator pointer_begin() { return PointerTypes.begin(); }
4069
Sebastian Redl78eb8742009-04-19 21:53:20 +00004070 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004071 iterator pointer_end() { return PointerTypes.end(); }
4072
Sebastian Redl78eb8742009-04-19 21:53:20 +00004073 /// member_pointer_begin - First member pointer type found;
4074 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4075
4076 /// member_pointer_end - Past the last member pointer type found;
4077 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4078
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004079 /// enumeration_begin - First enumeration type found;
4080 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4081
Sebastian Redl78eb8742009-04-19 21:53:20 +00004082 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004083 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004084
4085 iterator vector_begin() { return VectorTypes.begin(); }
4086 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004087};
4088
Sebastian Redl78eb8742009-04-19 21:53:20 +00004089/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004090/// the set of pointer types along with any more-qualified variants of
4091/// that type. For example, if @p Ty is "int const *", this routine
4092/// will add "int const *", "int const volatile *", "int const
4093/// restrict *", and "int const volatile restrict *" to the set of
4094/// pointer types. Returns true if the add of @p Ty itself succeeded,
4095/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00004096///
4097/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004098bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00004099BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4100 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00004101
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004102 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004103 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004104 return false;
4105
John McCall0953e762009-09-24 19:53:00 +00004106 const PointerType *PointerTy = Ty->getAs<PointerType>();
4107 assert(PointerTy && "type was not a pointer type!");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004108
John McCall0953e762009-09-24 19:53:00 +00004109 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00004110 // Don't add qualified variants of arrays. For one, they're not allowed
4111 // (the qualifier would sink to the element type), and for another, the
4112 // only overload situation where it matters is subscript or pointer +- int,
4113 // and those shouldn't have qualifier variants anyway.
4114 if (PointeeTy->isArrayType())
4115 return true;
John McCall0953e762009-09-24 19:53:00 +00004116 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00004117 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00004118 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004119 bool hasVolatile = VisibleQuals.hasVolatile();
4120 bool hasRestrict = VisibleQuals.hasRestrict();
4121
John McCall0953e762009-09-24 19:53:00 +00004122 // Iterate through all strict supersets of BaseCVR.
4123 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4124 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004125 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4126 // in the types.
4127 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4128 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00004129 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4130 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004131 }
4132
4133 return true;
4134}
4135
Sebastian Redl78eb8742009-04-19 21:53:20 +00004136/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4137/// to the set of pointer types along with any more-qualified variants of
4138/// that type. For example, if @p Ty is "int const *", this routine
4139/// will add "int const *", "int const volatile *", "int const
4140/// restrict *", and "int const volatile restrict *" to the set of
4141/// pointer types. Returns true if the add of @p Ty itself succeeded,
4142/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00004143///
4144/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004145bool
4146BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4147 QualType Ty) {
4148 // Insert this type.
4149 if (!MemberPointerTypes.insert(Ty))
4150 return false;
4151
John McCall0953e762009-09-24 19:53:00 +00004152 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4153 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00004154
John McCall0953e762009-09-24 19:53:00 +00004155 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00004156 // Don't add qualified variants of arrays. For one, they're not allowed
4157 // (the qualifier would sink to the element type), and for another, the
4158 // only overload situation where it matters is subscript or pointer +- int,
4159 // and those shouldn't have qualifier variants anyway.
4160 if (PointeeTy->isArrayType())
4161 return true;
John McCall0953e762009-09-24 19:53:00 +00004162 const Type *ClassTy = PointerTy->getClass();
4163
4164 // Iterate through all strict supersets of the pointee type's CVR
4165 // qualifiers.
4166 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4167 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4168 if ((CVR | BaseCVR) != CVR) continue;
4169
4170 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4171 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00004172 }
4173
4174 return true;
4175}
4176
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004177/// AddTypesConvertedFrom - Add each of the types to which the type @p
4178/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00004179/// primarily interested in pointer types and enumeration types. We also
4180/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004181/// AllowUserConversions is true if we should look at the conversion
4182/// functions of a class type, and AllowExplicitConversions if we
4183/// should also include the explicit conversion functions of a class
4184/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00004185void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004186BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004187 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004188 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004189 bool AllowExplicitConversions,
4190 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004191 // Only deal with canonical types.
4192 Ty = Context.getCanonicalType(Ty);
4193
4194 // Look through reference types; they aren't part of the type of an
4195 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00004196 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004197 Ty = RefTy->getPointeeType();
4198
4199 // We don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004200 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004201
Sebastian Redla65b5512009-11-05 16:36:20 +00004202 // If we're dealing with an array type, decay to the pointer.
4203 if (Ty->isArrayType())
4204 Ty = SemaRef.Context.getArrayDecayedType(Ty);
4205
Ted Kremenek6217b802009-07-29 21:53:49 +00004206 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004207 QualType PointeeTy = PointerTy->getPointeeType();
4208
4209 // Insert our type, and its more-qualified variants, into the set
4210 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004211 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004212 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00004213 } else if (Ty->isMemberPointerType()) {
4214 // Member pointers are far easier, since the pointee can't be converted.
4215 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4216 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004217 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00004218 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004219 } else if (Ty->isVectorType()) {
4220 VectorTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004221 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004222 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00004223 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00004224 // No conversion functions in incomplete types.
4225 return;
4226 }
Mike Stump1eb44332009-09-09 15:08:12 +00004227
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004228 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00004229 const UnresolvedSetImpl *Conversions
Fariborz Jahanianca4fb042009-10-07 17:26:09 +00004230 = ClassDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00004231 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004232 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00004233 NamedDecl *D = I.getDecl();
4234 if (isa<UsingShadowDecl>(D))
4235 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004236
Mike Stump1eb44332009-09-09 15:08:12 +00004237 // Skip conversion function templates; they don't tell us anything
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004238 // about which builtin types we can convert to.
John McCall32daa422010-03-31 01:36:47 +00004239 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004240 continue;
4241
John McCall32daa422010-03-31 01:36:47 +00004242 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004243 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00004244 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004245 VisibleQuals);
4246 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004247 }
4248 }
4249 }
4250}
4251
Douglas Gregor19b7b152009-08-24 13:43:27 +00004252/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4253/// the volatile- and non-volatile-qualified assignment operators for the
4254/// given type to the candidate set.
4255static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4256 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00004257 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004258 unsigned NumArgs,
4259 OverloadCandidateSet &CandidateSet) {
4260 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00004261
Douglas Gregor19b7b152009-08-24 13:43:27 +00004262 // T& operator=(T&, T)
4263 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4264 ParamTypes[1] = T;
4265 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4266 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004267
Douglas Gregor19b7b152009-08-24 13:43:27 +00004268 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4269 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00004270 ParamTypes[0]
4271 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00004272 ParamTypes[1] = T;
4273 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00004274 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00004275 }
4276}
Mike Stump1eb44332009-09-09 15:08:12 +00004277
Sebastian Redl9994a342009-10-25 17:03:50 +00004278/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4279/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004280static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4281 Qualifiers VRQuals;
4282 const RecordType *TyRec;
4283 if (const MemberPointerType *RHSMPType =
4284 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004285 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004286 else
4287 TyRec = ArgExpr->getType()->getAs<RecordType>();
4288 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004289 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004290 VRQuals.addVolatile();
4291 VRQuals.addRestrict();
4292 return VRQuals;
4293 }
4294
4295 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00004296 if (!ClassDecl->hasDefinition())
4297 return VRQuals;
4298
John McCalleec51cf2010-01-20 00:46:10 +00004299 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00004300 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004301
John McCalleec51cf2010-01-20 00:46:10 +00004302 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004303 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00004304 NamedDecl *D = I.getDecl();
4305 if (isa<UsingShadowDecl>(D))
4306 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4307 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004308 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4309 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4310 CanTy = ResTypeRef->getPointeeType();
4311 // Need to go down the pointer/mempointer chain and add qualifiers
4312 // as see them.
4313 bool done = false;
4314 while (!done) {
4315 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4316 CanTy = ResTypePtr->getPointeeType();
4317 else if (const MemberPointerType *ResTypeMPtr =
4318 CanTy->getAs<MemberPointerType>())
4319 CanTy = ResTypeMPtr->getPointeeType();
4320 else
4321 done = true;
4322 if (CanTy.isVolatileQualified())
4323 VRQuals.addVolatile();
4324 if (CanTy.isRestrictQualified())
4325 VRQuals.addRestrict();
4326 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4327 return VRQuals;
4328 }
4329 }
4330 }
4331 return VRQuals;
4332}
4333
Douglas Gregor74253732008-11-19 15:42:04 +00004334/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4335/// operator overloads to the candidate set (C++ [over.built]), based
4336/// on the operator @p Op and the arguments given. For example, if the
4337/// operator is a binary '+', this routine might add "int
4338/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004339void
Mike Stump1eb44332009-09-09 15:08:12 +00004340Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004341 SourceLocation OpLoc,
Douglas Gregor74253732008-11-19 15:42:04 +00004342 Expr **Args, unsigned NumArgs,
4343 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004344 // The set of "promoted arithmetic types", which are the arithmetic
4345 // types are that preserved by promotion (C++ [over.built]p2). Note
4346 // that the first few of these types are the promoted integral
4347 // types; these types need to be first.
4348 // FIXME: What about complex?
4349 const unsigned FirstIntegralType = 0;
4350 const unsigned LastIntegralType = 13;
Mike Stump1eb44332009-09-09 15:08:12 +00004351 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004352 LastPromotedIntegralType = 13;
4353 const unsigned FirstPromotedArithmeticType = 7,
4354 LastPromotedArithmeticType = 16;
4355 const unsigned NumArithmeticTypes = 16;
4356 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump1eb44332009-09-09 15:08:12 +00004357 Context.BoolTy, Context.CharTy, Context.WCharTy,
4358// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004359 Context.SignedCharTy, Context.ShortTy,
4360 Context.UnsignedCharTy, Context.UnsignedShortTy,
4361 Context.IntTy, Context.LongTy, Context.LongLongTy,
4362 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
4363 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
4364 };
Douglas Gregor652371a2009-10-21 22:01:30 +00004365 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
4366 "Invalid first promoted integral type");
4367 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4368 == Context.UnsignedLongLongTy &&
4369 "Invalid last promoted integral type");
4370 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
4371 "Invalid first promoted arithmetic type");
4372 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4373 == Context.LongDoubleTy &&
4374 "Invalid last promoted arithmetic type");
4375
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004376 // Find all of the types that the arguments can convert to, but only
4377 // if the operator we're looking at has built-in operator candidates
4378 // that make use of these types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004379 Qualifiers VisibleTypeConversionsQuals;
4380 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004381 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4382 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4383
Douglas Gregor5842ba92009-08-24 15:23:48 +00004384 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004385 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4386 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4387 OpLoc,
4388 true,
4389 (Op == OO_Exclaim ||
4390 Op == OO_AmpAmp ||
4391 Op == OO_PipePipe),
4392 VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004393
4394 bool isComparison = false;
4395 switch (Op) {
4396 case OO_None:
4397 case NUM_OVERLOADED_OPERATORS:
4398 assert(false && "Expected an overloaded operator");
4399 break;
4400
Douglas Gregor74253732008-11-19 15:42:04 +00004401 case OO_Star: // '*' is either unary or binary
Mike Stump1eb44332009-09-09 15:08:12 +00004402 if (NumArgs == 1)
Douglas Gregor74253732008-11-19 15:42:04 +00004403 goto UnaryStar;
4404 else
4405 goto BinaryStar;
4406 break;
4407
4408 case OO_Plus: // '+' is either unary or binary
4409 if (NumArgs == 1)
4410 goto UnaryPlus;
4411 else
4412 goto BinaryPlus;
4413 break;
4414
4415 case OO_Minus: // '-' is either unary or binary
4416 if (NumArgs == 1)
4417 goto UnaryMinus;
4418 else
4419 goto BinaryMinus;
4420 break;
4421
4422 case OO_Amp: // '&' is either unary or binary
4423 if (NumArgs == 1)
4424 goto UnaryAmp;
4425 else
4426 goto BinaryAmp;
4427
4428 case OO_PlusPlus:
4429 case OO_MinusMinus:
4430 // C++ [over.built]p3:
4431 //
4432 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4433 // is either volatile or empty, there exist candidate operator
4434 // functions of the form
4435 //
4436 // VQ T& operator++(VQ T&);
4437 // T operator++(VQ T&, int);
4438 //
4439 // C++ [over.built]p4:
4440 //
4441 // For every pair (T, VQ), where T is an arithmetic type other
4442 // than bool, and VQ is either volatile or empty, there exist
4443 // candidate operator functions of the form
4444 //
4445 // VQ T& operator--(VQ T&);
4446 // T operator--(VQ T&, int);
Mike Stump1eb44332009-09-09 15:08:12 +00004447 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor74253732008-11-19 15:42:04 +00004448 Arith < NumArithmeticTypes; ++Arith) {
4449 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump1eb44332009-09-09 15:08:12 +00004450 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004451 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00004452
4453 // Non-volatile version.
4454 if (NumArgs == 1)
4455 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4456 else
4457 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004458 // heuristic to reduce number of builtin candidates in the set.
4459 // Add volatile version only if there are conversions to a volatile type.
4460 if (VisibleTypeConversionsQuals.hasVolatile()) {
4461 // Volatile version
4462 ParamTypes[0]
4463 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4464 if (NumArgs == 1)
4465 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4466 else
4467 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4468 }
Douglas Gregor74253732008-11-19 15:42:04 +00004469 }
4470
4471 // C++ [over.built]p5:
4472 //
4473 // For every pair (T, VQ), where T is a cv-qualified or
4474 // cv-unqualified object type, and VQ is either volatile or
4475 // empty, there exist candidate operator functions of the form
4476 //
4477 // T*VQ& operator++(T*VQ&);
4478 // T*VQ& operator--(T*VQ&);
4479 // T* operator++(T*VQ&, int);
4480 // T* operator--(T*VQ&, int);
4481 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4482 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4483 // Skip pointer types that aren't pointers to object types.
Ted Kremenek6217b802009-07-29 21:53:49 +00004484 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00004485 continue;
4486
Mike Stump1eb44332009-09-09 15:08:12 +00004487 QualType ParamTypes[2] = {
4488 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00004489 };
Mike Stump1eb44332009-09-09 15:08:12 +00004490
Douglas Gregor74253732008-11-19 15:42:04 +00004491 // Without volatile
4492 if (NumArgs == 1)
4493 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4494 else
4495 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4496
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004497 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4498 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00004499 // With volatile
John McCall0953e762009-09-24 19:53:00 +00004500 ParamTypes[0]
4501 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor74253732008-11-19 15:42:04 +00004502 if (NumArgs == 1)
4503 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4504 else
4505 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4506 }
4507 }
4508 break;
4509
4510 UnaryStar:
4511 // C++ [over.built]p6:
4512 // For every cv-qualified or cv-unqualified object type T, there
4513 // exist candidate operator functions of the form
4514 //
4515 // T& operator*(T*);
4516 //
4517 // C++ [over.built]p7:
4518 // For every function type T, there exist candidate operator
4519 // functions of the form
4520 // T& operator*(T*);
4521 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4522 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4523 QualType ParamTy = *Ptr;
Ted Kremenek6217b802009-07-29 21:53:49 +00004524 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004525 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00004526 &ParamTy, Args, 1, CandidateSet);
4527 }
4528 break;
4529
4530 UnaryPlus:
4531 // C++ [over.built]p8:
4532 // For every type T, there exist candidate operator functions of
4533 // the form
4534 //
4535 // T* operator+(T*);
4536 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4537 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4538 QualType ParamTy = *Ptr;
4539 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4540 }
Mike Stump1eb44332009-09-09 15:08:12 +00004541
Douglas Gregor74253732008-11-19 15:42:04 +00004542 // Fall through
4543
4544 UnaryMinus:
4545 // C++ [over.built]p9:
4546 // For every promoted arithmetic type T, there exist candidate
4547 // operator functions of the form
4548 //
4549 // T operator+(T);
4550 // T operator-(T);
Mike Stump1eb44332009-09-09 15:08:12 +00004551 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor74253732008-11-19 15:42:04 +00004552 Arith < LastPromotedArithmeticType; ++Arith) {
4553 QualType ArithTy = ArithmeticTypes[Arith];
4554 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4555 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004556
4557 // Extension: We also add these operators for vector types.
4558 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4559 VecEnd = CandidateTypes.vector_end();
4560 Vec != VecEnd; ++Vec) {
4561 QualType VecTy = *Vec;
4562 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4563 }
Douglas Gregor74253732008-11-19 15:42:04 +00004564 break;
4565
4566 case OO_Tilde:
4567 // C++ [over.built]p10:
4568 // For every promoted integral type T, there exist candidate
4569 // operator functions of the form
4570 //
4571 // T operator~(T);
Mike Stump1eb44332009-09-09 15:08:12 +00004572 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor74253732008-11-19 15:42:04 +00004573 Int < LastPromotedIntegralType; ++Int) {
4574 QualType IntTy = ArithmeticTypes[Int];
4575 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4576 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004577
4578 // Extension: We also add this operator for vector types.
4579 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4580 VecEnd = CandidateTypes.vector_end();
4581 Vec != VecEnd; ++Vec) {
4582 QualType VecTy = *Vec;
4583 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4584 }
Douglas Gregor74253732008-11-19 15:42:04 +00004585 break;
4586
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004587 case OO_New:
4588 case OO_Delete:
4589 case OO_Array_New:
4590 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004591 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00004592 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004593 break;
4594
4595 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00004596 UnaryAmp:
4597 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004598 // C++ [over.match.oper]p3:
4599 // -- For the operator ',', the unary operator '&', or the
4600 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004601 break;
4602
Douglas Gregor19b7b152009-08-24 13:43:27 +00004603 case OO_EqualEqual:
4604 case OO_ExclaimEqual:
4605 // C++ [over.match.oper]p16:
Mike Stump1eb44332009-09-09 15:08:12 +00004606 // For every pointer to member type T, there exist candidate operator
4607 // functions of the form
Douglas Gregor19b7b152009-08-24 13:43:27 +00004608 //
4609 // bool operator==(T,T);
4610 // bool operator!=(T,T);
Mike Stump1eb44332009-09-09 15:08:12 +00004611 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor19b7b152009-08-24 13:43:27 +00004612 MemPtr = CandidateTypes.member_pointer_begin(),
4613 MemPtrEnd = CandidateTypes.member_pointer_end();
4614 MemPtr != MemPtrEnd;
4615 ++MemPtr) {
4616 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4617 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4618 }
Mike Stump1eb44332009-09-09 15:08:12 +00004619
Douglas Gregor19b7b152009-08-24 13:43:27 +00004620 // Fall through
Mike Stump1eb44332009-09-09 15:08:12 +00004621
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004622 case OO_Less:
4623 case OO_Greater:
4624 case OO_LessEqual:
4625 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004626 // C++ [over.built]p15:
4627 //
4628 // For every pointer or enumeration type T, there exist
4629 // candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004630 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004631 // bool operator<(T, T);
4632 // bool operator>(T, T);
4633 // bool operator<=(T, T);
4634 // bool operator>=(T, T);
4635 // bool operator==(T, T);
4636 // bool operator!=(T, T);
4637 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4638 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4639 QualType ParamTypes[2] = { *Ptr, *Ptr };
4640 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4641 }
Mike Stump1eb44332009-09-09 15:08:12 +00004642 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004643 = CandidateTypes.enumeration_begin();
4644 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4645 QualType ParamTypes[2] = { *Enum, *Enum };
4646 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4647 }
4648
4649 // Fall through.
4650 isComparison = true;
4651
Douglas Gregor74253732008-11-19 15:42:04 +00004652 BinaryPlus:
4653 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004654 if (!isComparison) {
4655 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4656
4657 // C++ [over.built]p13:
4658 //
4659 // For every cv-qualified or cv-unqualified object type T
4660 // there exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004661 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004662 // T* operator+(T*, ptrdiff_t);
4663 // T& operator[](T*, ptrdiff_t); [BELOW]
4664 // T* operator-(T*, ptrdiff_t);
4665 // T* operator+(ptrdiff_t, T*);
4666 // T& operator[](ptrdiff_t, T*); [BELOW]
4667 //
4668 // C++ [over.built]p14:
4669 //
4670 // For every T, where T is a pointer to object type, there
4671 // exist candidate operator functions of the form
4672 //
4673 // ptrdiff_t operator-(T, T);
Mike Stump1eb44332009-09-09 15:08:12 +00004674 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004675 = CandidateTypes.pointer_begin();
4676 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4677 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4678
4679 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4680 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4681
4682 if (Op == OO_Plus) {
4683 // T* operator+(ptrdiff_t, T*);
4684 ParamTypes[0] = ParamTypes[1];
4685 ParamTypes[1] = *Ptr;
4686 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4687 } else {
4688 // ptrdiff_t operator-(T, T);
4689 ParamTypes[1] = *Ptr;
4690 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4691 Args, 2, CandidateSet);
4692 }
4693 }
4694 }
4695 // Fall through
4696
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004697 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00004698 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004699 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004700 // C++ [over.built]p12:
4701 //
4702 // For every pair of promoted arithmetic types L and R, there
4703 // exist candidate operator functions of the form
4704 //
4705 // LR operator*(L, R);
4706 // LR operator/(L, R);
4707 // LR operator+(L, R);
4708 // LR operator-(L, R);
4709 // bool operator<(L, R);
4710 // bool operator>(L, R);
4711 // bool operator<=(L, R);
4712 // bool operator>=(L, R);
4713 // bool operator==(L, R);
4714 // bool operator!=(L, R);
4715 //
4716 // where LR is the result of the usual arithmetic conversions
4717 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004718 //
4719 // C++ [over.built]p24:
4720 //
4721 // For every pair of promoted arithmetic types L and R, there exist
4722 // candidate operator functions of the form
4723 //
4724 // LR operator?(bool, L, R);
4725 //
4726 // where LR is the result of the usual arithmetic conversions
4727 // between types L and R.
4728 // Our candidates ignore the first parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00004729 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004730 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004731 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004732 Right < LastPromotedArithmeticType; ++Right) {
4733 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00004734 QualType Result
4735 = isComparison
4736 ? Context.BoolTy
4737 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004738 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4739 }
4740 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004741
4742 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
4743 // conditional operator for vector types.
4744 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4745 Vec1End = CandidateTypes.vector_end();
4746 Vec1 != Vec1End; ++Vec1)
4747 for (BuiltinCandidateTypeSet::iterator
4748 Vec2 = CandidateTypes.vector_begin(),
4749 Vec2End = CandidateTypes.vector_end();
4750 Vec2 != Vec2End; ++Vec2) {
4751 QualType LandR[2] = { *Vec1, *Vec2 };
4752 QualType Result;
4753 if (isComparison)
4754 Result = Context.BoolTy;
4755 else {
4756 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
4757 Result = *Vec1;
4758 else
4759 Result = *Vec2;
4760 }
4761
4762 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4763 }
4764
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004765 break;
4766
4767 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00004768 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004769 case OO_Caret:
4770 case OO_Pipe:
4771 case OO_LessLess:
4772 case OO_GreaterGreater:
4773 // C++ [over.built]p17:
4774 //
4775 // For every pair of promoted integral types L and R, there
4776 // exist candidate operator functions of the form
4777 //
4778 // LR operator%(L, R);
4779 // LR operator&(L, R);
4780 // LR operator^(L, R);
4781 // LR operator|(L, R);
4782 // L operator<<(L, R);
4783 // L operator>>(L, R);
4784 //
4785 // where LR is the result of the usual arithmetic conversions
4786 // between types L and R.
Mike Stump1eb44332009-09-09 15:08:12 +00004787 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004788 Left < LastPromotedIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004789 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004790 Right < LastPromotedIntegralType; ++Right) {
4791 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4792 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4793 ? LandR[0]
Eli Friedmana95d7572009-08-19 07:44:53 +00004794 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004795 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4796 }
4797 }
4798 break;
4799
4800 case OO_Equal:
4801 // C++ [over.built]p20:
4802 //
4803 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00004804 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004805 // empty, there exist candidate operator functions of the form
4806 //
4807 // VQ T& operator=(VQ T&, T);
Douglas Gregor19b7b152009-08-24 13:43:27 +00004808 for (BuiltinCandidateTypeSet::iterator
4809 Enum = CandidateTypes.enumeration_begin(),
4810 EnumEnd = CandidateTypes.enumeration_end();
4811 Enum != EnumEnd; ++Enum)
Mike Stump1eb44332009-09-09 15:08:12 +00004812 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004813 CandidateSet);
4814 for (BuiltinCandidateTypeSet::iterator
4815 MemPtr = CandidateTypes.member_pointer_begin(),
4816 MemPtrEnd = CandidateTypes.member_pointer_end();
4817 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump1eb44332009-09-09 15:08:12 +00004818 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004819 CandidateSet);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004820
4821 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004822
4823 case OO_PlusEqual:
4824 case OO_MinusEqual:
4825 // C++ [over.built]p19:
4826 //
4827 // For every pair (T, VQ), where T is any type and VQ is either
4828 // volatile or empty, there exist candidate operator functions
4829 // of the form
4830 //
4831 // T*VQ& operator=(T*VQ&, T*);
4832 //
4833 // C++ [over.built]p21:
4834 //
4835 // For every pair (T, VQ), where T is a cv-qualified or
4836 // cv-unqualified object type and VQ is either volatile or
4837 // empty, there exist candidate operator functions of the form
4838 //
4839 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4840 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4841 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4842 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4843 QualType ParamTypes[2];
4844 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4845
4846 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004847 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004848 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4849 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004850
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004851 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4852 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00004853 // volatile version
John McCall0953e762009-09-24 19:53:00 +00004854 ParamTypes[0]
4855 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004856 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4857 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00004858 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004859 }
4860 // Fall through.
4861
4862 case OO_StarEqual:
4863 case OO_SlashEqual:
4864 // C++ [over.built]p18:
4865 //
4866 // For every triple (L, VQ, R), where L is an arithmetic type,
4867 // VQ is either volatile or empty, and R is a promoted
4868 // arithmetic type, there exist candidate operator functions of
4869 // the form
4870 //
4871 // VQ L& operator=(VQ L&, R);
4872 // VQ L& operator*=(VQ L&, R);
4873 // VQ L& operator/=(VQ L&, R);
4874 // VQ L& operator+=(VQ L&, R);
4875 // VQ L& operator-=(VQ L&, R);
4876 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004877 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004878 Right < LastPromotedArithmeticType; ++Right) {
4879 QualType ParamTypes[2];
4880 ParamTypes[1] = ArithmeticTypes[Right];
4881
4882 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004883 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004884 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4885 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004886
4887 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004888 if (VisibleTypeConversionsQuals.hasVolatile()) {
4889 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4890 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4891 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4892 /*IsAssigmentOperator=*/Op == OO_Equal);
4893 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004894 }
4895 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004896
4897 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
4898 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4899 Vec1End = CandidateTypes.vector_end();
4900 Vec1 != Vec1End; ++Vec1)
4901 for (BuiltinCandidateTypeSet::iterator
4902 Vec2 = CandidateTypes.vector_begin(),
4903 Vec2End = CandidateTypes.vector_end();
4904 Vec2 != Vec2End; ++Vec2) {
4905 QualType ParamTypes[2];
4906 ParamTypes[1] = *Vec2;
4907 // Add this built-in operator as a candidate (VQ is empty).
4908 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
4909 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4910 /*IsAssigmentOperator=*/Op == OO_Equal);
4911
4912 // Add this built-in operator as a candidate (VQ is 'volatile').
4913 if (VisibleTypeConversionsQuals.hasVolatile()) {
4914 ParamTypes[0] = Context.getVolatileType(*Vec1);
4915 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4916 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4917 /*IsAssigmentOperator=*/Op == OO_Equal);
4918 }
4919 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004920 break;
4921
4922 case OO_PercentEqual:
4923 case OO_LessLessEqual:
4924 case OO_GreaterGreaterEqual:
4925 case OO_AmpEqual:
4926 case OO_CaretEqual:
4927 case OO_PipeEqual:
4928 // C++ [over.built]p22:
4929 //
4930 // For every triple (L, VQ, R), where L is an integral type, VQ
4931 // is either volatile or empty, and R is a promoted integral
4932 // type, there exist candidate operator functions of the form
4933 //
4934 // VQ L& operator%=(VQ L&, R);
4935 // VQ L& operator<<=(VQ L&, R);
4936 // VQ L& operator>>=(VQ L&, R);
4937 // VQ L& operator&=(VQ L&, R);
4938 // VQ L& operator^=(VQ L&, R);
4939 // VQ L& operator|=(VQ L&, R);
4940 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004941 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004942 Right < LastPromotedIntegralType; ++Right) {
4943 QualType ParamTypes[2];
4944 ParamTypes[1] = ArithmeticTypes[Right];
4945
4946 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004947 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004948 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian035c46f2009-10-20 00:04:40 +00004949 if (VisibleTypeConversionsQuals.hasVolatile()) {
4950 // Add this built-in operator as a candidate (VQ is 'volatile').
4951 ParamTypes[0] = ArithmeticTypes[Left];
4952 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4953 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4954 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4955 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004956 }
4957 }
4958 break;
4959
Douglas Gregor74253732008-11-19 15:42:04 +00004960 case OO_Exclaim: {
4961 // C++ [over.operator]p23:
4962 //
4963 // There also exist candidate operator functions of the form
4964 //
Mike Stump1eb44332009-09-09 15:08:12 +00004965 // bool operator!(bool);
Douglas Gregor74253732008-11-19 15:42:04 +00004966 // bool operator&&(bool, bool); [BELOW]
4967 // bool operator||(bool, bool); [BELOW]
4968 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004969 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4970 /*IsAssignmentOperator=*/false,
4971 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00004972 break;
4973 }
4974
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004975 case OO_AmpAmp:
4976 case OO_PipePipe: {
4977 // C++ [over.operator]p23:
4978 //
4979 // There also exist candidate operator functions of the form
4980 //
Douglas Gregor74253732008-11-19 15:42:04 +00004981 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004982 // bool operator&&(bool, bool);
4983 // bool operator||(bool, bool);
4984 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004985 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4986 /*IsAssignmentOperator=*/false,
4987 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004988 break;
4989 }
4990
4991 case OO_Subscript:
4992 // C++ [over.built]p13:
4993 //
4994 // For every cv-qualified or cv-unqualified object type T there
4995 // exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004996 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004997 // T* operator+(T*, ptrdiff_t); [ABOVE]
4998 // T& operator[](T*, ptrdiff_t);
4999 // T* operator-(T*, ptrdiff_t); [ABOVE]
5000 // T* operator+(ptrdiff_t, T*); [ABOVE]
5001 // T& operator[](ptrdiff_t, T*);
5002 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
5003 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5004 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenek6217b802009-07-29 21:53:49 +00005005 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005006 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005007
5008 // T& operator[](T*, ptrdiff_t)
5009 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5010
5011 // T& operator[](ptrdiff_t, T*);
5012 ParamTypes[0] = ParamTypes[1];
5013 ParamTypes[1] = *Ptr;
5014 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregor26bcf672010-05-19 03:21:00 +00005015 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005016 break;
5017
5018 case OO_ArrowStar:
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005019 // C++ [over.built]p11:
5020 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5021 // C1 is the same type as C2 or is a derived class of C2, T is an object
5022 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5023 // there exist candidate operator functions of the form
5024 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5025 // where CV12 is the union of CV1 and CV2.
5026 {
5027 for (BuiltinCandidateTypeSet::iterator Ptr =
5028 CandidateTypes.pointer_begin();
5029 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5030 QualType C1Ty = (*Ptr);
5031 QualType C1;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00005032 QualifierCollector Q1;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005033 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00005034 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005035 if (!isa<RecordType>(C1))
5036 continue;
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005037 // heuristic to reduce number of builtin candidates in the set.
5038 // Add volatile/restrict version only if there are conversions to a
5039 // volatile/restrict type.
5040 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5041 continue;
5042 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5043 continue;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005044 }
5045 for (BuiltinCandidateTypeSet::iterator
5046 MemPtr = CandidateTypes.member_pointer_begin(),
5047 MemPtrEnd = CandidateTypes.member_pointer_end();
5048 MemPtr != MemPtrEnd; ++MemPtr) {
5049 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5050 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian43036972009-10-07 16:56:50 +00005051 C2 = C2.getUnqualifiedType();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005052 if (C1 != C2 && !IsDerivedFrom(C1, C2))
5053 break;
5054 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5055 // build CV12 T&
5056 QualType T = mptr->getPointeeType();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005057 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5058 T.isVolatileQualified())
5059 continue;
5060 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5061 T.isRestrictQualified())
5062 continue;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00005063 T = Q1.apply(T);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005064 QualType ResultTy = Context.getLValueReferenceType(T);
5065 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5066 }
5067 }
5068 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005069 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005070
5071 case OO_Conditional:
5072 // Note that we don't consider the first argument, since it has been
5073 // contextually converted to bool long ago. The candidates below are
5074 // therefore added as binary.
5075 //
5076 // C++ [over.built]p24:
5077 // For every type T, where T is a pointer or pointer-to-member type,
5078 // there exist candidate operator functions of the form
5079 //
5080 // T operator?(bool, T, T);
5081 //
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005082 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
5083 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
5084 QualType ParamTypes[2] = { *Ptr, *Ptr };
5085 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5086 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00005087 for (BuiltinCandidateTypeSet::iterator Ptr =
5088 CandidateTypes.member_pointer_begin(),
5089 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
5090 QualType ParamTypes[2] = { *Ptr, *Ptr };
5091 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5092 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005093 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005094 }
5095}
5096
Douglas Gregorfa047642009-02-04 00:32:51 +00005097/// \brief Add function candidates found via argument-dependent lookup
5098/// to the set of overloading candidates.
5099///
5100/// This routine performs argument-dependent name lookup based on the
5101/// given function name (which may also be an operator name) and adds
5102/// all of the overload candidates found by ADL to the overload
5103/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00005104void
Douglas Gregorfa047642009-02-04 00:32:51 +00005105Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00005106 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00005107 Expr **Args, unsigned NumArgs,
John McCalld5532b62009-11-23 01:53:49 +00005108 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005109 OverloadCandidateSet& CandidateSet,
5110 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00005111 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00005112
John McCalla113e722010-01-26 06:04:06 +00005113 // FIXME: This approach for uniquing ADL results (and removing
5114 // redundant candidates from the set) relies on pointer-equality,
5115 // which means we need to key off the canonical decl. However,
5116 // always going back to the canonical decl might not get us the
5117 // right set of default arguments. What default arguments are
5118 // we supposed to consider on ADL candidates, anyway?
5119
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005120 // FIXME: Pass in the explicit template arguments?
John McCall7edb5fd2010-01-26 07:16:45 +00005121 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00005122
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005123 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005124 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5125 CandEnd = CandidateSet.end();
5126 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00005127 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00005128 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00005129 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00005130 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00005131 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005132
5133 // For each of the ADL candidates we found, add it to the overload
5134 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00005135 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00005136 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00005137 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00005138 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005139 continue;
5140
John McCall9aa472c2010-03-19 07:35:19 +00005141 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00005142 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005143 } else
John McCall6e266892010-01-26 03:27:55 +00005144 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00005145 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00005146 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00005147 }
Douglas Gregorfa047642009-02-04 00:32:51 +00005148}
5149
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005150/// isBetterOverloadCandidate - Determines whether the first overload
5151/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00005152bool
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005153Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCall5769d612010-02-08 23:07:23 +00005154 const OverloadCandidate& Cand2,
5155 SourceLocation Loc) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005156 // Define viable functions to be better candidates than non-viable
5157 // functions.
5158 if (!Cand2.Viable)
5159 return Cand1.Viable;
5160 else if (!Cand1.Viable)
5161 return false;
5162
Douglas Gregor88a35142008-12-22 05:46:06 +00005163 // C++ [over.match.best]p1:
5164 //
5165 // -- if F is a static member function, ICS1(F) is defined such
5166 // that ICS1(F) is neither better nor worse than ICS1(G) for
5167 // any function G, and, symmetrically, ICS1(G) is neither
5168 // better nor worse than ICS1(F).
5169 unsigned StartArg = 0;
5170 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5171 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005172
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005173 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00005174 // A viable function F1 is defined to be a better function than another
5175 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005176 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005177 unsigned NumArgs = Cand1.Conversions.size();
5178 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5179 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005180 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005181 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
5182 Cand2.Conversions[ArgIdx])) {
5183 case ImplicitConversionSequence::Better:
5184 // Cand1 has a better conversion sequence.
5185 HasBetterConversion = true;
5186 break;
5187
5188 case ImplicitConversionSequence::Worse:
5189 // Cand1 can't be better than Cand2.
5190 return false;
5191
5192 case ImplicitConversionSequence::Indistinguishable:
5193 // Do nothing.
5194 break;
5195 }
5196 }
5197
Mike Stump1eb44332009-09-09 15:08:12 +00005198 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005199 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005200 if (HasBetterConversion)
5201 return true;
5202
Mike Stump1eb44332009-09-09 15:08:12 +00005203 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005204 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00005205 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005206 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5207 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005208
5209 // -- F1 and F2 are function template specializations, and the function
5210 // template for F1 is more specialized than the template for F2
5211 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005212 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00005213 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5214 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005215 if (FunctionTemplateDecl *BetterTemplate
5216 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5217 Cand2.Function->getPrimaryTemplate(),
John McCall5769d612010-02-08 23:07:23 +00005218 Loc,
Douglas Gregor5d7d3752009-09-14 23:02:14 +00005219 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5220 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005221 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005222
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005223 // -- the context is an initialization by user-defined conversion
5224 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5225 // from the return type of F1 to the destination type (i.e.,
5226 // the type of the entity being initialized) is a better
5227 // conversion sequence than the standard conversion sequence
5228 // from the return type of F2 to the destination type.
Mike Stump1eb44332009-09-09 15:08:12 +00005229 if (Cand1.Function && Cand2.Function &&
5230 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005231 isa<CXXConversionDecl>(Cand2.Function)) {
5232 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
5233 Cand2.FinalConversion)) {
5234 case ImplicitConversionSequence::Better:
5235 // Cand1 has a better conversion sequence.
5236 return true;
5237
5238 case ImplicitConversionSequence::Worse:
5239 // Cand1 can't be better than Cand2.
5240 return false;
5241
5242 case ImplicitConversionSequence::Indistinguishable:
5243 // Do nothing
5244 break;
5245 }
5246 }
5247
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005248 return false;
5249}
5250
Mike Stump1eb44332009-09-09 15:08:12 +00005251/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00005252/// within an overload candidate set.
5253///
5254/// \param CandidateSet the set of candidate functions.
5255///
5256/// \param Loc the location of the function name (or operator symbol) for
5257/// which overload resolution occurs.
5258///
Mike Stump1eb44332009-09-09 15:08:12 +00005259/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00005260/// function, Best points to the candidate function found.
5261///
5262/// \returns The result of overload resolution.
Douglas Gregor20093b42009-12-09 23:02:17 +00005263OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
5264 SourceLocation Loc,
5265 OverloadCandidateSet::iterator& Best) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005266 // Find the best viable function.
5267 Best = CandidateSet.end();
5268 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5269 Cand != CandidateSet.end(); ++Cand) {
5270 if (Cand->Viable) {
John McCall5769d612010-02-08 23:07:23 +00005271 if (Best == CandidateSet.end() ||
5272 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005273 Best = Cand;
5274 }
5275 }
5276
5277 // If we didn't find any viable functions, abort.
5278 if (Best == CandidateSet.end())
5279 return OR_No_Viable_Function;
5280
5281 // Make sure that this function is better than every other viable
5282 // function. If not, we have an ambiguity.
5283 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5284 Cand != CandidateSet.end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00005285 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005286 Cand != Best &&
John McCall5769d612010-02-08 23:07:23 +00005287 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005288 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005289 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005290 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005291 }
Mike Stump1eb44332009-09-09 15:08:12 +00005292
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005293 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005294 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00005295 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005296 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005297 return OR_Deleted;
5298
Douglas Gregore0762c92009-06-19 23:52:42 +00005299 // C++ [basic.def.odr]p2:
5300 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00005301 // when referred to from a potentially-evaluated expression. [Note: this
5302 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00005303 // (clause 13), user-defined conversions (12.3.2), allocation function for
5304 // placement new (5.3.4), as well as non-default initialization (8.5).
5305 if (Best->Function)
5306 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005307 return OR_Success;
5308}
5309
John McCall3c80f572010-01-12 02:15:36 +00005310namespace {
5311
5312enum OverloadCandidateKind {
5313 oc_function,
5314 oc_method,
5315 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00005316 oc_function_template,
5317 oc_method_template,
5318 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00005319 oc_implicit_default_constructor,
5320 oc_implicit_copy_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00005321 oc_implicit_copy_assignment
John McCall3c80f572010-01-12 02:15:36 +00005322};
5323
John McCall220ccbf2010-01-13 00:25:19 +00005324OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5325 FunctionDecl *Fn,
5326 std::string &Description) {
5327 bool isTemplate = false;
5328
5329 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5330 isTemplate = true;
5331 Description = S.getTemplateArgumentBindingsText(
5332 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5333 }
John McCallb1622a12010-01-06 09:43:14 +00005334
5335 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00005336 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00005337 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00005338
John McCall3c80f572010-01-12 02:15:36 +00005339 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5340 : oc_implicit_default_constructor;
John McCallb1622a12010-01-06 09:43:14 +00005341 }
5342
5343 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5344 // This actually gets spelled 'candidate function' for now, but
5345 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00005346 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00005347 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00005348
5349 assert(Meth->isCopyAssignment()
5350 && "implicit method is not copy assignment operator?");
John McCall3c80f572010-01-12 02:15:36 +00005351 return oc_implicit_copy_assignment;
5352 }
5353
John McCall220ccbf2010-01-13 00:25:19 +00005354 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00005355}
5356
5357} // end anonymous namespace
5358
5359// Notes the location of an overload candidate.
5360void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCall220ccbf2010-01-13 00:25:19 +00005361 std::string FnDesc;
5362 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5363 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5364 << (unsigned) K << FnDesc;
John McCallb1622a12010-01-06 09:43:14 +00005365}
5366
John McCall1d318332010-01-12 00:44:57 +00005367/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5368/// "lead" diagnostic; it will be given two arguments, the source and
5369/// target types of the conversion.
5370void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
5371 SourceLocation CaretLoc,
5372 const PartialDiagnostic &PDiag) {
5373 Diag(CaretLoc, PDiag)
5374 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
5375 for (AmbiguousConversionSequence::const_iterator
5376 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
5377 NoteOverloadCandidate(*I);
5378 }
John McCall81201622010-01-08 04:41:39 +00005379}
5380
John McCall1d318332010-01-12 00:44:57 +00005381namespace {
5382
John McCalladbb8f82010-01-13 09:16:55 +00005383void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5384 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5385 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00005386 assert(Cand->Function && "for now, candidate must be a function");
5387 FunctionDecl *Fn = Cand->Function;
5388
5389 // There's a conversion slot for the object argument if this is a
5390 // non-constructor method. Note that 'I' corresponds the
5391 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00005392 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00005393 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00005394 if (I == 0)
5395 isObjectArgument = true;
5396 else
5397 I--;
John McCall220ccbf2010-01-13 00:25:19 +00005398 }
5399
John McCall220ccbf2010-01-13 00:25:19 +00005400 std::string FnDesc;
5401 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5402
John McCalladbb8f82010-01-13 09:16:55 +00005403 Expr *FromExpr = Conv.Bad.FromExpr;
5404 QualType FromTy = Conv.Bad.getFromType();
5405 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00005406
John McCall5920dbb2010-02-02 02:42:52 +00005407 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00005408 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00005409 Expr *E = FromExpr->IgnoreParens();
5410 if (isa<UnaryOperator>(E))
5411 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00005412 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00005413
5414 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5415 << (unsigned) FnKind << FnDesc
5416 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5417 << ToTy << Name << I+1;
5418 return;
5419 }
5420
John McCall258b2032010-01-23 08:10:49 +00005421 // Do some hand-waving analysis to see if the non-viability is due
5422 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00005423 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5424 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5425 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5426 CToTy = RT->getPointeeType();
5427 else {
5428 // TODO: detect and diagnose the full richness of const mismatches.
5429 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5430 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5431 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5432 }
5433
5434 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5435 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5436 // It is dumb that we have to do this here.
5437 while (isa<ArrayType>(CFromTy))
5438 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5439 while (isa<ArrayType>(CToTy))
5440 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5441
5442 Qualifiers FromQs = CFromTy.getQualifiers();
5443 Qualifiers ToQs = CToTy.getQualifiers();
5444
5445 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5446 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5447 << (unsigned) FnKind << FnDesc
5448 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5449 << FromTy
5450 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5451 << (unsigned) isObjectArgument << I+1;
5452 return;
5453 }
5454
5455 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5456 assert(CVR && "unexpected qualifiers mismatch");
5457
5458 if (isObjectArgument) {
5459 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5460 << (unsigned) FnKind << FnDesc
5461 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5462 << FromTy << (CVR - 1);
5463 } else {
5464 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5465 << (unsigned) FnKind << FnDesc
5466 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5467 << FromTy << (CVR - 1) << I+1;
5468 }
5469 return;
5470 }
5471
John McCall258b2032010-01-23 08:10:49 +00005472 // Diagnose references or pointers to incomplete types differently,
5473 // since it's far from impossible that the incompleteness triggered
5474 // the failure.
5475 QualType TempFromTy = FromTy.getNonReferenceType();
5476 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5477 TempFromTy = PTy->getPointeeType();
5478 if (TempFromTy->isIncompleteType()) {
5479 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5480 << (unsigned) FnKind << FnDesc
5481 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5482 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5483 return;
5484 }
5485
Douglas Gregor85789812010-06-30 23:01:39 +00005486 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005487 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00005488 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
5489 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
5490 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5491 FromPtrTy->getPointeeType()) &&
5492 !FromPtrTy->getPointeeType()->isIncompleteType() &&
5493 !ToPtrTy->getPointeeType()->isIncompleteType() &&
5494 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
5495 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005496 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00005497 }
5498 } else if (const ObjCObjectPointerType *FromPtrTy
5499 = FromTy->getAs<ObjCObjectPointerType>()) {
5500 if (const ObjCObjectPointerType *ToPtrTy
5501 = ToTy->getAs<ObjCObjectPointerType>())
5502 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
5503 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
5504 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5505 FromPtrTy->getPointeeType()) &&
5506 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005507 BaseToDerivedConversion = 2;
5508 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
5509 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
5510 !FromTy->isIncompleteType() &&
5511 !ToRefTy->getPointeeType()->isIncompleteType() &&
5512 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
5513 BaseToDerivedConversion = 3;
5514 }
5515
5516 if (BaseToDerivedConversion) {
Douglas Gregor85789812010-06-30 23:01:39 +00005517 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005518 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00005519 << (unsigned) FnKind << FnDesc
5520 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005521 << (BaseToDerivedConversion - 1)
Douglas Gregor85789812010-06-30 23:01:39 +00005522 << FromTy << ToTy << I+1;
5523 return;
5524 }
5525
John McCall651f3ee2010-01-14 03:28:57 +00005526 // TODO: specialize more based on the kind of mismatch
John McCall220ccbf2010-01-13 00:25:19 +00005527 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5528 << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00005529 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalle81e15e2010-01-14 00:56:20 +00005530 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCalladbb8f82010-01-13 09:16:55 +00005531}
5532
5533void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5534 unsigned NumFormalArgs) {
5535 // TODO: treat calls to a missing default constructor as a special case
5536
5537 FunctionDecl *Fn = Cand->Function;
5538 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5539
5540 unsigned MinParams = Fn->getMinRequiredArguments();
5541
5542 // at least / at most / exactly
Douglas Gregora18592e2010-05-08 18:13:28 +00005543 // FIXME: variadic templates "at most" should account for parameter packs
John McCalladbb8f82010-01-13 09:16:55 +00005544 unsigned mode, modeCount;
5545 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00005546 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5547 (Cand->FailureKind == ovl_fail_bad_deduction &&
5548 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCalladbb8f82010-01-13 09:16:55 +00005549 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5550 mode = 0; // "at least"
5551 else
5552 mode = 2; // "exactly"
5553 modeCount = MinParams;
5554 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00005555 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5556 (Cand->FailureKind == ovl_fail_bad_deduction &&
5557 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00005558 if (MinParams != FnTy->getNumArgs())
5559 mode = 1; // "at most"
5560 else
5561 mode = 2; // "exactly"
5562 modeCount = FnTy->getNumArgs();
5563 }
5564
5565 std::string Description;
5566 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5567
5568 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregora18592e2010-05-08 18:13:28 +00005569 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5570 << modeCount << NumFormalArgs;
John McCall220ccbf2010-01-13 00:25:19 +00005571}
5572
John McCall342fec42010-02-01 18:53:26 +00005573/// Diagnose a failed template-argument deduction.
5574void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5575 Expr **Args, unsigned NumArgs) {
5576 FunctionDecl *Fn = Cand->Function; // pattern
5577
Douglas Gregora9333192010-05-08 17:41:32 +00005578 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00005579 NamedDecl *ParamD;
5580 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5581 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5582 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00005583 switch (Cand->DeductionFailure.Result) {
5584 case Sema::TDK_Success:
5585 llvm_unreachable("TDK_success while diagnosing bad deduction");
5586
5587 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00005588 assert(ParamD && "no parameter found for incomplete deduction result");
5589 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5590 << ParamD->getDeclName();
5591 return;
5592 }
5593
Douglas Gregora9333192010-05-08 17:41:32 +00005594 case Sema::TDK_Inconsistent:
5595 case Sema::TDK_InconsistentQuals: {
Douglas Gregorf1a84452010-05-08 19:15:54 +00005596 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00005597 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00005598 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00005599 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00005600 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00005601 which = 1;
5602 else {
Douglas Gregora9333192010-05-08 17:41:32 +00005603 which = 2;
5604 }
5605
5606 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5607 << which << ParamD->getDeclName()
5608 << *Cand->DeductionFailure.getFirstArg()
5609 << *Cand->DeductionFailure.getSecondArg();
5610 return;
5611 }
Douglas Gregora18592e2010-05-08 18:13:28 +00005612
Douglas Gregorf1a84452010-05-08 19:15:54 +00005613 case Sema::TDK_InvalidExplicitArguments:
5614 assert(ParamD && "no parameter found for invalid explicit arguments");
5615 if (ParamD->getDeclName())
5616 S.Diag(Fn->getLocation(),
5617 diag::note_ovl_candidate_explicit_arg_mismatch_named)
5618 << ParamD->getDeclName();
5619 else {
5620 int index = 0;
5621 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5622 index = TTP->getIndex();
5623 else if (NonTypeTemplateParmDecl *NTTP
5624 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5625 index = NTTP->getIndex();
5626 else
5627 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
5628 S.Diag(Fn->getLocation(),
5629 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
5630 << (index + 1);
5631 }
5632 return;
5633
Douglas Gregora18592e2010-05-08 18:13:28 +00005634 case Sema::TDK_TooManyArguments:
5635 case Sema::TDK_TooFewArguments:
5636 DiagnoseArityMismatch(S, Cand, NumArgs);
5637 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00005638
5639 case Sema::TDK_InstantiationDepth:
5640 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
5641 return;
5642
5643 case Sema::TDK_SubstitutionFailure: {
5644 std::string ArgString;
5645 if (TemplateArgumentList *Args
5646 = Cand->DeductionFailure.getTemplateArgumentList())
5647 ArgString = S.getTemplateArgumentBindingsText(
5648 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
5649 *Args);
5650 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
5651 << ArgString;
5652 return;
5653 }
Douglas Gregora9333192010-05-08 17:41:32 +00005654
John McCall342fec42010-02-01 18:53:26 +00005655 // TODO: diagnose these individually, then kill off
5656 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00005657 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00005658 case Sema::TDK_FailedOverloadResolution:
5659 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
5660 return;
5661 }
5662}
5663
5664/// Generates a 'note' diagnostic for an overload candidate. We've
5665/// already generated a primary error at the call site.
5666///
5667/// It really does need to be a single diagnostic with its caret
5668/// pointed at the candidate declaration. Yes, this creates some
5669/// major challenges of technical writing. Yes, this makes pointing
5670/// out problems with specific arguments quite awkward. It's still
5671/// better than generating twenty screens of text for every failed
5672/// overload.
5673///
5674/// It would be great to be able to express per-candidate problems
5675/// more richly for those diagnostic clients that cared, but we'd
5676/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00005677void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
5678 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00005679 FunctionDecl *Fn = Cand->Function;
5680
John McCall81201622010-01-08 04:41:39 +00005681 // Note deleted candidates, but only if they're viable.
John McCall3c80f572010-01-12 02:15:36 +00005682 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCall220ccbf2010-01-13 00:25:19 +00005683 std::string FnDesc;
5684 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00005685
5686 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00005687 << FnKind << FnDesc << Fn->isDeleted();
John McCalla1d7d622010-01-08 00:58:21 +00005688 return;
John McCall81201622010-01-08 04:41:39 +00005689 }
5690
John McCall220ccbf2010-01-13 00:25:19 +00005691 // We don't really have anything else to say about viable candidates.
5692 if (Cand->Viable) {
5693 S.NoteOverloadCandidate(Fn);
5694 return;
5695 }
John McCall1d318332010-01-12 00:44:57 +00005696
John McCalladbb8f82010-01-13 09:16:55 +00005697 switch (Cand->FailureKind) {
5698 case ovl_fail_too_many_arguments:
5699 case ovl_fail_too_few_arguments:
5700 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00005701
John McCalladbb8f82010-01-13 09:16:55 +00005702 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00005703 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5704
John McCall717e8912010-01-23 05:17:32 +00005705 case ovl_fail_trivial_conversion:
5706 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00005707 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00005708 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00005709
John McCallb1bdc622010-02-25 01:37:24 +00005710 case ovl_fail_bad_conversion: {
5711 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5712 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00005713 if (Cand->Conversions[I].isBad())
5714 return DiagnoseBadConversion(S, Cand, I);
5715
5716 // FIXME: this currently happens when we're called from SemaInit
5717 // when user-conversion overload fails. Figure out how to handle
5718 // those conditions and diagnose them well.
5719 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00005720 }
John McCallb1bdc622010-02-25 01:37:24 +00005721 }
John McCalla1d7d622010-01-08 00:58:21 +00005722}
5723
5724void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5725 // Desugar the type of the surrogate down to a function type,
5726 // retaining as many typedefs as possible while still showing
5727 // the function type (and, therefore, its parameter types).
5728 QualType FnType = Cand->Surrogate->getConversionType();
5729 bool isLValueReference = false;
5730 bool isRValueReference = false;
5731 bool isPointer = false;
5732 if (const LValueReferenceType *FnTypeRef =
5733 FnType->getAs<LValueReferenceType>()) {
5734 FnType = FnTypeRef->getPointeeType();
5735 isLValueReference = true;
5736 } else if (const RValueReferenceType *FnTypeRef =
5737 FnType->getAs<RValueReferenceType>()) {
5738 FnType = FnTypeRef->getPointeeType();
5739 isRValueReference = true;
5740 }
5741 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5742 FnType = FnTypePtr->getPointeeType();
5743 isPointer = true;
5744 }
5745 // Desugar down to a function type.
5746 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5747 // Reconstruct the pointer/reference as appropriate.
5748 if (isPointer) FnType = S.Context.getPointerType(FnType);
5749 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5750 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5751
5752 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5753 << FnType;
5754}
5755
5756void NoteBuiltinOperatorCandidate(Sema &S,
5757 const char *Opc,
5758 SourceLocation OpLoc,
5759 OverloadCandidate *Cand) {
5760 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5761 std::string TypeStr("operator");
5762 TypeStr += Opc;
5763 TypeStr += "(";
5764 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5765 if (Cand->Conversions.size() == 1) {
5766 TypeStr += ")";
5767 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5768 } else {
5769 TypeStr += ", ";
5770 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5771 TypeStr += ")";
5772 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5773 }
5774}
5775
5776void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5777 OverloadCandidate *Cand) {
5778 unsigned NoOperands = Cand->Conversions.size();
5779 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5780 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00005781 if (ICS.isBad()) break; // all meaningless after first invalid
5782 if (!ICS.isAmbiguous()) continue;
5783
5784 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005785 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00005786 }
5787}
5788
John McCall1b77e732010-01-15 23:32:50 +00005789SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5790 if (Cand->Function)
5791 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00005792 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00005793 return Cand->Surrogate->getLocation();
5794 return SourceLocation();
5795}
5796
John McCallbf65c0b2010-01-12 00:48:53 +00005797struct CompareOverloadCandidatesForDisplay {
5798 Sema &S;
5799 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00005800
5801 bool operator()(const OverloadCandidate *L,
5802 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00005803 // Fast-path this check.
5804 if (L == R) return false;
5805
John McCall81201622010-01-08 04:41:39 +00005806 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00005807 if (L->Viable) {
5808 if (!R->Viable) return true;
5809
5810 // TODO: introduce a tri-valued comparison for overload
5811 // candidates. Would be more worthwhile if we had a sort
5812 // that could exploit it.
John McCall5769d612010-02-08 23:07:23 +00005813 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5814 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00005815 } else if (R->Viable)
5816 return false;
John McCall81201622010-01-08 04:41:39 +00005817
John McCall1b77e732010-01-15 23:32:50 +00005818 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00005819
John McCall1b77e732010-01-15 23:32:50 +00005820 // Criteria by which we can sort non-viable candidates:
5821 if (!L->Viable) {
5822 // 1. Arity mismatches come after other candidates.
5823 if (L->FailureKind == ovl_fail_too_many_arguments ||
5824 L->FailureKind == ovl_fail_too_few_arguments)
5825 return false;
5826 if (R->FailureKind == ovl_fail_too_many_arguments ||
5827 R->FailureKind == ovl_fail_too_few_arguments)
5828 return true;
John McCall81201622010-01-08 04:41:39 +00005829
John McCall717e8912010-01-23 05:17:32 +00005830 // 2. Bad conversions come first and are ordered by the number
5831 // of bad conversions and quality of good conversions.
5832 if (L->FailureKind == ovl_fail_bad_conversion) {
5833 if (R->FailureKind != ovl_fail_bad_conversion)
5834 return true;
5835
5836 // If there's any ordering between the defined conversions...
5837 // FIXME: this might not be transitive.
5838 assert(L->Conversions.size() == R->Conversions.size());
5839
5840 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00005841 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5842 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall717e8912010-01-23 05:17:32 +00005843 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5844 R->Conversions[I])) {
5845 case ImplicitConversionSequence::Better:
5846 leftBetter++;
5847 break;
5848
5849 case ImplicitConversionSequence::Worse:
5850 leftBetter--;
5851 break;
5852
5853 case ImplicitConversionSequence::Indistinguishable:
5854 break;
5855 }
5856 }
5857 if (leftBetter > 0) return true;
5858 if (leftBetter < 0) return false;
5859
5860 } else if (R->FailureKind == ovl_fail_bad_conversion)
5861 return false;
5862
John McCall1b77e732010-01-15 23:32:50 +00005863 // TODO: others?
5864 }
5865
5866 // Sort everything else by location.
5867 SourceLocation LLoc = GetLocationForCandidate(L);
5868 SourceLocation RLoc = GetLocationForCandidate(R);
5869
5870 // Put candidates without locations (e.g. builtins) at the end.
5871 if (LLoc.isInvalid()) return false;
5872 if (RLoc.isInvalid()) return true;
5873
5874 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00005875 }
5876};
5877
John McCall717e8912010-01-23 05:17:32 +00005878/// CompleteNonViableCandidate - Normally, overload resolution only
5879/// computes up to the first
5880void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5881 Expr **Args, unsigned NumArgs) {
5882 assert(!Cand->Viable);
5883
5884 // Don't do anything on failures other than bad conversion.
5885 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5886
5887 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00005888 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCall717e8912010-01-23 05:17:32 +00005889 unsigned ConvCount = Cand->Conversions.size();
5890 while (true) {
5891 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5892 ConvIdx++;
5893 if (Cand->Conversions[ConvIdx - 1].isBad())
5894 break;
5895 }
5896
5897 if (ConvIdx == ConvCount)
5898 return;
5899
John McCallb1bdc622010-02-25 01:37:24 +00005900 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
5901 "remaining conversion is initialized?");
5902
Douglas Gregor23ef6c02010-04-16 17:45:54 +00005903 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00005904 // operation somehow.
5905 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00005906
5907 const FunctionProtoType* Proto;
5908 unsigned ArgIdx = ConvIdx;
5909
5910 if (Cand->IsSurrogate) {
5911 QualType ConvType
5912 = Cand->Surrogate->getConversionType().getNonReferenceType();
5913 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5914 ConvType = ConvPtrType->getPointeeType();
5915 Proto = ConvType->getAs<FunctionProtoType>();
5916 ArgIdx--;
5917 } else if (Cand->Function) {
5918 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
5919 if (isa<CXXMethodDecl>(Cand->Function) &&
5920 !isa<CXXConstructorDecl>(Cand->Function))
5921 ArgIdx--;
5922 } else {
5923 // Builtin binary operator with a bad first conversion.
5924 assert(ConvCount <= 3);
5925 for (; ConvIdx != ConvCount; ++ConvIdx)
5926 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005927 = TryCopyInitialization(S, Args[ConvIdx],
5928 Cand->BuiltinTypes.ParamTypes[ConvIdx],
5929 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00005930 /*InOverloadResolution*/ true);
John McCall717e8912010-01-23 05:17:32 +00005931 return;
5932 }
5933
5934 // Fill in the rest of the conversions.
5935 unsigned NumArgsInProto = Proto->getNumArgs();
5936 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
5937 if (ArgIdx < NumArgsInProto)
5938 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005939 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
5940 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00005941 /*InOverloadResolution=*/true);
John McCall717e8912010-01-23 05:17:32 +00005942 else
5943 Cand->Conversions[ConvIdx].setEllipsis();
5944 }
5945}
5946
John McCalla1d7d622010-01-08 00:58:21 +00005947} // end anonymous namespace
5948
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005949/// PrintOverloadCandidates - When overload resolution fails, prints
5950/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00005951/// set.
Mike Stump1eb44332009-09-09 15:08:12 +00005952void
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005953Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall81201622010-01-08 04:41:39 +00005954 OverloadCandidateDisplayKind OCD,
John McCallcbce6062010-01-12 07:18:19 +00005955 Expr **Args, unsigned NumArgs,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00005956 const char *Opc,
Fariborz Jahanian16a5eac2009-10-09 00:13:15 +00005957 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00005958 // Sort the candidates by viability and position. Sorting directly would
5959 // be prohibitive, so we make a set of pointers and sort those.
5960 llvm::SmallVector<OverloadCandidate*, 32> Cands;
5961 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
5962 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5963 LastCand = CandidateSet.end();
John McCall717e8912010-01-23 05:17:32 +00005964 Cand != LastCand; ++Cand) {
5965 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00005966 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00005967 else if (OCD == OCD_AllCandidates) {
5968 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00005969 if (Cand->Function || Cand->IsSurrogate)
5970 Cands.push_back(Cand);
5971 // Otherwise, this a non-viable builtin candidate. We do not, in general,
5972 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00005973 }
5974 }
5975
John McCallbf65c0b2010-01-12 00:48:53 +00005976 std::sort(Cands.begin(), Cands.end(),
5977 CompareOverloadCandidatesForDisplay(*this));
John McCall81201622010-01-08 04:41:39 +00005978
John McCall1d318332010-01-12 00:44:57 +00005979 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00005980
John McCall81201622010-01-08 04:41:39 +00005981 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00005982 const Diagnostic::OverloadsShown ShowOverloads = Diags.getShowOverloads();
5983 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00005984 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
5985 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00005986
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00005987 // Set an arbitrary limit on the number of candidate functions we'll spam
5988 // the user with. FIXME: This limit should depend on details of the
5989 // candidate list.
5990 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
5991 break;
5992 }
5993 ++CandsShown;
5994
John McCalla1d7d622010-01-08 00:58:21 +00005995 if (Cand->Function)
John McCall220ccbf2010-01-13 00:25:19 +00005996 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00005997 else if (Cand->IsSurrogate)
5998 NoteSurrogateCandidate(*this, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00005999 else {
6000 assert(Cand->Viable &&
6001 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00006002 // Generally we only see ambiguities including viable builtin
6003 // operators if overload resolution got screwed up by an
6004 // ambiguous user-defined conversion.
6005 //
6006 // FIXME: It's quite possible for different conversions to see
6007 // different ambiguities, though.
6008 if (!ReportedAmbiguousConversions) {
6009 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
6010 ReportedAmbiguousConversions = true;
6011 }
John McCalla1d7d622010-01-08 00:58:21 +00006012
John McCall1d318332010-01-12 00:44:57 +00006013 // If this is a viable builtin, print it.
John McCalla1d7d622010-01-08 00:58:21 +00006014 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006015 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006016 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006017
6018 if (I != E)
Jeffrey Yasskin258de302010-06-11 06:58:43 +00006019 Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006020}
6021
John McCall9aa472c2010-03-19 07:35:19 +00006022static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCallc373d482010-01-27 01:50:18 +00006023 if (isa<UnresolvedLookupExpr>(E))
John McCall9aa472c2010-03-19 07:35:19 +00006024 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00006025
John McCall9aa472c2010-03-19 07:35:19 +00006026 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00006027}
6028
Douglas Gregor904eed32008-11-10 20:40:00 +00006029/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6030/// an overloaded function (C++ [over.over]), where @p From is an
6031/// expression with overloaded function type and @p ToType is the type
6032/// we're trying to resolve to. For example:
6033///
6034/// @code
6035/// int f(double);
6036/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00006037///
Douglas Gregor904eed32008-11-10 20:40:00 +00006038/// int (*pfd)(double) = f; // selects f(double)
6039/// @endcode
6040///
6041/// This routine returns the resulting FunctionDecl if it could be
6042/// resolved, and NULL otherwise. When @p Complain is true, this
6043/// routine will emit diagnostics if there is an error.
6044FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00006045Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall6bb80172010-03-30 21:47:33 +00006046 bool Complain,
6047 DeclAccessPair &FoundResult) {
Douglas Gregor904eed32008-11-10 20:40:00 +00006048 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00006049 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00006050 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00006051 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00006052 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00006053 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00006054 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00006055 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00006056 FunctionType = MemTypePtr->getPointeeType();
6057 IsMember = true;
6058 }
Douglas Gregor904eed32008-11-10 20:40:00 +00006059
Douglas Gregor904eed32008-11-10 20:40:00 +00006060 // C++ [over.over]p1:
6061 // [...] [Note: any redundant set of parentheses surrounding the
6062 // overloaded function name is ignored (5.1). ]
Douglas Gregor904eed32008-11-10 20:40:00 +00006063 // C++ [over.over]p1:
6064 // [...] The overloaded function name can be preceded by the &
6065 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00006066 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
6067 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6068 if (OvlExpr->hasExplicitTemplateArgs()) {
6069 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6070 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregor904eed32008-11-10 20:40:00 +00006071 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006072
6073 // We expect a pointer or reference to function, or a function pointer.
6074 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6075 if (!FunctionType->isFunctionType()) {
6076 if (Complain)
6077 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6078 << OvlExpr->getName() << ToType;
6079
6080 return 0;
6081 }
6082
6083 assert(From->getType() == Context.OverloadTy);
Douglas Gregor904eed32008-11-10 20:40:00 +00006084
Douglas Gregor904eed32008-11-10 20:40:00 +00006085 // Look through all of the overloaded functions, searching for one
6086 // whose type matches exactly.
John McCall9aa472c2010-03-19 07:35:19 +00006087 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb7a09262010-04-01 18:32:35 +00006088 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
6089
Douglas Gregor00aeb522009-07-08 23:33:52 +00006090 bool FoundNonTemplateFunction = false;
John McCall7bb12da2010-02-02 06:20:04 +00006091 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6092 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00006093 // Look through any using declarations to find the underlying function.
6094 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6095
Douglas Gregor904eed32008-11-10 20:40:00 +00006096 // C++ [over.over]p3:
6097 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00006098 // targets of type "pointer-to-function" or "reference-to-function."
6099 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00006100 // type "pointer-to-member-function."
6101 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00006102
Mike Stump1eb44332009-09-09 15:08:12 +00006103 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthbd647292009-12-29 06:17:27 +00006104 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006105 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00006106 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00006107 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00006108 // static when converting to member pointer.
6109 if (Method->isStatic() == IsMember)
6110 continue;
6111 } else if (IsMember)
6112 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00006113
Douglas Gregor00aeb522009-07-08 23:33:52 +00006114 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00006115 // If the name is a function template, template argument deduction is
6116 // done (14.8.2.2), and if the argument deduction succeeds, the
6117 // resulting template argument list is used to generate a single
6118 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00006119 // overloaded functions considered.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00006120 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor83314aa2009-07-08 20:55:45 +00006121 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00006122 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor83314aa2009-07-08 20:55:45 +00006123 if (TemplateDeductionResult Result
John McCall7bb12da2010-02-02 06:20:04 +00006124 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00006125 FunctionType, Specialization, Info)) {
6126 // FIXME: make a note of the failed deduction for diagnostics.
6127 (void)Result;
6128 } else {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00006129 // FIXME: If the match isn't exact, shouldn't we just drop this as
6130 // a candidate? Find a testcase before changing the code.
Mike Stump1eb44332009-09-09 15:08:12 +00006131 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00006132 == Context.getCanonicalType(Specialization->getType()));
John McCall9aa472c2010-03-19 07:35:19 +00006133 Matches.push_back(std::make_pair(I.getPair(),
6134 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor83314aa2009-07-08 20:55:45 +00006135 }
John McCallba135432009-11-21 08:51:07 +00006136
6137 continue;
Douglas Gregor83314aa2009-07-08 20:55:45 +00006138 }
Mike Stump1eb44332009-09-09 15:08:12 +00006139
Chandler Carruthbd647292009-12-29 06:17:27 +00006140 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00006141 // Skip non-static functions when converting to pointer, and static
6142 // when converting to member pointer.
6143 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00006144 continue;
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006145
6146 // If we have explicit template arguments, skip non-templates.
John McCall7bb12da2010-02-02 06:20:04 +00006147 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006148 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00006149 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00006150 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00006151
Chandler Carruthbd647292009-12-29 06:17:27 +00006152 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00006153 QualType ResultTy;
6154 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6155 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6156 ResultTy)) {
John McCall9aa472c2010-03-19 07:35:19 +00006157 Matches.push_back(std::make_pair(I.getPair(),
6158 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00006159 FoundNonTemplateFunction = true;
6160 }
Mike Stump1eb44332009-09-09 15:08:12 +00006161 }
Douglas Gregor904eed32008-11-10 20:40:00 +00006162 }
6163
Douglas Gregor00aeb522009-07-08 23:33:52 +00006164 // If there were 0 or 1 matches, we're done.
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006165 if (Matches.empty()) {
6166 if (Complain) {
6167 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6168 << OvlExpr->getName() << FunctionType;
6169 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6170 E = OvlExpr->decls_end();
6171 I != E; ++I)
6172 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6173 NoteOverloadCandidate(F);
6174 }
6175
Douglas Gregor00aeb522009-07-08 23:33:52 +00006176 return 0;
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006177 } else if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00006178 FunctionDecl *Result = Matches[0].second;
John McCall6bb80172010-03-30 21:47:33 +00006179 FoundResult = Matches[0].first;
Sebastian Redl07ab2022009-10-17 21:12:09 +00006180 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCallc373d482010-01-27 01:50:18 +00006181 if (Complain)
John McCall6bb80172010-03-30 21:47:33 +00006182 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redl07ab2022009-10-17 21:12:09 +00006183 return Result;
6184 }
Douglas Gregor00aeb522009-07-08 23:33:52 +00006185
6186 // C++ [over.over]p4:
6187 // If more than one function is selected, [...]
Douglas Gregor312a2022009-09-26 03:56:17 +00006188 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006189 // [...] and any given function template specialization F1 is
6190 // eliminated if the set contains a second function template
6191 // specialization whose function template is more specialized
6192 // than the function template of F1 according to the partial
6193 // ordering rules of 14.5.5.2.
6194
6195 // The algorithm specified above is quadratic. We instead use a
6196 // two-pass algorithm (similar to the one used to identify the
6197 // best viable function in an overload set) that identifies the
6198 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00006199
6200 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6201 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6202 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCallc373d482010-01-27 01:50:18 +00006203
6204 UnresolvedSetIterator Result =
John McCall9aa472c2010-03-19 07:35:19 +00006205 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redl07ab2022009-10-17 21:12:09 +00006206 TPOC_Other, From->getLocStart(),
6207 PDiag(),
6208 PDiag(diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00006209 << Matches[0].second->getDeclName(),
John McCall220ccbf2010-01-13 00:25:19 +00006210 PDiag(diag::note_ovl_candidate)
6211 << (unsigned) oc_function_template);
John McCall9aa472c2010-03-19 07:35:19 +00006212 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCallc373d482010-01-27 01:50:18 +00006213 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall6bb80172010-03-30 21:47:33 +00006214 FoundResult = Matches[Result - MatchesCopy.begin()].first;
John McCallb697e082010-05-06 18:15:07 +00006215 if (Complain) {
John McCall6bb80172010-03-30 21:47:33 +00006216 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCallb697e082010-05-06 18:15:07 +00006217 DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc());
6218 }
John McCallc373d482010-01-27 01:50:18 +00006219 return cast<FunctionDecl>(*Result);
Douglas Gregor00aeb522009-07-08 23:33:52 +00006220 }
Mike Stump1eb44332009-09-09 15:08:12 +00006221
Douglas Gregor312a2022009-09-26 03:56:17 +00006222 // [...] any function template specializations in the set are
6223 // eliminated if the set also contains a non-template function, [...]
John McCallc373d482010-01-27 01:50:18 +00006224 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCall9aa472c2010-03-19 07:35:19 +00006225 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCallc373d482010-01-27 01:50:18 +00006226 ++I;
6227 else {
John McCall9aa472c2010-03-19 07:35:19 +00006228 Matches[I] = Matches[--N];
6229 Matches.set_size(N);
John McCallc373d482010-01-27 01:50:18 +00006230 }
6231 }
Douglas Gregor312a2022009-09-26 03:56:17 +00006232
Mike Stump1eb44332009-09-09 15:08:12 +00006233 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00006234 // selected function.
John McCallc373d482010-01-27 01:50:18 +00006235 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00006236 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall6bb80172010-03-30 21:47:33 +00006237 FoundResult = Matches[0].first;
John McCallb697e082010-05-06 18:15:07 +00006238 if (Complain) {
John McCall9aa472c2010-03-19 07:35:19 +00006239 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
John McCallb697e082010-05-06 18:15:07 +00006240 DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc());
6241 }
John McCall9aa472c2010-03-19 07:35:19 +00006242 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redl07ab2022009-10-17 21:12:09 +00006243 }
Mike Stump1eb44332009-09-09 15:08:12 +00006244
Douglas Gregor00aeb522009-07-08 23:33:52 +00006245 // FIXME: We should probably return the same thing that BestViableFunction
6246 // returns (even if we issue the diagnostics here).
6247 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00006248 << Matches[0].second->getDeclName();
6249 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6250 NoteOverloadCandidate(Matches[I].second);
Douglas Gregor904eed32008-11-10 20:40:00 +00006251 return 0;
6252}
6253
Douglas Gregor4b52e252009-12-21 23:17:24 +00006254/// \brief Given an expression that refers to an overloaded function, try to
6255/// resolve that overloaded function expression down to a single function.
6256///
6257/// This routine can only resolve template-ids that refer to a single function
6258/// template, where that template-id refers to a single template whose template
6259/// arguments are either provided by the template-id or have defaults,
6260/// as described in C++0x [temp.arg.explicit]p3.
6261FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6262 // C++ [over.over]p1:
6263 // [...] [Note: any redundant set of parentheses surrounding the
6264 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00006265 // C++ [over.over]p1:
6266 // [...] The overloaded function name can be preceded by the &
6267 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00006268
6269 if (From->getType() != Context.OverloadTy)
6270 return 0;
6271
6272 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor4b52e252009-12-21 23:17:24 +00006273
6274 // If we didn't actually find any template-ids, we're done.
John McCall7bb12da2010-02-02 06:20:04 +00006275 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00006276 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00006277
6278 TemplateArgumentListInfo ExplicitTemplateArgs;
6279 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor4b52e252009-12-21 23:17:24 +00006280
6281 // Look through all of the overloaded functions, searching for one
6282 // whose type matches exactly.
6283 FunctionDecl *Matched = 0;
John McCall7bb12da2010-02-02 06:20:04 +00006284 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6285 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00006286 // C++0x [temp.arg.explicit]p3:
6287 // [...] In contexts where deduction is done and fails, or in contexts
6288 // where deduction is not done, if a template argument list is
6289 // specified and it, along with any default template arguments,
6290 // identifies a single function template specialization, then the
6291 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00006292 FunctionTemplateDecl *FunctionTemplate
6293 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor4b52e252009-12-21 23:17:24 +00006294
6295 // C++ [over.over]p2:
6296 // If the name is a function template, template argument deduction is
6297 // done (14.8.2.2), and if the argument deduction succeeds, the
6298 // resulting template argument list is used to generate a single
6299 // function template specialization, which is added to the set of
6300 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00006301 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00006302 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00006303 if (TemplateDeductionResult Result
6304 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6305 Specialization, Info)) {
6306 // FIXME: make a note of the failed deduction for diagnostics.
6307 (void)Result;
6308 continue;
6309 }
6310
6311 // Multiple matches; we can't resolve to a single declaration.
6312 if (Matched)
6313 return 0;
6314
6315 Matched = Specialization;
6316 }
6317
6318 return Matched;
6319}
6320
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006321/// \brief Add a single candidate to the overload set.
6322static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00006323 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00006324 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006325 Expr **Args, unsigned NumArgs,
6326 OverloadCandidateSet &CandidateSet,
6327 bool PartialOverloading) {
John McCall9aa472c2010-03-19 07:35:19 +00006328 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00006329 if (isa<UsingShadowDecl>(Callee))
6330 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6331
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006332 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00006333 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCall9aa472c2010-03-19 07:35:19 +00006334 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00006335 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006336 return;
John McCallba135432009-11-21 08:51:07 +00006337 }
6338
6339 if (FunctionTemplateDecl *FuncTemplate
6340 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00006341 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6342 ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00006343 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00006344 return;
6345 }
6346
6347 assert(false && "unhandled case in overloaded call candidate");
6348
6349 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006350}
6351
6352/// \brief Add the overload candidates named by callee and/or found by argument
6353/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00006354void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006355 Expr **Args, unsigned NumArgs,
6356 OverloadCandidateSet &CandidateSet,
6357 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00006358
6359#ifndef NDEBUG
6360 // Verify that ArgumentDependentLookup is consistent with the rules
6361 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006362 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006363 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6364 // and let Y be the lookup set produced by argument dependent
6365 // lookup (defined as follows). If X contains
6366 //
6367 // -- a declaration of a class member, or
6368 //
6369 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00006370 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006371 //
6372 // -- a declaration that is neither a function or a function
6373 // template
6374 //
6375 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00006376
John McCall3b4294e2009-12-16 12:17:52 +00006377 if (ULE->requiresADL()) {
6378 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6379 E = ULE->decls_end(); I != E; ++I) {
6380 assert(!(*I)->getDeclContext()->isRecord());
6381 assert(isa<UsingShadowDecl>(*I) ||
6382 !(*I)->getDeclContext()->isFunctionOrMethod());
6383 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00006384 }
6385 }
6386#endif
6387
John McCall3b4294e2009-12-16 12:17:52 +00006388 // It would be nice to avoid this copy.
6389 TemplateArgumentListInfo TABuffer;
6390 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6391 if (ULE->hasExplicitTemplateArgs()) {
6392 ULE->copyTemplateArgumentsInto(TABuffer);
6393 ExplicitTemplateArgs = &TABuffer;
6394 }
6395
6396 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6397 E = ULE->decls_end(); I != E; ++I)
John McCall9aa472c2010-03-19 07:35:19 +00006398 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00006399 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006400 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00006401
John McCall3b4294e2009-12-16 12:17:52 +00006402 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00006403 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6404 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006405 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006406 CandidateSet,
6407 PartialOverloading);
6408}
John McCall578b69b2009-12-16 08:11:27 +00006409
John McCall3b4294e2009-12-16 12:17:52 +00006410static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
6411 Expr **Args, unsigned NumArgs) {
6412 Fn->Destroy(SemaRef.Context);
6413 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
6414 Args[Arg]->Destroy(SemaRef.Context);
6415 return SemaRef.ExprError();
6416}
6417
John McCall578b69b2009-12-16 08:11:27 +00006418/// Attempts to recover from a call where no functions were found.
6419///
6420/// Returns true if new candidates were found.
John McCall3b4294e2009-12-16 12:17:52 +00006421static Sema::OwningExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006422BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00006423 UnresolvedLookupExpr *ULE,
6424 SourceLocation LParenLoc,
6425 Expr **Args, unsigned NumArgs,
6426 SourceLocation *CommaLocs,
6427 SourceLocation RParenLoc) {
John McCall578b69b2009-12-16 08:11:27 +00006428
6429 CXXScopeSpec SS;
6430 if (ULE->getQualifier()) {
6431 SS.setScopeRep(ULE->getQualifier());
6432 SS.setRange(ULE->getQualifierRange());
6433 }
6434
John McCall3b4294e2009-12-16 12:17:52 +00006435 TemplateArgumentListInfo TABuffer;
6436 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6437 if (ULE->hasExplicitTemplateArgs()) {
6438 ULE->copyTemplateArgumentsInto(TABuffer);
6439 ExplicitTemplateArgs = &TABuffer;
6440 }
6441
John McCall578b69b2009-12-16 08:11:27 +00006442 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6443 Sema::LookupOrdinaryName);
Douglas Gregor91f7ac72010-05-18 16:14:23 +00006444 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCall3b4294e2009-12-16 12:17:52 +00006445 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCall578b69b2009-12-16 08:11:27 +00006446
John McCall3b4294e2009-12-16 12:17:52 +00006447 assert(!R.empty() && "lookup results empty despite recovery");
6448
6449 // Build an implicit member call if appropriate. Just drop the
6450 // casts and such from the call, we don't really care.
6451 Sema::OwningExprResult NewFn = SemaRef.ExprError();
6452 if ((*R.begin())->isCXXClassMember())
6453 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6454 else if (ExplicitTemplateArgs)
6455 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6456 else
6457 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6458
6459 if (NewFn.isInvalid())
6460 return Destroy(SemaRef, Fn, Args, NumArgs);
6461
6462 Fn->Destroy(SemaRef.Context);
6463
6464 // This shouldn't cause an infinite loop because we're giving it
6465 // an expression with non-empty lookup results, which should never
6466 // end up here.
6467 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
6468 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
6469 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00006470}
Douglas Gregord7a95972010-06-08 17:35:15 +00006471
Douglas Gregorf6b89692008-11-26 05:54:23 +00006472/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00006473/// (which eventually refers to the declaration Func) and the call
6474/// arguments Args/NumArgs, attempt to resolve the function call down
6475/// to a specific function. If overload resolution succeeds, returns
6476/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00006477/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00006478/// arguments and Fn, and returns NULL.
John McCall3b4294e2009-12-16 12:17:52 +00006479Sema::OwningExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006480Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00006481 SourceLocation LParenLoc,
6482 Expr **Args, unsigned NumArgs,
6483 SourceLocation *CommaLocs,
6484 SourceLocation RParenLoc) {
6485#ifndef NDEBUG
6486 if (ULE->requiresADL()) {
6487 // To do ADL, we must have found an unqualified name.
6488 assert(!ULE->getQualifier() && "qualified name with ADL");
6489
6490 // We don't perform ADL for implicit declarations of builtins.
6491 // Verify that this was correctly set up.
6492 FunctionDecl *F;
6493 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6494 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6495 F->getBuiltinID() && F->isImplicit())
6496 assert(0 && "performing ADL for builtin");
6497
6498 // We don't perform ADL in C.
6499 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6500 }
6501#endif
6502
John McCall5769d612010-02-08 23:07:23 +00006503 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00006504
John McCall3b4294e2009-12-16 12:17:52 +00006505 // Add the functions denoted by the callee to the set of candidate
6506 // functions, including those from argument-dependent lookup.
6507 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00006508
6509 // If we found nothing, try to recover.
6510 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6511 // bailout out if it fails.
John McCall3b4294e2009-12-16 12:17:52 +00006512 if (CandidateSet.empty())
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006513 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00006514 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00006515
Douglas Gregorf6b89692008-11-26 05:54:23 +00006516 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006517 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00006518 case OR_Success: {
6519 FunctionDecl *FDecl = Best->Function;
John McCall9aa472c2010-03-19 07:35:19 +00006520 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00006521 DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00006522 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall3b4294e2009-12-16 12:17:52 +00006523 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6524 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00006525
6526 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00006527 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00006528 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00006529 << ULE->getName() << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006530 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00006531 break;
6532
6533 case OR_Ambiguous:
6534 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00006535 << ULE->getName() << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006536 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00006537 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006538
6539 case OR_Deleted:
6540 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6541 << Best->Function->isDeleted()
John McCall3b4294e2009-12-16 12:17:52 +00006542 << ULE->getName()
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006543 << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006544 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006545 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00006546 }
6547
6548 // Overload resolution failed. Destroy all of the subexpressions and
6549 // return NULL.
6550 Fn->Destroy(Context);
6551 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
6552 Args[Arg]->Destroy(Context);
John McCall3b4294e2009-12-16 12:17:52 +00006553 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00006554}
6555
John McCall6e266892010-01-26 03:27:55 +00006556static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00006557 return Functions.size() > 1 ||
6558 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6559}
6560
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006561/// \brief Create a unary operation that may resolve to an overloaded
6562/// operator.
6563///
6564/// \param OpLoc The location of the operator itself (e.g., '*').
6565///
6566/// \param OpcIn The UnaryOperator::Opcode that describes this
6567/// operator.
6568///
6569/// \param Functions The set of non-member functions that will be
6570/// considered by overload resolution. The caller needs to build this
6571/// set based on the context using, e.g.,
6572/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6573/// set should not contain any member functions; those will be added
6574/// by CreateOverloadedUnaryOp().
6575///
6576/// \param input The input argument.
John McCall6e266892010-01-26 03:27:55 +00006577Sema::OwningExprResult
6578Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6579 const UnresolvedSetImpl &Fns,
6580 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006581 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
6582 Expr *Input = (Expr *)input.get();
6583
6584 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6585 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6586 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6587
6588 Expr *Args[2] = { Input, 0 };
6589 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00006590
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006591 // For post-increment and post-decrement, add the implicit '0' as
6592 // the second argument, so that we know this is a post-increment or
6593 // post-decrement.
6594 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
6595 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump1eb44332009-09-09 15:08:12 +00006596 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006597 SourceLocation());
6598 NumArgs = 2;
6599 }
6600
6601 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00006602 if (Fns.empty())
6603 return Owned(new (Context) UnaryOperator(input.takeAs<Expr>(),
6604 Opc,
6605 Context.DependentTy,
6606 OpLoc));
6607
John McCallc373d482010-01-27 01:50:18 +00006608 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00006609 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00006610 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00006611 0, SourceRange(), OpName, OpLoc,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00006612 /*ADL*/ true, IsOverloaded(Fns),
6613 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006614 input.release();
6615 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6616 &Args[0], NumArgs,
6617 Context.DependentTy,
6618 OpLoc));
6619 }
6620
6621 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00006622 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006623
6624 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00006625 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006626
6627 // Add operator candidates that are member functions.
6628 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6629
John McCall6e266892010-01-26 03:27:55 +00006630 // Add candidates from ADL.
6631 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregordc81c882010-02-05 05:15:43 +00006632 Args, NumArgs,
John McCall6e266892010-01-26 03:27:55 +00006633 /*ExplicitTemplateArgs*/ 0,
6634 CandidateSet);
6635
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006636 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00006637 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006638
6639 // Perform overload resolution.
6640 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006641 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006642 case OR_Success: {
6643 // We found a built-in operator or an overloaded operator.
6644 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00006645
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006646 if (FnDecl) {
6647 // We matched an overloaded operator. Build a call to that
6648 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00006649
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006650 // Convert the arguments.
6651 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00006652 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00006653
John McCall6bb80172010-03-30 21:47:33 +00006654 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6655 Best->FoundDecl, Method))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006656 return ExprError();
6657 } else {
6658 // Convert the arguments.
Douglas Gregore1a5c172009-12-23 17:40:29 +00006659 OwningExprResult InputInit
6660 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregorbaecfed2009-12-23 00:02:00 +00006661 FnDecl->getParamDecl(0)),
Douglas Gregore1a5c172009-12-23 17:40:29 +00006662 SourceLocation(),
6663 move(input));
6664 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006665 return ExprError();
Douglas Gregorbaecfed2009-12-23 00:02:00 +00006666
Douglas Gregore1a5c172009-12-23 17:40:29 +00006667 input = move(InputInit);
Douglas Gregorbaecfed2009-12-23 00:02:00 +00006668 Input = (Expr *)input.get();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006669 }
6670
John McCallb697e082010-05-06 18:15:07 +00006671 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6672
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006673 // Determine the result type
Douglas Gregor5291c3c2010-07-13 08:18:22 +00006674 QualType ResultTy = FnDecl->getCallResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006675
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006676 // Build the actual expression node.
6677 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6678 SourceLocation());
6679 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00006680
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006681 input.release();
Eli Friedman4c3b8962009-11-18 03:58:17 +00006682 Args[0] = Input;
Anders Carlsson26a2a072009-10-13 21:19:37 +00006683 ExprOwningPtr<CallExpr> TheCall(this,
6684 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman4c3b8962009-11-18 03:58:17 +00006685 Args, NumArgs, ResultTy, OpLoc));
John McCallb697e082010-05-06 18:15:07 +00006686
Anders Carlsson26a2a072009-10-13 21:19:37 +00006687 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6688 FnDecl))
6689 return ExprError();
6690
6691 return MaybeBindToTemporary(TheCall.release());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006692 } else {
6693 // We matched a built-in operator. Convert the arguments, then
6694 // break out so that we will build the appropriate built-in
6695 // operator node.
6696 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00006697 Best->Conversions[0], AA_Passing))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006698 return ExprError();
6699
6700 break;
6701 }
6702 }
6703
6704 case OR_No_Viable_Function:
6705 // No viable function; fall through to handling this as a
6706 // built-in operator, which will produce an error message for us.
6707 break;
6708
6709 case OR_Ambiguous:
6710 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6711 << UnaryOperator::getOpcodeStr(Opc)
6712 << Input->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006713 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00006714 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006715 return ExprError();
6716
6717 case OR_Deleted:
6718 Diag(OpLoc, diag::err_ovl_deleted_oper)
6719 << Best->Function->isDeleted()
6720 << UnaryOperator::getOpcodeStr(Opc)
6721 << Input->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006722 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006723 return ExprError();
6724 }
6725
6726 // Either we found no viable overloaded operator or we matched a
6727 // built-in operator. In either case, fall through to trying to
6728 // build a built-in operation.
6729 input.release();
6730 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
6731}
6732
Douglas Gregor063daf62009-03-13 18:40:31 +00006733/// \brief Create a binary operation that may resolve to an overloaded
6734/// operator.
6735///
6736/// \param OpLoc The location of the operator itself (e.g., '+').
6737///
6738/// \param OpcIn The BinaryOperator::Opcode that describes this
6739/// operator.
6740///
6741/// \param Functions The set of non-member functions that will be
6742/// considered by overload resolution. The caller needs to build this
6743/// set based on the context using, e.g.,
6744/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6745/// set should not contain any member functions; those will be added
6746/// by CreateOverloadedBinOp().
6747///
6748/// \param LHS Left-hand argument.
6749/// \param RHS Right-hand argument.
Mike Stump1eb44332009-09-09 15:08:12 +00006750Sema::OwningExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00006751Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006752 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00006753 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00006754 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00006755 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006756 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00006757
6758 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6759 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6760 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6761
6762 // If either side is type-dependent, create an appropriate dependent
6763 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006764 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00006765 if (Fns.empty()) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006766 // If there are no functions to store, just build a dependent
6767 // BinaryOperator or CompoundAssignment.
6768 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
6769 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6770 Context.DependentTy, OpLoc));
6771
6772 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6773 Context.DependentTy,
6774 Context.DependentTy,
6775 Context.DependentTy,
6776 OpLoc));
6777 }
John McCall6e266892010-01-26 03:27:55 +00006778
6779 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00006780 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00006781 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00006782 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00006783 0, SourceRange(), OpName, OpLoc,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00006784 /*ADL*/ true, IsOverloaded(Fns),
6785 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00006786 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00006787 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00006788 Context.DependentTy,
6789 OpLoc));
6790 }
6791
6792 // If this is the .* operator, which is not overloadable, just
6793 // create a built-in binary operator.
6794 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006795 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00006796
Sebastian Redl275c2b42009-11-18 23:10:33 +00006797 // If this is the assignment operator, we only perform overload resolution
6798 // if the left-hand side is a class or enumeration type. This is actually
6799 // a hack. The standard requires that we do overload resolution between the
6800 // various built-in candidates, but as DR507 points out, this can lead to
6801 // problems. So we do it this way, which pretty much follows what GCC does.
6802 // Note that we go the traditional code path for compound assignment forms.
6803 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006804 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00006805
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006806 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00006807 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00006808
6809 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00006810 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00006811
6812 // Add operator candidates that are member functions.
6813 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6814
John McCall6e266892010-01-26 03:27:55 +00006815 // Add candidates from ADL.
6816 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6817 Args, 2,
6818 /*ExplicitTemplateArgs*/ 0,
6819 CandidateSet);
6820
Douglas Gregor063daf62009-03-13 18:40:31 +00006821 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00006822 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00006823
6824 // Perform overload resolution.
6825 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006826 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00006827 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00006828 // We found a built-in operator or an overloaded operator.
6829 FunctionDecl *FnDecl = Best->Function;
6830
6831 if (FnDecl) {
6832 // We matched an overloaded operator. Build a call to that
6833 // operator.
6834
6835 // Convert the arguments.
6836 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00006837 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +00006838 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00006839
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006840 OwningExprResult Arg1
6841 = PerformCopyInitialization(
6842 InitializedEntity::InitializeParameter(
6843 FnDecl->getParamDecl(0)),
6844 SourceLocation(),
6845 Owned(Args[1]));
6846 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00006847 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006848
Douglas Gregor5fccd362010-03-03 23:55:11 +00006849 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00006850 Best->FoundDecl, Method))
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006851 return ExprError();
6852
6853 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00006854 } else {
6855 // Convert the arguments.
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006856 OwningExprResult Arg0
6857 = PerformCopyInitialization(
6858 InitializedEntity::InitializeParameter(
6859 FnDecl->getParamDecl(0)),
6860 SourceLocation(),
6861 Owned(Args[0]));
6862 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00006863 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006864
6865 OwningExprResult Arg1
6866 = PerformCopyInitialization(
6867 InitializedEntity::InitializeParameter(
6868 FnDecl->getParamDecl(1)),
6869 SourceLocation(),
6870 Owned(Args[1]));
6871 if (Arg1.isInvalid())
6872 return ExprError();
6873 Args[0] = LHS = Arg0.takeAs<Expr>();
6874 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00006875 }
6876
John McCallb697e082010-05-06 18:15:07 +00006877 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6878
Douglas Gregor063daf62009-03-13 18:40:31 +00006879 // Determine the result type
6880 QualType ResultTy
Douglas Gregor5291c3c2010-07-13 08:18:22 +00006881 = FnDecl->getType()->getAs<FunctionType>()
6882 ->getCallResultType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +00006883
6884 // Build the actual expression node.
6885 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00006886 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00006887 UsualUnaryConversions(FnExpr);
6888
Anders Carlsson15ea3782009-10-13 22:43:21 +00006889 ExprOwningPtr<CXXOperatorCallExpr>
6890 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6891 Args, 2, ResultTy,
6892 OpLoc));
6893
6894 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6895 FnDecl))
6896 return ExprError();
6897
6898 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor063daf62009-03-13 18:40:31 +00006899 } else {
6900 // We matched a built-in operator. Convert the arguments, then
6901 // break out so that we will build the appropriate built-in
6902 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006903 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00006904 Best->Conversions[0], AA_Passing) ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006905 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00006906 Best->Conversions[1], AA_Passing))
Douglas Gregor063daf62009-03-13 18:40:31 +00006907 return ExprError();
6908
6909 break;
6910 }
6911 }
6912
Douglas Gregor33074752009-09-30 21:46:01 +00006913 case OR_No_Viable_Function: {
6914 // C++ [over.match.oper]p9:
6915 // If the operator is the operator , [...] and there are no
6916 // viable functions, then the operator is assumed to be the
6917 // built-in operator and interpreted according to clause 5.
6918 if (Opc == BinaryOperator::Comma)
6919 break;
6920
Sebastian Redl8593c782009-05-21 11:50:50 +00006921 // For class as left operand for assignment or compound assigment operator
6922 // do not fall through to handling in built-in, but report that no overloaded
6923 // assignment operator found
Douglas Gregor33074752009-09-30 21:46:01 +00006924 OwningExprResult Result = ExprError();
6925 if (Args[0]->getType()->isRecordType() &&
6926 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00006927 Diag(OpLoc, diag::err_ovl_no_viable_oper)
6928 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006929 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00006930 } else {
6931 // No viable function; try to create a built-in operation, which will
6932 // produce an error. Then, show the non-viable candidates.
6933 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00006934 }
Douglas Gregor33074752009-09-30 21:46:01 +00006935 assert(Result.isInvalid() &&
6936 "C++ binary operator overloading is missing candidates!");
6937 if (Result.isInvalid())
John McCallcbce6062010-01-12 07:18:19 +00006938 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00006939 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00006940 return move(Result);
6941 }
Douglas Gregor063daf62009-03-13 18:40:31 +00006942
6943 case OR_Ambiguous:
6944 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6945 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006946 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006947 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00006948 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00006949 return ExprError();
6950
6951 case OR_Deleted:
6952 Diag(OpLoc, diag::err_ovl_deleted_oper)
6953 << Best->Function->isDeleted()
6954 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006955 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006956 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor063daf62009-03-13 18:40:31 +00006957 return ExprError();
John McCall1d318332010-01-12 00:44:57 +00006958 }
Douglas Gregor063daf62009-03-13 18:40:31 +00006959
Douglas Gregor33074752009-09-30 21:46:01 +00006960 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006961 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00006962}
6963
Sebastian Redlf322ed62009-10-29 20:17:01 +00006964Action::OwningExprResult
6965Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
6966 SourceLocation RLoc,
6967 ExprArg Base, ExprArg Idx) {
6968 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
6969 static_cast<Expr*>(Idx.get()) };
6970 DeclarationName OpName =
6971 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
6972
6973 // If either side is type-dependent, create an appropriate dependent
6974 // expression.
6975 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
6976
John McCallc373d482010-01-27 01:50:18 +00006977 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00006978 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00006979 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCallf7a1a742009-11-24 19:00:30 +00006980 0, SourceRange(), OpName, LLoc,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00006981 /*ADL*/ true, /*Overloaded*/ false,
6982 UnresolvedSetIterator(),
6983 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +00006984 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00006985
6986 Base.release();
6987 Idx.release();
6988 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
6989 Args, 2,
6990 Context.DependentTy,
6991 RLoc));
6992 }
6993
6994 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00006995 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00006996
6997 // Subscript can only be overloaded as a member function.
6998
6999 // Add operator candidates that are member functions.
7000 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7001
7002 // Add builtin operator candidates.
7003 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7004
7005 // Perform overload resolution.
7006 OverloadCandidateSet::iterator Best;
7007 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
7008 case OR_Success: {
7009 // We found a built-in operator or an overloaded operator.
7010 FunctionDecl *FnDecl = Best->Function;
7011
7012 if (FnDecl) {
7013 // We matched an overloaded operator. Build a call to that
7014 // operator.
7015
John McCall9aa472c2010-03-19 07:35:19 +00007016 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007017 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +00007018
Sebastian Redlf322ed62009-10-29 20:17:01 +00007019 // Convert the arguments.
7020 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007021 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007022 Best->FoundDecl, Method))
Sebastian Redlf322ed62009-10-29 20:17:01 +00007023 return ExprError();
7024
Anders Carlsson38f88ab2010-01-29 18:37:50 +00007025 // Convert the arguments.
7026 OwningExprResult InputInit
7027 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7028 FnDecl->getParamDecl(0)),
7029 SourceLocation(),
7030 Owned(Args[1]));
7031 if (InputInit.isInvalid())
7032 return ExprError();
7033
7034 Args[1] = InputInit.takeAs<Expr>();
7035
Sebastian Redlf322ed62009-10-29 20:17:01 +00007036 // Determine the result type
7037 QualType ResultTy
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007038 = FnDecl->getType()->getAs<FunctionType>()
7039 ->getCallResultType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007040
7041 // Build the actual expression node.
7042 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7043 LLoc);
7044 UsualUnaryConversions(FnExpr);
7045
7046 Base.release();
7047 Idx.release();
7048 ExprOwningPtr<CXXOperatorCallExpr>
7049 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7050 FnExpr, Args, 2,
7051 ResultTy, RLoc));
7052
7053 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
7054 FnDecl))
7055 return ExprError();
7056
7057 return MaybeBindToTemporary(TheCall.release());
7058 } else {
7059 // We matched a built-in operator. Convert the arguments, then
7060 // break out so that we will build the appropriate built-in
7061 // operator node.
7062 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00007063 Best->Conversions[0], AA_Passing) ||
Sebastian Redlf322ed62009-10-29 20:17:01 +00007064 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00007065 Best->Conversions[1], AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00007066 return ExprError();
7067
7068 break;
7069 }
7070 }
7071
7072 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00007073 if (CandidateSet.empty())
7074 Diag(LLoc, diag::err_ovl_no_oper)
7075 << Args[0]->getType() << /*subscript*/ 0
7076 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7077 else
7078 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7079 << Args[0]->getType()
7080 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007081 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall1eb3e102010-01-07 02:04:15 +00007082 "[]", LLoc);
7083 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00007084 }
7085
7086 case OR_Ambiguous:
7087 Diag(LLoc, diag::err_ovl_ambiguous_oper)
7088 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007089 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redlf322ed62009-10-29 20:17:01 +00007090 "[]", LLoc);
7091 return ExprError();
7092
7093 case OR_Deleted:
7094 Diag(LLoc, diag::err_ovl_deleted_oper)
7095 << Best->Function->isDeleted() << "[]"
7096 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007097 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall81201622010-01-08 04:41:39 +00007098 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007099 return ExprError();
7100 }
7101
7102 // We matched a built-in operator; build it.
7103 Base.release();
7104 Idx.release();
7105 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
7106 Owned(Args[1]), RLoc);
7107}
7108
Douglas Gregor88a35142008-12-22 05:46:06 +00007109/// BuildCallToMemberFunction - Build a call to a member
7110/// function. MemExpr is the expression that refers to the member
7111/// function (and includes the object parameter), Args/NumArgs are the
7112/// arguments to the function call (not including the object
7113/// parameter). The caller needs to validate that the member
7114/// expression refers to a member function or an overloaded member
7115/// function.
John McCallaa81e162009-12-01 22:10:20 +00007116Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00007117Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7118 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor88a35142008-12-22 05:46:06 +00007119 unsigned NumArgs, SourceLocation *CommaLocs,
7120 SourceLocation RParenLoc) {
7121 // Dig out the member expression. This holds both the object
7122 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00007123 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7124
John McCall129e2df2009-11-30 22:42:35 +00007125 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00007126 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +00007127 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007128 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +00007129 if (isa<MemberExpr>(NakedMemExpr)) {
7130 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00007131 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +00007132 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +00007133 Qualifier = MemExpr->getQualifier();
John McCall129e2df2009-11-30 22:42:35 +00007134 } else {
7135 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007136 Qualifier = UnresExpr->getQualifier();
7137
John McCall701c89e2009-12-03 04:06:58 +00007138 QualType ObjectType = UnresExpr->getBaseType();
John McCall129e2df2009-11-30 22:42:35 +00007139
Douglas Gregor88a35142008-12-22 05:46:06 +00007140 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +00007141 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00007142
John McCallaa81e162009-12-01 22:10:20 +00007143 // FIXME: avoid copy.
7144 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7145 if (UnresExpr->hasExplicitTemplateArgs()) {
7146 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7147 TemplateArgs = &TemplateArgsBuffer;
7148 }
7149
John McCall129e2df2009-11-30 22:42:35 +00007150 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7151 E = UnresExpr->decls_end(); I != E; ++I) {
7152
John McCall701c89e2009-12-03 04:06:58 +00007153 NamedDecl *Func = *I;
7154 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7155 if (isa<UsingShadowDecl>(Func))
7156 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7157
John McCall129e2df2009-11-30 22:42:35 +00007158 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00007159 // If explicit template arguments were provided, we can't call a
7160 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00007161 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00007162 continue;
7163
John McCall9aa472c2010-03-19 07:35:19 +00007164 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCall86820f52010-01-26 01:37:31 +00007165 Args, NumArgs,
John McCall701c89e2009-12-03 04:06:58 +00007166 CandidateSet, /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00007167 } else {
John McCall129e2df2009-11-30 22:42:35 +00007168 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +00007169 I.getPair(), ActingDC, TemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00007170 ObjectType, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00007171 CandidateSet,
7172 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00007173 }
Douglas Gregordec06662009-08-21 18:42:58 +00007174 }
Mike Stump1eb44332009-09-09 15:08:12 +00007175
John McCall129e2df2009-11-30 22:42:35 +00007176 DeclarationName DeclName = UnresExpr->getMemberName();
7177
Douglas Gregor88a35142008-12-22 05:46:06 +00007178 OverloadCandidateSet::iterator Best;
John McCall129e2df2009-11-30 22:42:35 +00007179 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00007180 case OR_Success:
7181 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00007182 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +00007183 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007184 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +00007185 break;
7186
7187 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00007188 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00007189 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00007190 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007191 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00007192 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007193 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007194
7195 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00007196 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00007197 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007198 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00007199 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007200 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007201
7202 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00007203 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007204 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00007205 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007206 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007207 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007208 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007209 }
7210
John McCall6bb80172010-03-30 21:47:33 +00007211 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +00007212
John McCallaa81e162009-12-01 22:10:20 +00007213 // If overload resolution picked a static member, build a
7214 // non-member call based on that function.
7215 if (Method->isStatic()) {
7216 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7217 Args, NumArgs, RParenLoc);
7218 }
7219
John McCall129e2df2009-11-30 22:42:35 +00007220 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00007221 }
7222
7223 assert(Method && "Member call to something that isn't a method?");
Mike Stump1eb44332009-09-09 15:08:12 +00007224 ExprOwningPtr<CXXMemberCallExpr>
John McCallaa81e162009-12-01 22:10:20 +00007225 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump1eb44332009-09-09 15:08:12 +00007226 NumArgs,
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007227 Method->getCallResultType(),
Douglas Gregor88a35142008-12-22 05:46:06 +00007228 RParenLoc));
7229
Anders Carlssoneed3e692009-10-10 00:06:20 +00007230 // Check for a valid return type.
7231 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
7232 TheCall.get(), Method))
John McCallaa81e162009-12-01 22:10:20 +00007233 return ExprError();
Anders Carlssoneed3e692009-10-10 00:06:20 +00007234
Douglas Gregor88a35142008-12-22 05:46:06 +00007235 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +00007236 // We only need to do this if there was actually an overload; otherwise
7237 // it was done at lookup.
John McCallaa81e162009-12-01 22:10:20 +00007238 Expr *ObjectArg = MemExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00007239 if (!Method->isStatic() &&
John McCall6bb80172010-03-30 21:47:33 +00007240 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7241 FoundDecl, Method))
John McCallaa81e162009-12-01 22:10:20 +00007242 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007243 MemExpr->setBase(ObjectArg);
7244
7245 // Convert the rest of the arguments
Douglas Gregor5f970ee2010-05-04 18:18:31 +00007246 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00007247 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00007248 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00007249 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007250
Anders Carlssond406bf02009-08-16 01:56:34 +00007251 if (CheckFunctionCall(Method, TheCall.get()))
John McCallaa81e162009-12-01 22:10:20 +00007252 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00007253
John McCallaa81e162009-12-01 22:10:20 +00007254 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor88a35142008-12-22 05:46:06 +00007255}
7256
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007257/// BuildCallToObjectOfClassType - Build a call to an object of class
7258/// type (C++ [over.call.object]), which can end up invoking an
7259/// overloaded function call operator (@c operator()) or performing a
7260/// user-defined conversion on the object argument.
Mike Stump1eb44332009-09-09 15:08:12 +00007261Sema::ExprResult
7262Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00007263 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007264 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00007265 SourceLocation *CommaLocs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007266 SourceLocation RParenLoc) {
7267 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00007268 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00007269
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007270 // C++ [over.call.object]p1:
7271 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00007272 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007273 // candidate functions includes at least the function call
7274 // operators of T. The function call operators of T are obtained by
7275 // ordinary lookup of the name operator() in the context of
7276 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +00007277 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00007278 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00007279
7280 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007281 PDiag(diag::err_incomplete_object_call)
Douglas Gregor593564b2009-11-15 07:48:03 +00007282 << Object->getSourceRange()))
7283 return true;
7284
John McCalla24dc2e2009-11-17 02:14:36 +00007285 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7286 LookupQualifiedName(R, Record->getDecl());
7287 R.suppressDiagnostics();
7288
Douglas Gregor593564b2009-11-15 07:48:03 +00007289 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00007290 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00007291 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCall86820f52010-01-26 01:37:31 +00007292 Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00007293 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00007294 }
Douglas Gregor4a27d702009-10-21 06:18:39 +00007295
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007296 // C++ [over.call.object]p2:
7297 // In addition, for each conversion function declared in T of the
7298 // form
7299 //
7300 // operator conversion-type-id () cv-qualifier;
7301 //
7302 // where cv-qualifier is the same cv-qualification as, or a
7303 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00007304 // denotes the type "pointer to function of (P1,...,Pn) returning
7305 // R", or the type "reference to pointer to function of
7306 // (P1,...,Pn) returning R", or the type "reference to function
7307 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007308 // is also considered as a candidate function. Similarly,
7309 // surrogate call functions are added to the set of candidate
7310 // functions for each conversion function declared in an
7311 // accessible base class provided the function is not hidden
7312 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +00007313 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00007314 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00007315 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00007316 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00007317 NamedDecl *D = *I;
7318 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7319 if (isa<UsingShadowDecl>(D))
7320 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7321
Douglas Gregor4a27d702009-10-21 06:18:39 +00007322 // Skip over templated conversion functions; they aren't
7323 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00007324 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00007325 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007326
John McCall701c89e2009-12-03 04:06:58 +00007327 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCallba135432009-11-21 08:51:07 +00007328
Douglas Gregor4a27d702009-10-21 06:18:39 +00007329 // Strip the reference type (if any) and then the pointer type (if
7330 // any) to get down to what might be a function type.
7331 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7332 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7333 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007334
Douglas Gregor4a27d702009-10-21 06:18:39 +00007335 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall9aa472c2010-03-19 07:35:19 +00007336 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall701c89e2009-12-03 04:06:58 +00007337 Object->getType(), Args, NumArgs,
7338 CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007339 }
Mike Stump1eb44332009-09-09 15:08:12 +00007340
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007341 // Perform overload resolution.
7342 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00007343 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007344 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007345 // Overload resolution succeeded; we'll build the appropriate call
7346 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007347 break;
7348
7349 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00007350 if (CandidateSet.empty())
7351 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7352 << Object->getType() << /*call*/ 1
7353 << Object->getSourceRange();
7354 else
7355 Diag(Object->getSourceRange().getBegin(),
7356 diag::err_ovl_no_viable_object_call)
7357 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007358 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007359 break;
7360
7361 case OR_Ambiguous:
7362 Diag(Object->getSourceRange().getBegin(),
7363 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00007364 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007365 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007366 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007367
7368 case OR_Deleted:
7369 Diag(Object->getSourceRange().getBegin(),
7370 diag::err_ovl_deleted_object_call)
7371 << Best->Function->isDeleted()
7372 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007373 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007374 break;
Mike Stump1eb44332009-09-09 15:08:12 +00007375 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007376
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007377 if (Best == CandidateSet.end()) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007378 // We had an error; delete all of the subexpressions and return
7379 // the error.
Ted Kremenek8189cde2009-02-07 01:47:29 +00007380 Object->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007381 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek8189cde2009-02-07 01:47:29 +00007382 Args[ArgIdx]->Destroy(Context);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007383 return true;
7384 }
7385
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007386 if (Best->Function == 0) {
7387 // Since there is no function declaration, this is one of the
7388 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00007389 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007390 = cast<CXXConversionDecl>(
7391 Best->Conversions[0].UserDefined.ConversionFunction);
7392
John McCall9aa472c2010-03-19 07:35:19 +00007393 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007394 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00007395
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007396 // We selected one of the surrogate functions that converts the
7397 // object parameter to a function pointer. Perform the conversion
7398 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00007399
7400 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00007401 // and then call it.
John McCall6bb80172010-03-30 21:47:33 +00007402 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7403 Conv);
Fariborz Jahanianb7400232009-09-28 23:23:40 +00007404
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00007405 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00007406 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
Douglas Gregoraa0be172010-04-13 15:50:39 +00007407 CommaLocs, RParenLoc).result();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007408 }
7409
John McCall9aa472c2010-03-19 07:35:19 +00007410 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007411 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00007412
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007413 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7414 // that calls this method, using Object for the implicit object
7415 // parameter and passing along the remaining arguments.
7416 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall183700f2009-09-21 23:43:11 +00007417 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007418
7419 unsigned NumArgsInProto = Proto->getNumArgs();
7420 unsigned NumArgsToCheck = NumArgs;
7421
7422 // Build the full argument list for the method call (the
7423 // implicit object parameter is placed at the beginning of the
7424 // list).
7425 Expr **MethodArgs;
7426 if (NumArgs < NumArgsInProto) {
7427 NumArgsToCheck = NumArgsInProto;
7428 MethodArgs = new Expr*[NumArgsInProto + 1];
7429 } else {
7430 MethodArgs = new Expr*[NumArgs + 1];
7431 }
7432 MethodArgs[0] = Object;
7433 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7434 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00007435
7436 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00007437 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007438 UsualUnaryConversions(NewFn);
7439
7440 // Once we've built TheCall, all of the expressions are properly
7441 // owned.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007442 QualType ResultTy = Method->getCallResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00007443 ExprOwningPtr<CXXOperatorCallExpr>
7444 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor063daf62009-03-13 18:40:31 +00007445 MethodArgs, NumArgs + 1,
Ted Kremenek8189cde2009-02-07 01:47:29 +00007446 ResultTy, RParenLoc));
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007447 delete [] MethodArgs;
7448
Anders Carlsson07d68f12009-10-13 21:49:31 +00007449 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
7450 Method))
7451 return true;
7452
Douglas Gregor518fda12009-01-13 05:10:00 +00007453 // We may have default arguments. If so, we need to allocate more
7454 // slots in the call for them.
7455 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00007456 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00007457 else if (NumArgs > NumArgsInProto)
7458 NumArgsToCheck = NumArgsInProto;
7459
Chris Lattner312531a2009-04-12 08:11:20 +00007460 bool IsError = false;
7461
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007462 // Initialize the implicit object parameter.
Douglas Gregor5fccd362010-03-03 23:55:11 +00007463 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007464 Best->FoundDecl, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007465 TheCall->setArg(0, Object);
7466
Chris Lattner312531a2009-04-12 08:11:20 +00007467
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007468 // Check the argument types.
7469 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007470 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00007471 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007472 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00007473
Douglas Gregor518fda12009-01-13 05:10:00 +00007474 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +00007475
7476 OwningExprResult InputInit
7477 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7478 Method->getParamDecl(i)),
7479 SourceLocation(), Owned(Arg));
7480
7481 IsError |= InputInit.isInvalid();
7482 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00007483 } else {
Douglas Gregord47c47d2009-11-09 19:27:57 +00007484 OwningExprResult DefArg
7485 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7486 if (DefArg.isInvalid()) {
7487 IsError = true;
7488 break;
7489 }
7490
7491 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00007492 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007493
7494 TheCall->setArg(i + 1, Arg);
7495 }
7496
7497 // If this is a variadic call, handle args passed through "...".
7498 if (Proto->isVariadic()) {
7499 // Promote the arguments (C99 6.5.2.2p7).
7500 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7501 Expr *Arg = Args[i];
Chris Lattner40378332010-05-16 04:01:30 +00007502 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007503 TheCall->setArg(i + 1, Arg);
7504 }
7505 }
7506
Chris Lattner312531a2009-04-12 08:11:20 +00007507 if (IsError) return true;
7508
Anders Carlssond406bf02009-08-16 01:56:34 +00007509 if (CheckFunctionCall(Method, TheCall.get()))
7510 return true;
7511
Douglas Gregoraa0be172010-04-13 15:50:39 +00007512 return MaybeBindToTemporary(TheCall.release()).result();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007513}
7514
Douglas Gregor8ba10742008-11-20 16:27:02 +00007515/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00007516/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00007517/// @c Member is the name of the member we're trying to find.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007518Sema::OwningExprResult
7519Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
7520 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor8ba10742008-11-20 16:27:02 +00007521 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00007522
John McCall5769d612010-02-08 23:07:23 +00007523 SourceLocation Loc = Base->getExprLoc();
7524
Douglas Gregor8ba10742008-11-20 16:27:02 +00007525 // C++ [over.ref]p1:
7526 //
7527 // [...] An expression x->m is interpreted as (x.operator->())->m
7528 // for a class object x of type T if T::operator->() exists and if
7529 // the operator is selected as the best match function by the
7530 // overload resolution mechanism (13.3).
Douglas Gregor8ba10742008-11-20 16:27:02 +00007531 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +00007532 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +00007533 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007534
John McCall5769d612010-02-08 23:07:23 +00007535 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +00007536 PDiag(diag::err_typecheck_incomplete_tag)
7537 << Base->getSourceRange()))
7538 return ExprError();
7539
John McCalla24dc2e2009-11-17 02:14:36 +00007540 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7541 LookupQualifiedName(R, BaseRecord->getDecl());
7542 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00007543
7544 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00007545 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00007546 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00007547 /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00007548 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00007549
7550 // Perform overload resolution.
7551 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00007552 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00007553 case OR_Success:
7554 // Overload resolution succeeded; we'll build the call below.
7555 break;
7556
7557 case OR_No_Viable_Function:
7558 if (CandidateSet.empty())
7559 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007560 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007561 else
7562 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007563 << "operator->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007564 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007565 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007566
7567 case OR_Ambiguous:
7568 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlssone30572a2009-09-10 23:18:36 +00007569 << "->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007570 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007571 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007572
7573 case OR_Deleted:
7574 Diag(OpLoc, diag::err_ovl_deleted_oper)
7575 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00007576 << "->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007577 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007578 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007579 }
7580
John McCall9aa472c2010-03-19 07:35:19 +00007581 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007582 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +00007583
Douglas Gregor8ba10742008-11-20 16:27:02 +00007584 // Convert the object parameter.
7585 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00007586 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7587 Best->FoundDecl, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007588 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00007589
7590 // No concerns about early exits now.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007591 BaseIn.release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007592
7593 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00007594 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7595 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00007596 UsualUnaryConversions(FnExpr);
Anders Carlsson15ea3782009-10-13 22:43:21 +00007597
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007598 QualType ResultTy = Method->getCallResultType();
Anders Carlsson15ea3782009-10-13 22:43:21 +00007599 ExprOwningPtr<CXXOperatorCallExpr>
7600 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7601 &Base, 1, ResultTy, OpLoc));
7602
7603 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
7604 Method))
7605 return ExprError();
7606 return move(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00007607}
7608
Douglas Gregor904eed32008-11-10 20:40:00 +00007609/// FixOverloadedFunctionReference - E is an expression that refers to
7610/// a C++ overloaded function (possibly with some parentheses and
7611/// perhaps a '&' around it). We have resolved the overloaded function
7612/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00007613/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +00007614Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +00007615 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00007616 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00007617 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7618 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00007619 if (SubExpr == PE->getSubExpr())
7620 return PE->Retain();
7621
7622 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7623 }
7624
7625 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00007626 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7627 Found, Fn);
Douglas Gregor097bfb12009-10-23 22:18:25 +00007628 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00007629 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00007630 "Implicit cast type cannot be determined from overload");
Douglas Gregor699ee522009-11-20 19:42:02 +00007631 if (SubExpr == ICE->getSubExpr())
7632 return ICE->Retain();
7633
7634 return new (Context) ImplicitCastExpr(ICE->getType(),
7635 ICE->getCastKind(),
Anders Carlssonf1b48b72010-04-24 16:57:13 +00007636 SubExpr, CXXBaseSpecifierArray(),
Sebastian Redl906082e2010-07-20 04:20:21 +00007637 ICE->getCategory());
Douglas Gregor699ee522009-11-20 19:42:02 +00007638 }
7639
7640 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007641 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00007642 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00007643 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7644 if (Method->isStatic()) {
7645 // Do nothing: static member functions aren't any different
7646 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00007647 } else {
John McCallf7a1a742009-11-24 19:00:30 +00007648 // Fix the sub expression, which really has to be an
7649 // UnresolvedLookupExpr holding an overloaded member function
7650 // or template.
John McCall6bb80172010-03-30 21:47:33 +00007651 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7652 Found, Fn);
John McCallba135432009-11-21 08:51:07 +00007653 if (SubExpr == UnOp->getSubExpr())
7654 return UnOp->Retain();
Douglas Gregor699ee522009-11-20 19:42:02 +00007655
John McCallba135432009-11-21 08:51:07 +00007656 assert(isa<DeclRefExpr>(SubExpr)
7657 && "fixed to something other than a decl ref");
7658 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7659 && "fixed to a member ref with no nested name qualifier");
7660
7661 // We have taken the address of a pointer to member
7662 // function. Perform the computation here so that we get the
7663 // appropriate pointer to member type.
7664 QualType ClassType
7665 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7666 QualType MemPtrType
7667 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7668
7669 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7670 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00007671 }
7672 }
John McCall6bb80172010-03-30 21:47:33 +00007673 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7674 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00007675 if (SubExpr == UnOp->getSubExpr())
7676 return UnOp->Retain();
Anders Carlsson96ad5332009-10-21 17:16:23 +00007677
Douglas Gregor699ee522009-11-20 19:42:02 +00007678 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7679 Context.getPointerType(SubExpr->getType()),
7680 UnOp->getOperatorLoc());
Douglas Gregor699ee522009-11-20 19:42:02 +00007681 }
John McCallba135432009-11-21 08:51:07 +00007682
7683 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00007684 // FIXME: avoid copy.
7685 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00007686 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00007687 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7688 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00007689 }
7690
John McCallba135432009-11-21 08:51:07 +00007691 return DeclRefExpr::Create(Context,
7692 ULE->getQualifier(),
7693 ULE->getQualifierRange(),
7694 Fn,
7695 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00007696 Fn->getType(),
7697 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00007698 }
7699
John McCall129e2df2009-11-30 22:42:35 +00007700 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00007701 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00007702 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7703 if (MemExpr->hasExplicitTemplateArgs()) {
7704 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7705 TemplateArgs = &TemplateArgsBuffer;
7706 }
John McCalld5532b62009-11-23 01:53:49 +00007707
John McCallaa81e162009-12-01 22:10:20 +00007708 Expr *Base;
7709
7710 // If we're filling in
7711 if (MemExpr->isImplicitAccess()) {
7712 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7713 return DeclRefExpr::Create(Context,
7714 MemExpr->getQualifier(),
7715 MemExpr->getQualifierRange(),
7716 Fn,
7717 MemExpr->getMemberLoc(),
7718 Fn->getType(),
7719 TemplateArgs);
Douglas Gregor828a1972010-01-07 23:12:05 +00007720 } else {
7721 SourceLocation Loc = MemExpr->getMemberLoc();
7722 if (MemExpr->getQualifier())
7723 Loc = MemExpr->getQualifierRange().getBegin();
7724 Base = new (Context) CXXThisExpr(Loc,
7725 MemExpr->getBaseType(),
7726 /*isImplicit=*/true);
7727 }
John McCallaa81e162009-12-01 22:10:20 +00007728 } else
7729 Base = MemExpr->getBase()->Retain();
7730
7731 return MemberExpr::Create(Context, Base,
Douglas Gregor699ee522009-11-20 19:42:02 +00007732 MemExpr->isArrow(),
7733 MemExpr->getQualifier(),
7734 MemExpr->getQualifierRange(),
7735 Fn,
John McCall6bb80172010-03-30 21:47:33 +00007736 Found,
John McCalld5532b62009-11-23 01:53:49 +00007737 MemExpr->getMemberLoc(),
John McCallaa81e162009-12-01 22:10:20 +00007738 TemplateArgs,
Douglas Gregor699ee522009-11-20 19:42:02 +00007739 Fn->getType());
7740 }
7741
Douglas Gregor699ee522009-11-20 19:42:02 +00007742 assert(false && "Invalid reference to overloaded function");
7743 return E->Retain();
Douglas Gregor904eed32008-11-10 20:40:00 +00007744}
7745
Douglas Gregor20093b42009-12-09 23:02:17 +00007746Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCall161755a2010-04-06 21:38:20 +00007747 DeclAccessPair Found,
Douglas Gregor20093b42009-12-09 23:02:17 +00007748 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +00007749 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +00007750}
7751
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007752} // end namespace clang