blob: 3ed79fd4613c0e3749687ce1937e738760ea3f59 [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
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCall7cd088e2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000021#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000024#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000026#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000027#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor661b4932010-09-12 04:28:07 +000028#include "llvm/ADT/DenseSet.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000029#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000030#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000031#include <algorithm>
32
33namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000034using namespace sema;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000035
John McCall120d63c2010-08-24 20:38:10 +000036static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
37 bool InOverloadResolution,
38 StandardConversionSequence &SCS);
39static OverloadingResult
40IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
41 UserDefinedConversionSequence& User,
42 OverloadCandidateSet& Conversions,
43 bool AllowExplicit);
44
45
46static ImplicitConversionSequence::CompareKind
47CompareStandardConversionSequences(Sema &S,
48 const StandardConversionSequence& SCS1,
49 const StandardConversionSequence& SCS2);
50
51static ImplicitConversionSequence::CompareKind
52CompareQualificationConversions(Sema &S,
53 const StandardConversionSequence& SCS1,
54 const StandardConversionSequence& SCS2);
55
56static ImplicitConversionSequence::CompareKind
57CompareDerivedToBaseConversions(Sema &S,
58 const StandardConversionSequence& SCS1,
59 const StandardConversionSequence& SCS2);
60
61
62
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000063/// GetConversionCategory - Retrieve the implicit conversion
64/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000065ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000066GetConversionCategory(ImplicitConversionKind Kind) {
67 static const ImplicitConversionCategory
68 Category[(int)ICK_Num_Conversion_Kinds] = {
69 ICC_Identity,
70 ICC_Lvalue_Transformation,
71 ICC_Lvalue_Transformation,
72 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +000073 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000074 ICC_Qualification_Adjustment,
75 ICC_Promotion,
76 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000077 ICC_Promotion,
78 ICC_Conversion,
79 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000080 ICC_Conversion,
81 ICC_Conversion,
82 ICC_Conversion,
83 ICC_Conversion,
84 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000085 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000086 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +000087 ICC_Conversion,
88 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000089 ICC_Conversion
90 };
91 return Category[(int)Kind];
92}
93
94/// GetConversionRank - Retrieve the implicit conversion rank
95/// corresponding to the given implicit conversion kind.
96ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
97 static const ImplicitConversionRank
98 Rank[(int)ICK_Num_Conversion_Kinds] = {
99 ICR_Exact_Match,
100 ICR_Exact_Match,
101 ICR_Exact_Match,
102 ICR_Exact_Match,
103 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000104 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000105 ICR_Promotion,
106 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000107 ICR_Promotion,
108 ICR_Conversion,
109 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000110 ICR_Conversion,
111 ICR_Conversion,
112 ICR_Conversion,
113 ICR_Conversion,
114 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000115 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000116 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000117 ICR_Conversion,
118 ICR_Conversion,
Chandler Carruth23a370f2010-02-25 07:20:54 +0000119 ICR_Complex_Real_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000120 };
121 return Rank[(int)Kind];
122}
123
124/// GetImplicitConversionName - Return the name of this kind of
125/// implicit conversion.
126const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +0000127 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000128 "No conversion",
129 "Lvalue-to-rvalue",
130 "Array-to-pointer",
131 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000132 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000133 "Qualification",
134 "Integral promotion",
135 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000136 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000137 "Integral conversion",
138 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000139 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000140 "Floating-integral conversion",
141 "Pointer conversion",
142 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000143 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000144 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000145 "Derived-to-base conversion",
146 "Vector conversion",
147 "Vector splat",
148 "Complex-real conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000149 };
150 return Name[Kind];
151}
152
Douglas Gregor60d62c22008-10-31 16:23:19 +0000153/// StandardConversionSequence - Set the standard conversion
154/// sequence to the identity conversion.
155void StandardConversionSequence::setAsIdentityConversion() {
156 First = ICK_Identity;
157 Second = ICK_Identity;
158 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000159 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000160 ReferenceBinding = false;
161 DirectBinding = false;
Sebastian Redl85002392009-03-29 22:46:24 +0000162 RRefBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000163 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000164}
165
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000166/// getRank - Retrieve the rank of this standard conversion sequence
167/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
168/// implicit conversions.
169ImplicitConversionRank StandardConversionSequence::getRank() const {
170 ImplicitConversionRank Rank = ICR_Exact_Match;
171 if (GetConversionRank(First) > Rank)
172 Rank = GetConversionRank(First);
173 if (GetConversionRank(Second) > Rank)
174 Rank = GetConversionRank(Second);
175 if (GetConversionRank(Third) > Rank)
176 Rank = GetConversionRank(Third);
177 return Rank;
178}
179
180/// isPointerConversionToBool - Determines whether this conversion is
181/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000182/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000183/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000184bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000185 // Note that FromType has not necessarily been transformed by the
186 // array-to-pointer or function-to-pointer implicit conversions, so
187 // check for their presence as well as checking whether FromType is
188 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000189 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000190 (getFromType()->isPointerType() ||
191 getFromType()->isObjCObjectPointerType() ||
192 getFromType()->isBlockPointerType() ||
Anders Carlssonc8df0b62010-11-05 00:12:09 +0000193 getFromType()->isNullPtrType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000194 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
195 return true;
196
197 return false;
198}
199
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000200/// isPointerConversionToVoidPointer - Determines whether this
201/// conversion is a conversion of a pointer to a void pointer. This is
202/// used as part of the ranking of standard conversion sequences (C++
203/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000204bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000205StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000206isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000207 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000208 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000209
210 // Note that FromType has not necessarily been transformed by the
211 // array-to-pointer implicit conversion, so check for its presence
212 // and redo the conversion to get a pointer.
213 if (First == ICK_Array_To_Pointer)
214 FromType = Context.getArrayDecayedType(FromType);
215
John McCall202422e2010-10-26 06:40:27 +0000216 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000217 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000218 return ToPtrType->getPointeeType()->isVoidType();
219
220 return false;
221}
222
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000223/// DebugPrint - Print this standard conversion sequence to standard
224/// error. Useful for debugging overloading issues.
225void StandardConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000226 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000227 bool PrintedSomething = false;
228 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000229 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000230 PrintedSomething = true;
231 }
232
233 if (Second != ICK_Identity) {
234 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000235 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000236 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000237 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000238
239 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000240 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000241 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000242 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000243 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000244 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000245 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000246 PrintedSomething = true;
247 }
248
249 if (Third != ICK_Identity) {
250 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000251 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000252 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000253 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000254 PrintedSomething = true;
255 }
256
257 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000258 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000259 }
260}
261
262/// DebugPrint - Print this user-defined conversion sequence to standard
263/// error. Useful for debugging overloading issues.
264void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000265 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000266 if (Before.First || Before.Second || Before.Third) {
267 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000268 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000269 }
Benjamin Kramer900fc632010-04-17 09:33:03 +0000270 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000271 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000272 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000273 After.DebugPrint();
274 }
275}
276
277/// DebugPrint - Print this implicit conversion sequence to standard
278/// error. Useful for debugging overloading issues.
279void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000280 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000281 switch (ConversionKind) {
282 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000283 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000284 Standard.DebugPrint();
285 break;
286 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000287 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000288 UserDefined.DebugPrint();
289 break;
290 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000291 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000292 break;
John McCall1d318332010-01-12 00:44:57 +0000293 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000294 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000295 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000296 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000297 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000298 break;
299 }
300
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000301 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000302}
303
John McCall1d318332010-01-12 00:44:57 +0000304void AmbiguousConversionSequence::construct() {
305 new (&conversions()) ConversionSet();
306}
307
308void AmbiguousConversionSequence::destruct() {
309 conversions().~ConversionSet();
310}
311
312void
313AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
314 FromTypePtr = O.FromTypePtr;
315 ToTypePtr = O.ToTypePtr;
316 new (&conversions()) ConversionSet(O.conversions());
317}
318
Douglas Gregora9333192010-05-08 17:41:32 +0000319namespace {
320 // Structure used by OverloadCandidate::DeductionFailureInfo to store
321 // template parameter and template argument information.
322 struct DFIParamWithArguments {
323 TemplateParameter Param;
324 TemplateArgument FirstArg;
325 TemplateArgument SecondArg;
326 };
327}
328
329/// \brief Convert from Sema's representation of template deduction information
330/// to the form used in overload-candidate information.
331OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000332static MakeDeductionFailureInfo(ASTContext &Context,
333 Sema::TemplateDeductionResult TDK,
John McCall2a7fb272010-08-25 05:32:35 +0000334 TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000335 OverloadCandidate::DeductionFailureInfo Result;
336 Result.Result = static_cast<unsigned>(TDK);
337 Result.Data = 0;
338 switch (TDK) {
339 case Sema::TDK_Success:
340 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000341 case Sema::TDK_TooManyArguments:
342 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000343 break;
344
345 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000346 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000347 Result.Data = Info.Param.getOpaqueValue();
348 break;
349
Douglas Gregora9333192010-05-08 17:41:32 +0000350 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000351 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000352 // FIXME: Should allocate from normal heap so that we can free this later.
353 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000354 Saved->Param = Info.Param;
355 Saved->FirstArg = Info.FirstArg;
356 Saved->SecondArg = Info.SecondArg;
357 Result.Data = Saved;
358 break;
359 }
360
361 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000362 Result.Data = Info.take();
363 break;
364
Douglas Gregora9333192010-05-08 17:41:32 +0000365 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000366 case Sema::TDK_FailedOverloadResolution:
367 break;
368 }
369
370 return Result;
371}
John McCall1d318332010-01-12 00:44:57 +0000372
Douglas Gregora9333192010-05-08 17:41:32 +0000373void OverloadCandidate::DeductionFailureInfo::Destroy() {
374 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
375 case Sema::TDK_Success:
376 case Sema::TDK_InstantiationDepth:
377 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000378 case Sema::TDK_TooManyArguments:
379 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000380 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000381 break;
382
Douglas Gregora9333192010-05-08 17:41:32 +0000383 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000384 case Sema::TDK_Underqualified:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000385 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000386 Data = 0;
387 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000388
389 case Sema::TDK_SubstitutionFailure:
390 // FIXME: Destroy the template arugment list?
391 Data = 0;
392 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000393
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000394 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000395 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000396 case Sema::TDK_FailedOverloadResolution:
397 break;
398 }
399}
400
401TemplateParameter
402OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
403 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
404 case Sema::TDK_Success:
405 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000406 case Sema::TDK_TooManyArguments:
407 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000408 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000409 return TemplateParameter();
410
411 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000412 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000413 return TemplateParameter::getFromOpaqueValue(Data);
414
415 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000416 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000417 return static_cast<DFIParamWithArguments*>(Data)->Param;
418
419 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000420 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000421 case Sema::TDK_FailedOverloadResolution:
422 break;
423 }
424
425 return TemplateParameter();
426}
Douglas Gregorec20f462010-05-08 20:07:26 +0000427
428TemplateArgumentList *
429OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
430 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
431 case Sema::TDK_Success:
432 case Sema::TDK_InstantiationDepth:
433 case Sema::TDK_TooManyArguments:
434 case Sema::TDK_TooFewArguments:
435 case Sema::TDK_Incomplete:
436 case Sema::TDK_InvalidExplicitArguments:
437 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000438 case Sema::TDK_Underqualified:
Douglas Gregorec20f462010-05-08 20:07:26 +0000439 return 0;
440
441 case Sema::TDK_SubstitutionFailure:
442 return static_cast<TemplateArgumentList*>(Data);
443
444 // Unhandled
445 case Sema::TDK_NonDeducedMismatch:
446 case Sema::TDK_FailedOverloadResolution:
447 break;
448 }
449
450 return 0;
451}
452
Douglas Gregora9333192010-05-08 17:41:32 +0000453const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
454 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
455 case Sema::TDK_Success:
456 case Sema::TDK_InstantiationDepth:
457 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000458 case Sema::TDK_TooManyArguments:
459 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000460 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000461 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000462 return 0;
463
Douglas Gregora9333192010-05-08 17:41:32 +0000464 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000465 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000466 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
467
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000468 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000469 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000470 case Sema::TDK_FailedOverloadResolution:
471 break;
472 }
473
474 return 0;
475}
476
477const TemplateArgument *
478OverloadCandidate::DeductionFailureInfo::getSecondArg() {
479 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
480 case Sema::TDK_Success:
481 case Sema::TDK_InstantiationDepth:
482 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000483 case Sema::TDK_TooManyArguments:
484 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000485 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000486 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000487 return 0;
488
Douglas Gregora9333192010-05-08 17:41:32 +0000489 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000490 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000491 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
492
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000493 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000494 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000495 case Sema::TDK_FailedOverloadResolution:
496 break;
497 }
498
499 return 0;
500}
501
502void OverloadCandidateSet::clear() {
Douglas Gregora9333192010-05-08 17:41:32 +0000503 inherited::clear();
504 Functions.clear();
505}
506
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000507// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000508// overload of the declarations in Old. This routine returns false if
509// New and Old cannot be overloaded, e.g., if New has the same
510// signature as some function in Old (C++ 1.3.10) or if the Old
511// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000512// it does return false, MatchedDecl will point to the decl that New
513// cannot be overloaded with. This decl may be a UsingShadowDecl on
514// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000515//
516// Example: Given the following input:
517//
518// void f(int, float); // #1
519// void f(int, int); // #2
520// int f(int, int); // #3
521//
522// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000523// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000524//
John McCall51fa86f2009-12-02 08:47:38 +0000525// When we process #2, Old contains only the FunctionDecl for #1. By
526// comparing the parameter types, we see that #1 and #2 are overloaded
527// (since they have different signatures), so this routine returns
528// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000529//
John McCall51fa86f2009-12-02 08:47:38 +0000530// When we process #3, Old is an overload set containing #1 and #2. We
531// compare the signatures of #3 to #1 (they're overloaded, so we do
532// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
533// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000534// signature), IsOverload returns false and MatchedDecl will be set to
535// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000536//
537// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
538// into a class by a using declaration. The rules for whether to hide
539// shadow declarations ignore some properties which otherwise figure
540// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000541Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000542Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
543 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000544 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000545 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000546 NamedDecl *OldD = *I;
547
548 bool OldIsUsingDecl = false;
549 if (isa<UsingShadowDecl>(OldD)) {
550 OldIsUsingDecl = true;
551
552 // We can always introduce two using declarations into the same
553 // context, even if they have identical signatures.
554 if (NewIsUsingDecl) continue;
555
556 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
557 }
558
559 // If either declaration was introduced by a using declaration,
560 // we'll need to use slightly different rules for matching.
561 // Essentially, these rules are the normal rules, except that
562 // function templates hide function templates with different
563 // return types or template parameter lists.
564 bool UseMemberUsingDeclRules =
565 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
566
John McCall51fa86f2009-12-02 08:47:38 +0000567 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000568 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
569 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
570 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
571 continue;
572 }
573
John McCall871b2e72009-12-09 03:35:25 +0000574 Match = *I;
575 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000576 }
John McCall51fa86f2009-12-02 08:47:38 +0000577 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000578 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
579 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
580 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
581 continue;
582 }
583
John McCall871b2e72009-12-09 03:35:25 +0000584 Match = *I;
585 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000586 }
John McCall9f54ad42009-12-10 09:41:52 +0000587 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
588 // We can overload with these, which can show up when doing
589 // redeclaration checks for UsingDecls.
590 assert(Old.getLookupKind() == LookupUsingDeclName);
591 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
592 // Optimistically assume that an unresolved using decl will
593 // overload; if it doesn't, we'll have to diagnose during
594 // template instantiation.
595 } else {
John McCall68263142009-11-18 22:49:29 +0000596 // (C++ 13p1):
597 // Only function declarations can be overloaded; object and type
598 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000599 Match = *I;
600 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000601 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000602 }
John McCall68263142009-11-18 22:49:29 +0000603
John McCall871b2e72009-12-09 03:35:25 +0000604 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000605}
606
John McCallad00b772010-06-16 08:42:20 +0000607bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
608 bool UseUsingDeclRules) {
John McCall7b492022010-08-12 07:09:11 +0000609 // If both of the functions are extern "C", then they are not
610 // overloads.
611 if (Old->isExternC() && New->isExternC())
612 return false;
613
John McCall68263142009-11-18 22:49:29 +0000614 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
615 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
616
617 // C++ [temp.fct]p2:
618 // A function template can be overloaded with other function templates
619 // and with normal (non-template) functions.
620 if ((OldTemplate == 0) != (NewTemplate == 0))
621 return true;
622
623 // Is the function New an overload of the function Old?
624 QualType OldQType = Context.getCanonicalType(Old->getType());
625 QualType NewQType = Context.getCanonicalType(New->getType());
626
627 // Compare the signatures (C++ 1.3.10) of the two functions to
628 // determine whether they are overloads. If we find any mismatch
629 // in the signature, they are overloads.
630
631 // If either of these functions is a K&R-style function (no
632 // prototype), then we consider them to have matching signatures.
633 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
634 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
635 return false;
636
637 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
638 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
639
640 // The signature of a function includes the types of its
641 // parameters (C++ 1.3.10), which includes the presence or absence
642 // of the ellipsis; see C++ DR 357).
643 if (OldQType != NewQType &&
644 (OldType->getNumArgs() != NewType->getNumArgs() ||
645 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000646 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000647 return true;
648
649 // C++ [temp.over.link]p4:
650 // The signature of a function template consists of its function
651 // signature, its return type and its template parameter list. The names
652 // of the template parameters are significant only for establishing the
653 // relationship between the template parameters and the rest of the
654 // signature.
655 //
656 // We check the return type and template parameter lists for function
657 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +0000658 //
659 // However, we don't consider either of these when deciding whether
660 // a member introduced by a shadow declaration is hidden.
661 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +0000662 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
663 OldTemplate->getTemplateParameters(),
664 false, TPL_TemplateMatch) ||
665 OldType->getResultType() != NewType->getResultType()))
666 return true;
667
668 // If the function is a class member, its signature includes the
669 // cv-qualifiers (if any) on the function itself.
670 //
671 // As part of this, also check whether one of the member functions
672 // is static, in which case they are not overloads (C++
673 // 13.1p2). While not part of the definition of the signature,
674 // this check is important to determine whether these functions
675 // can be overloaded.
676 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
677 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
678 if (OldMethod && NewMethod &&
679 !OldMethod->isStatic() && !NewMethod->isStatic() &&
680 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
681 return true;
682
683 // The signatures match; this is not an overload.
684 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000685}
686
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000687/// TryImplicitConversion - Attempt to perform an implicit conversion
688/// from the given expression (Expr) to the given type (ToType). This
689/// function returns an implicit conversion sequence that can be used
690/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000691///
692/// void f(float f);
693/// void g(int i) { f(i); }
694///
695/// this routine would produce an implicit conversion sequence to
696/// describe the initialization of f from i, which will be a standard
697/// conversion sequence containing an lvalue-to-rvalue conversion (C++
698/// 4.1) followed by a floating-integral conversion (C++ 4.9).
699//
700/// Note that this routine only determines how the conversion can be
701/// performed; it does not actually perform the conversion. As such,
702/// it will not produce any diagnostics if no conversion is available,
703/// but will instead return an implicit conversion sequence of kind
704/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000705///
706/// If @p SuppressUserConversions, then user-defined conversions are
707/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000708/// If @p AllowExplicit, then explicit user-defined conversions are
709/// permitted.
John McCall120d63c2010-08-24 20:38:10 +0000710static ImplicitConversionSequence
711TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
712 bool SuppressUserConversions,
713 bool AllowExplicit,
714 bool InOverloadResolution) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000715 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +0000716 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
717 ICS.Standard)) {
John McCall1d318332010-01-12 00:44:57 +0000718 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +0000719 return ICS;
720 }
721
John McCall120d63c2010-08-24 20:38:10 +0000722 if (!S.getLangOptions().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +0000723 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +0000724 return ICS;
725 }
726
Douglas Gregor604eb652010-08-11 02:15:33 +0000727 // C++ [over.ics.user]p4:
728 // A conversion of an expression of class type to the same class
729 // type is given Exact Match rank, and a conversion of an
730 // expression of class type to a base class of that type is
731 // given Conversion rank, in spite of the fact that a copy/move
732 // constructor (i.e., a user-defined conversion function) is
733 // called for those cases.
734 QualType FromType = From->getType();
735 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +0000736 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
737 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000738 ICS.setStandard();
739 ICS.Standard.setAsIdentityConversion();
740 ICS.Standard.setFromType(FromType);
741 ICS.Standard.setAllToTypes(ToType);
742
743 // We don't actually check at this point whether there is a valid
744 // copy/move constructor, since overloading just assumes that it
745 // exists. When we actually perform initialization, we'll find the
746 // appropriate constructor to copy the returned object, if needed.
747 ICS.Standard.CopyConstructor = 0;
Douglas Gregor604eb652010-08-11 02:15:33 +0000748
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000749 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +0000750 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000751 ICS.Standard.Second = ICK_Derived_To_Base;
Douglas Gregor604eb652010-08-11 02:15:33 +0000752
753 return ICS;
754 }
755
756 if (SuppressUserConversions) {
757 // We're not in the case above, so there is no conversion that
758 // we can perform.
759 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000760 return ICS;
761 }
762
763 // Attempt user-defined conversion.
John McCall5769d612010-02-08 23:07:23 +0000764 OverloadCandidateSet Conversions(From->getExprLoc());
765 OverloadingResult UserDefResult
John McCall120d63c2010-08-24 20:38:10 +0000766 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000767 AllowExplicit);
John McCall5769d612010-02-08 23:07:23 +0000768
769 if (UserDefResult == OR_Success) {
John McCall1d318332010-01-12 00:44:57 +0000770 ICS.setUserDefined();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000771 // C++ [over.ics.user]p4:
772 // A conversion of an expression of class type to the same class
773 // type is given Exact Match rank, and a conversion of an
774 // expression of class type to a base class of that type is
775 // given Conversion rank, in spite of the fact that a copy
776 // constructor (i.e., a user-defined conversion function) is
777 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000778 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000779 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000780 QualType FromCanon
John McCall120d63c2010-08-24 20:38:10 +0000781 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
782 QualType ToCanon
783 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor9e9199d2009-12-22 00:34:07 +0000784 if (Constructor->isCopyConstructor() &&
John McCall120d63c2010-08-24 20:38:10 +0000785 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000786 // Turn this into a "standard" conversion sequence, so that it
787 // gets ranked with standard conversion sequences.
John McCall1d318332010-01-12 00:44:57 +0000788 ICS.setStandard();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000789 ICS.Standard.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +0000790 ICS.Standard.setFromType(From->getType());
Douglas Gregorad323a82010-01-27 03:51:04 +0000791 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000792 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000793 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000794 ICS.Standard.Second = ICK_Derived_To_Base;
795 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000796 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000797
798 // C++ [over.best.ics]p4:
799 // However, when considering the argument of a user-defined
800 // conversion function that is a candidate by 13.3.1.3 when
801 // invoked for the copying of the temporary in the second step
802 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
803 // 13.3.1.6 in all cases, only standard conversion sequences and
804 // ellipsis conversion sequences are allowed.
John McCalladbb8f82010-01-13 09:16:55 +0000805 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCallb1bdc622010-02-25 01:37:24 +0000806 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCalladbb8f82010-01-13 09:16:55 +0000807 }
John McCallcefd3ad2010-01-13 22:30:33 +0000808 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall1d318332010-01-12 00:44:57 +0000809 ICS.setAmbiguous();
810 ICS.Ambiguous.setFromType(From->getType());
811 ICS.Ambiguous.setToType(ToType);
812 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
813 Cand != Conversions.end(); ++Cand)
814 if (Cand->Viable)
815 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000816 } else {
John McCallb1bdc622010-02-25 01:37:24 +0000817 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000818 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000819
820 return ICS;
821}
822
John McCall120d63c2010-08-24 20:38:10 +0000823bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
824 const InitializedEntity &Entity,
825 Expr *Initializer,
826 bool SuppressUserConversions,
827 bool AllowExplicitConversions,
828 bool InOverloadResolution) {
829 ImplicitConversionSequence ICS
830 = clang::TryImplicitConversion(*this, Initializer, Entity.getType(),
831 SuppressUserConversions,
832 AllowExplicitConversions,
833 InOverloadResolution);
834 if (ICS.isBad()) return true;
835
836 // Perform the actual conversion.
837 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
838 return false;
839}
840
Douglas Gregor575c63a2010-04-16 22:27:05 +0000841/// PerformImplicitConversion - Perform an implicit conversion of the
842/// expression From to the type ToType. Returns true if there was an
843/// error, false otherwise. The expression From is replaced with the
844/// converted expression. Flavor is the kind of conversion we're
845/// performing, used in the error message. If @p AllowExplicit,
846/// explicit user-defined conversions are permitted.
847bool
848Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
849 AssignmentAction Action, bool AllowExplicit) {
850 ImplicitConversionSequence ICS;
851 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
852}
853
854bool
855Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
856 AssignmentAction Action, bool AllowExplicit,
857 ImplicitConversionSequence& ICS) {
John McCall120d63c2010-08-24 20:38:10 +0000858 ICS = clang::TryImplicitConversion(*this, From, ToType,
859 /*SuppressUserConversions=*/false,
860 AllowExplicit,
861 /*InOverloadResolution=*/false);
Douglas Gregor575c63a2010-04-16 22:27:05 +0000862 return PerformImplicitConversion(From, ToType, ICS, Action);
863}
864
Douglas Gregor43c79c22009-12-09 00:47:37 +0000865/// \brief Determine whether the conversion from FromType to ToType is a valid
866/// conversion that strips "noreturn" off the nested function type.
867static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
868 QualType ToType, QualType &ResultTy) {
869 if (Context.hasSameUnqualifiedType(FromType, ToType))
870 return false;
871
872 // Strip the noreturn off the type we're converting from; noreturn can
873 // safely be removed.
874 FromType = Context.getNoReturnType(FromType, false);
875 if (!Context.hasSameUnqualifiedType(FromType, ToType))
876 return false;
877
878 ResultTy = FromType;
879 return true;
880}
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000881
882/// \brief Determine whether the conversion from FromType to ToType is a valid
883/// vector conversion.
884///
885/// \param ICK Will be set to the vector conversion kind, if this is a vector
886/// conversion.
887static bool IsVectorConversion(ASTContext &Context, QualType FromType,
888 QualType ToType, ImplicitConversionKind &ICK) {
889 // We need at least one of these types to be a vector type to have a vector
890 // conversion.
891 if (!ToType->isVectorType() && !FromType->isVectorType())
892 return false;
893
894 // Identical types require no conversions.
895 if (Context.hasSameUnqualifiedType(FromType, ToType))
896 return false;
897
898 // There are no conversions between extended vector types, only identity.
899 if (ToType->isExtVectorType()) {
900 // There are no conversions between extended vector types other than the
901 // identity conversion.
902 if (FromType->isExtVectorType())
903 return false;
904
905 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +0000906 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000907 ICK = ICK_Vector_Splat;
908 return true;
909 }
910 }
Douglas Gregor255210e2010-08-06 10:14:59 +0000911
912 // We can perform the conversion between vector types in the following cases:
913 // 1)vector types are equivalent AltiVec and GCC vector types
914 // 2)lax vector conversions are permitted and the vector types are of the
915 // same size
916 if (ToType->isVectorType() && FromType->isVectorType()) {
917 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruthc45eb9c2010-08-08 05:02:51 +0000918 (Context.getLangOptions().LaxVectorConversions &&
919 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +0000920 ICK = ICK_Vector_Conversion;
921 return true;
922 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000923 }
Douglas Gregor255210e2010-08-06 10:14:59 +0000924
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000925 return false;
926}
Douglas Gregor43c79c22009-12-09 00:47:37 +0000927
Douglas Gregor60d62c22008-10-31 16:23:19 +0000928/// IsStandardConversion - Determines whether there is a standard
929/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
930/// expression From to the type ToType. Standard conversion sequences
931/// only consider non-class types; for conversions that involve class
932/// types, use TryImplicitConversion. If a conversion exists, SCS will
933/// contain the standard conversion sequence required to perform this
934/// conversion and this routine will return true. Otherwise, this
935/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +0000936static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
937 bool InOverloadResolution,
938 StandardConversionSequence &SCS) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000939 QualType FromType = From->getType();
John McCall120d63c2010-08-24 20:38:10 +0000940
Douglas Gregor60d62c22008-10-31 16:23:19 +0000941 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000942 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +0000943 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000944 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +0000945 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000946 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000947
Douglas Gregorf9201e02009-02-11 23:02:49 +0000948 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +0000949 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +0000950 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall120d63c2010-08-24 20:38:10 +0000951 if (S.getLangOptions().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000952 return false;
953
Mike Stump1eb44332009-09-09 15:08:12 +0000954 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000955 }
956
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000957 // The first conversion can be an lvalue-to-rvalue conversion,
958 // array-to-pointer conversion, or function-to-pointer conversion
959 // (C++ 4p1).
960
John McCall120d63c2010-08-24 20:38:10 +0000961 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000962 DeclAccessPair AccessPair;
963 if (FunctionDecl *Fn
John McCall120d63c2010-08-24 20:38:10 +0000964 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
965 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000966 // We were able to resolve the address of the overloaded function,
967 // so we can convert to the type of that function.
968 FromType = Fn->getType();
969 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
970 if (!Method->isStatic()) {
971 Type *ClassType
John McCall120d63c2010-08-24 20:38:10 +0000972 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
973 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000974 }
975 }
976
977 // If the "from" expression takes the address of the overloaded
978 // function, update the type of the resulting expression accordingly.
979 if (FromType->getAs<FunctionType>())
980 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
John McCall2de56d12010-08-25 11:45:40 +0000981 if (UnOp->getOpcode() == UO_AddrOf)
John McCall120d63c2010-08-24 20:38:10 +0000982 FromType = S.Context.getPointerType(FromType);
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000983
984 // Check that we've computed the proper type after overload resolution.
John McCall120d63c2010-08-24 20:38:10 +0000985 assert(S.Context.hasSameType(FromType,
986 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000987 } else {
988 return false;
989 }
Anders Carlsson2bd62502010-11-04 05:28:09 +0000990 }
Mike Stump1eb44332009-09-09 15:08:12 +0000991 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000992 // An lvalue (3.10) of a non-function, non-array type T can be
993 // converted to an rvalue.
John McCall120d63c2010-08-24 20:38:10 +0000994 Expr::isLvalueResult argIsLvalue = From->isLvalue(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000995 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000996 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +0000997 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000998 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000999
1000 // If T is a non-class type, the type of the rvalue is the
1001 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001002 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1003 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001004 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001005 } else if (FromType->isArrayType()) {
1006 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001007 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001008
1009 // An lvalue or rvalue of type "array of N T" or "array of unknown
1010 // bound of T" can be converted to an rvalue of type "pointer to
1011 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001012 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001013
John McCall120d63c2010-08-24 20:38:10 +00001014 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001015 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001016 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001017
1018 // For the purpose of ranking in overload resolution
1019 // (13.3.3.1.1), this conversion is considered an
1020 // array-to-pointer conversion followed by a qualification
1021 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001022 SCS.Second = ICK_Identity;
1023 SCS.Third = ICK_Qualification;
Douglas Gregorad323a82010-01-27 03:51:04 +00001024 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001025 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001026 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001027 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
1028 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001029 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001030
1031 // An lvalue of function type T can be converted to an rvalue of
1032 // type "pointer to T." The result is a pointer to the
1033 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001034 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001035 } else {
1036 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001037 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001038 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001039 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001040
1041 // The second conversion can be an integral promotion, floating
1042 // point promotion, integral conversion, floating point conversion,
1043 // floating-integral conversion, pointer conversion,
1044 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001045 // For overloading in C, this can also be a "compatible-type"
1046 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001047 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001048 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001049 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001050 // The unqualified versions of the types are the same: there's no
1051 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001052 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001053 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001054 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001055 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001056 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001057 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001058 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001059 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001060 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001061 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001062 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001063 SCS.Second = ICK_Complex_Promotion;
1064 FromType = ToType.getUnqualifiedType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001065 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001066 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001067 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001068 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001069 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001070 } else if (FromType->isComplexType() && ToType->isComplexType()) {
1071 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001072 SCS.Second = ICK_Complex_Conversion;
1073 FromType = ToType.getUnqualifiedType();
Chandler Carruth23a370f2010-02-25 07:20:54 +00001074 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
1075 (ToType->isComplexType() && FromType->isArithmeticType())) {
1076 // Complex-real conversions (C99 6.3.1.7)
1077 SCS.Second = ICK_Complex_Real;
1078 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001079 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001080 // Floating point conversions (C++ 4.8).
1081 SCS.Second = ICK_Floating_Conversion;
1082 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001083 } else if ((FromType->isRealFloatingType() &&
John McCall120d63c2010-08-24 20:38:10 +00001084 ToType->isIntegralType(S.Context) && !ToType->isBooleanType()) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001085 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001086 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001087 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001088 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001089 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001090 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1091 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001092 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001093 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001094 SCS.IncompatibleObjC = IncompatibleObjC;
John McCall120d63c2010-08-24 20:38:10 +00001095 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1096 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001097 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001098 SCS.Second = ICK_Pointer_Member;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001099 } else if (ToType->isBooleanType() &&
1100 (FromType->isArithmeticType() ||
Fariborz Jahanian1f7711d2009-12-11 21:23:13 +00001101 FromType->isAnyPointerType() ||
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001102 FromType->isBlockPointerType() ||
1103 FromType->isMemberPointerType() ||
Douglas Gregor00619622010-06-22 23:41:02 +00001104 FromType->isNullPtrType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001105 // Boolean conversions (C++ 4.12).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001106 SCS.Second = ICK_Boolean_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001107 FromType = S.Context.BoolTy;
1108 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001109 SCS.Second = SecondICK;
1110 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001111 } else if (!S.getLangOptions().CPlusPlus &&
1112 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001113 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001114 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001115 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001116 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001117 // Treat a conversion that strips "noreturn" as an identity conversion.
1118 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001119 } else {
1120 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001121 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001122 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001123 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001124
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001125 QualType CanonFrom;
1126 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001127 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall120d63c2010-08-24 20:38:10 +00001128 if (S.IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001129 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001130 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001131 CanonFrom = S.Context.getCanonicalType(FromType);
1132 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001133 } else {
1134 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001135 SCS.Third = ICK_Identity;
1136
Mike Stump1eb44332009-09-09 15:08:12 +00001137 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001138 // [...] Any difference in top-level cv-qualification is
1139 // subsumed by the initialization itself and does not constitute
1140 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001141 CanonFrom = S.Context.getCanonicalType(FromType);
1142 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00001143 if (CanonFrom.getLocalUnqualifiedType()
1144 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001145 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1146 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001147 FromType = ToType;
1148 CanonFrom = CanonTo;
1149 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001150 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001151 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001152
1153 // If we have not converted the argument type to the parameter type,
1154 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001155 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001156 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001157
Douglas Gregor60d62c22008-10-31 16:23:19 +00001158 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001159}
1160
1161/// IsIntegralPromotion - Determines whether the conversion from the
1162/// expression From (whose potentially-adjusted type is FromType) to
1163/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1164/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001165bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001166 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001167 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001168 if (!To) {
1169 return false;
1170 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001171
1172 // An rvalue of type char, signed char, unsigned char, short int, or
1173 // unsigned short int can be converted to an rvalue of type int if
1174 // int can represent all the values of the source type; otherwise,
1175 // the source rvalue can be converted to an rvalue of type unsigned
1176 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001177 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1178 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001179 if (// We can promote any signed, promotable integer type to an int
1180 (FromType->isSignedIntegerType() ||
1181 // We can promote any unsigned integer type whose size is
1182 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001183 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001184 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001185 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001186 }
1187
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001188 return To->getKind() == BuiltinType::UInt;
1189 }
1190
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001191 // C++0x [conv.prom]p3:
1192 // A prvalue of an unscoped enumeration type whose underlying type is not
1193 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1194 // following types that can represent all the values of the enumeration
1195 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1196 // unsigned int, long int, unsigned long int, long long int, or unsigned
1197 // long long int. If none of the types in that list can represent all the
1198 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1199 // type can be converted to an rvalue a prvalue of the extended integer type
1200 // with lowest integer conversion rank (4.13) greater than the rank of long
1201 // long in which all the values of the enumeration can be represented. If
1202 // there are two such extended types, the signed one is chosen.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001203 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1204 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1205 // provided for a scoped enumeration.
1206 if (FromEnumType->getDecl()->isScoped())
1207 return false;
1208
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001209 // We have already pre-calculated the promotion type, so this is trivial.
Douglas Gregor5dde1602010-09-12 03:38:25 +00001210 if (ToType->isIntegerType() &&
1211 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall842aef82009-12-09 09:09:27 +00001212 return Context.hasSameUnqualifiedType(ToType,
1213 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001214 }
John McCall842aef82009-12-09 09:09:27 +00001215
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001216 // C++0x [conv.prom]p2:
1217 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1218 // to an rvalue a prvalue of the first of the following types that can
1219 // represent all the values of its underlying type: int, unsigned int,
1220 // long int, unsigned long int, long long int, or unsigned long long int.
1221 // If none of the types in that list can represent all the values of its
1222 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
1223 // or wchar_t can be converted to an rvalue a prvalue of its underlying
1224 // type.
1225 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1226 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001227 // Determine whether the type we're converting from is signed or
1228 // unsigned.
1229 bool FromIsSigned;
1230 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall842aef82009-12-09 09:09:27 +00001231
1232 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1233 FromIsSigned = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001234
1235 // The types we'll try to promote to, in the appropriate
1236 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001237 QualType PromoteTypes[6] = {
1238 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001239 Context.LongTy, Context.UnsignedLongTy ,
1240 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001241 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001242 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001243 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1244 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001245 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001246 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1247 // We found the type that we can promote to. If this is the
1248 // type we wanted, we have a promotion. Otherwise, no
1249 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001250 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001251 }
1252 }
1253 }
1254
1255 // An rvalue for an integral bit-field (9.6) can be converted to an
1256 // rvalue of type int if int can represent all the values of the
1257 // bit-field; otherwise, it can be converted to unsigned int if
1258 // unsigned int can represent all the values of the bit-field. If
1259 // the bit-field is larger yet, no integral promotion applies to
1260 // it. If the bit-field has an enumerated type, it is treated as any
1261 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001262 // FIXME: We should delay checking of bit-fields until we actually perform the
1263 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001264 using llvm::APSInt;
1265 if (From)
1266 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001267 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001268 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001269 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1270 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1271 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001272
Douglas Gregor86f19402008-12-20 23:49:58 +00001273 // Are we promoting to an int from a bitfield that fits in an int?
1274 if (BitWidth < ToSize ||
1275 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1276 return To->getKind() == BuiltinType::Int;
1277 }
Mike Stump1eb44332009-09-09 15:08:12 +00001278
Douglas Gregor86f19402008-12-20 23:49:58 +00001279 // Are we promoting to an unsigned int from an unsigned bitfield
1280 // that fits into an unsigned int?
1281 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1282 return To->getKind() == BuiltinType::UInt;
1283 }
Mike Stump1eb44332009-09-09 15:08:12 +00001284
Douglas Gregor86f19402008-12-20 23:49:58 +00001285 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001286 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001287 }
Mike Stump1eb44332009-09-09 15:08:12 +00001288
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001289 // An rvalue of type bool can be converted to an rvalue of type int,
1290 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001291 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001292 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001293 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001294
1295 return false;
1296}
1297
1298/// IsFloatingPointPromotion - Determines whether the conversion from
1299/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1300/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001301bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001302 /// An rvalue of type float can be converted to an rvalue of type
1303 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +00001304 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1305 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001306 if (FromBuiltin->getKind() == BuiltinType::Float &&
1307 ToBuiltin->getKind() == BuiltinType::Double)
1308 return true;
1309
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001310 // C99 6.3.1.5p1:
1311 // When a float is promoted to double or long double, or a
1312 // double is promoted to long double [...].
1313 if (!getLangOptions().CPlusPlus &&
1314 (FromBuiltin->getKind() == BuiltinType::Float ||
1315 FromBuiltin->getKind() == BuiltinType::Double) &&
1316 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1317 return true;
1318 }
1319
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001320 return false;
1321}
1322
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001323/// \brief Determine if a conversion is a complex promotion.
1324///
1325/// A complex promotion is defined as a complex -> complex conversion
1326/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001327/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001328bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001329 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001330 if (!FromComplex)
1331 return false;
1332
John McCall183700f2009-09-21 23:43:11 +00001333 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001334 if (!ToComplex)
1335 return false;
1336
1337 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001338 ToComplex->getElementType()) ||
1339 IsIntegralPromotion(0, FromComplex->getElementType(),
1340 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001341}
1342
Douglas Gregorcb7de522008-11-26 23:31:11 +00001343/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1344/// the pointer type FromPtr to a pointer to type ToPointee, with the
1345/// same type qualifiers as FromPtr has on its pointee type. ToType,
1346/// if non-empty, will be a pointer to ToType that may or may not have
1347/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +00001348static QualType
1349BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001350 QualType ToPointee, QualType ToType,
1351 ASTContext &Context) {
1352 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1353 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001354 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001355
1356 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001357 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001358 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001359 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001360 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001361
1362 // Build a pointer to ToPointee. It has the right qualifiers
1363 // already.
1364 return Context.getPointerType(ToPointee);
1365 }
1366
1367 // Just build a canonical type that has the right qualifiers.
John McCall0953e762009-09-24 19:53:00 +00001368 return Context.getPointerType(
Douglas Gregora4923eb2009-11-16 21:35:15 +00001369 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1370 Quals));
Douglas Gregorcb7de522008-11-26 23:31:11 +00001371}
1372
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001373/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1374/// the FromType, which is an objective-c pointer, to ToType, which may or may
1375/// not have the right set of qualifiers.
1376static QualType
1377BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1378 QualType ToType,
1379 ASTContext &Context) {
1380 QualType CanonFromType = Context.getCanonicalType(FromType);
1381 QualType CanonToType = Context.getCanonicalType(ToType);
1382 Qualifiers Quals = CanonFromType.getQualifiers();
1383
1384 // Exact qualifier match -> return the pointer type we're converting to.
1385 if (CanonToType.getLocalQualifiers() == Quals)
1386 return ToType;
1387
1388 // Just build a canonical type that has the right qualifiers.
1389 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1390}
1391
Mike Stump1eb44332009-09-09 15:08:12 +00001392static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001393 bool InOverloadResolution,
1394 ASTContext &Context) {
1395 // Handle value-dependent integral null pointer constants correctly.
1396 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1397 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001398 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001399 return !InOverloadResolution;
1400
Douglas Gregorce940492009-09-25 04:25:58 +00001401 return Expr->isNullPointerConstant(Context,
1402 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1403 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001404}
Mike Stump1eb44332009-09-09 15:08:12 +00001405
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001406/// IsPointerConversion - Determines whether the conversion of the
1407/// expression From, which has the (possibly adjusted) type FromType,
1408/// can be converted to the type ToType via a pointer conversion (C++
1409/// 4.10). If so, returns true and places the converted type (that
1410/// might differ from ToType in its cv-qualifiers at some level) into
1411/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001412///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001413/// This routine also supports conversions to and from block pointers
1414/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1415/// pointers to interfaces. FIXME: Once we've determined the
1416/// appropriate overloading rules for Objective-C, we may want to
1417/// split the Objective-C checks into a different routine; however,
1418/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001419/// conversions, so for now they live here. IncompatibleObjC will be
1420/// set if the conversion is an allowed Objective-C conversion that
1421/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001422bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001423 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001424 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001425 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001426 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +00001427 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1428 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001429
Mike Stump1eb44332009-09-09 15:08:12 +00001430 // Conversion from a null pointer constant to any Objective-C pointer type.
1431 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001432 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001433 ConvertedType = ToType;
1434 return true;
1435 }
1436
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001437 // Blocks: Block pointers can be converted to void*.
1438 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001439 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001440 ConvertedType = ToType;
1441 return true;
1442 }
1443 // Blocks: A null pointer constant can be converted to a block
1444 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001445 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001446 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001447 ConvertedType = ToType;
1448 return true;
1449 }
1450
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001451 // If the left-hand-side is nullptr_t, the right side can be a null
1452 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001453 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001454 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001455 ConvertedType = ToType;
1456 return true;
1457 }
1458
Ted Kremenek6217b802009-07-29 21:53:49 +00001459 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001460 if (!ToTypePtr)
1461 return false;
1462
1463 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001464 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001465 ConvertedType = ToType;
1466 return true;
1467 }
Sebastian Redl07779722008-10-31 14:43:28 +00001468
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001469 // Beyond this point, both types need to be pointers
1470 // , including objective-c pointers.
1471 QualType ToPointeeType = ToTypePtr->getPointeeType();
1472 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1473 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1474 ToType, Context);
1475 return true;
1476
1477 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001478 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001479 if (!FromTypePtr)
1480 return false;
1481
1482 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001483
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00001484 // If the unqualified pointee types are the same, this can't be a
1485 // pointer conversion, so don't do all of the work below.
1486 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1487 return false;
1488
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001489 // An rvalue of type "pointer to cv T," where T is an object type,
1490 // can be converted to an rvalue of type "pointer to cv void" (C++
1491 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00001492 if (FromPointeeType->isIncompleteOrObjectType() &&
1493 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001494 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001495 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001496 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001497 return true;
1498 }
1499
Douglas Gregorf9201e02009-02-11 23:02:49 +00001500 // When we're overloading in C, we allow a special kind of pointer
1501 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001502 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001503 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001504 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001505 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001506 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001507 return true;
1508 }
1509
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001510 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001511 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001512 // An rvalue of type "pointer to cv D," where D is a class type,
1513 // can be converted to an rvalue of type "pointer to cv B," where
1514 // B is a base class (clause 10) of D. If B is an inaccessible
1515 // (clause 11) or ambiguous (10.2) base class of D, a program that
1516 // necessitates this conversion is ill-formed. The result of the
1517 // conversion is a pointer to the base class sub-object of the
1518 // derived class object. The null pointer value is converted to
1519 // the null pointer value of the destination type.
1520 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001521 // Note that we do not check for ambiguity or inaccessibility
1522 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001523 if (getLangOptions().CPlusPlus &&
1524 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001525 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001526 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001527 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001528 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001529 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001530 ToType, Context);
1531 return true;
1532 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001533
Douglas Gregorc7887512008-12-19 19:13:09 +00001534 return false;
1535}
1536
1537/// isObjCPointerConversion - Determines whether this is an
1538/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1539/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001540bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001541 QualType& ConvertedType,
1542 bool &IncompatibleObjC) {
1543 if (!getLangOptions().ObjC1)
1544 return false;
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001545
Steve Naroff14108da2009-07-10 23:34:53 +00001546 // First, we handle all conversions on ObjC object pointer types.
John McCall183700f2009-09-21 23:43:11 +00001547 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001548 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001549 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001550
Steve Naroff14108da2009-07-10 23:34:53 +00001551 if (ToObjCPtr && FromObjCPtr) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00001552 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001553 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001554 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001555 ConvertedType = ToType;
1556 return true;
1557 }
1558 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001559 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001560 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001561 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001562 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001563 ConvertedType = ToType;
1564 return true;
1565 }
1566 // Objective C++: We're able to convert from a pointer to an
1567 // interface to a pointer to a different interface.
1568 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00001569 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1570 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1571 if (getLangOptions().CPlusPlus && LHS && RHS &&
1572 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1573 FromObjCPtr->getPointeeType()))
1574 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00001575 ConvertedType = ToType;
1576 return true;
1577 }
1578
1579 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1580 // Okay: this is some kind of implicit downcast of Objective-C
1581 // interfaces, which is permitted. However, we're going to
1582 // complain about it.
1583 IncompatibleObjC = true;
1584 ConvertedType = FromType;
1585 return true;
1586 }
Mike Stump1eb44332009-09-09 15:08:12 +00001587 }
Steve Naroff14108da2009-07-10 23:34:53 +00001588 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001589 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001590 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001591 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001592 else if (const BlockPointerType *ToBlockPtr =
1593 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00001594 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001595 // to a block pointer type.
1596 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1597 ConvertedType = ToType;
1598 return true;
1599 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001600 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001601 }
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001602 else if (FromType->getAs<BlockPointerType>() &&
1603 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1604 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00001605 // pointer to any object.
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001606 ConvertedType = ToType;
1607 return true;
1608 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001609 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001610 return false;
1611
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001612 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001613 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001614 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001615 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001616 FromPointeeType = FromBlockPtr->getPointeeType();
1617 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001618 return false;
1619
Douglas Gregorc7887512008-12-19 19:13:09 +00001620 // If we have pointers to pointers, recursively check whether this
1621 // is an Objective-C conversion.
1622 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1623 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1624 IncompatibleObjC)) {
1625 // We always complain about this conversion.
1626 IncompatibleObjC = true;
1627 ConvertedType = ToType;
1628 return true;
1629 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001630 // Allow conversion of pointee being objective-c pointer to another one;
1631 // as in I* to id.
1632 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1633 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1634 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1635 IncompatibleObjC)) {
1636 ConvertedType = ToType;
1637 return true;
1638 }
1639
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001640 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001641 // differences in the argument and result types are in Objective-C
1642 // pointer conversions. If so, we permit the conversion (but
1643 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001644 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001645 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001646 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001647 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001648 if (FromFunctionType && ToFunctionType) {
1649 // If the function types are exactly the same, this isn't an
1650 // Objective-C pointer conversion.
1651 if (Context.getCanonicalType(FromPointeeType)
1652 == Context.getCanonicalType(ToPointeeType))
1653 return false;
1654
1655 // Perform the quick checks that will tell us whether these
1656 // function types are obviously different.
1657 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1658 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1659 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1660 return false;
1661
1662 bool HasObjCConversion = false;
1663 if (Context.getCanonicalType(FromFunctionType->getResultType())
1664 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1665 // Okay, the types match exactly. Nothing to do.
1666 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1667 ToFunctionType->getResultType(),
1668 ConvertedType, IncompatibleObjC)) {
1669 // Okay, we have an Objective-C pointer conversion.
1670 HasObjCConversion = true;
1671 } else {
1672 // Function types are too different. Abort.
1673 return false;
1674 }
Mike Stump1eb44332009-09-09 15:08:12 +00001675
Douglas Gregorc7887512008-12-19 19:13:09 +00001676 // Check argument types.
1677 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1678 ArgIdx != NumArgs; ++ArgIdx) {
1679 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1680 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1681 if (Context.getCanonicalType(FromArgType)
1682 == Context.getCanonicalType(ToArgType)) {
1683 // Okay, the types match exactly. Nothing to do.
1684 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1685 ConvertedType, IncompatibleObjC)) {
1686 // Okay, we have an Objective-C pointer conversion.
1687 HasObjCConversion = true;
1688 } else {
1689 // Argument types are too different. Abort.
1690 return false;
1691 }
1692 }
1693
1694 if (HasObjCConversion) {
1695 // We had an Objective-C conversion. Allow this pointer
1696 // conversion, but complain about it.
1697 ConvertedType = ToType;
1698 IncompatibleObjC = true;
1699 return true;
1700 }
1701 }
1702
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001703 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001704}
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001705
1706/// FunctionArgTypesAreEqual - This routine checks two function proto types
1707/// for equlity of their argument types. Caller has already checked that
1708/// they have same number of arguments. This routine assumes that Objective-C
1709/// pointer types which only differ in their protocol qualifiers are equal.
1710bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1711 FunctionProtoType* NewType){
1712 if (!getLangOptions().ObjC1)
1713 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1714 NewType->arg_type_begin());
1715
1716 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1717 N = NewType->arg_type_begin(),
1718 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1719 QualType ToType = (*O);
1720 QualType FromType = (*N);
1721 if (ToType != FromType) {
1722 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1723 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00001724 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1725 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1726 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1727 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001728 continue;
1729 }
John McCallc12c5bb2010-05-15 11:32:37 +00001730 else if (const ObjCObjectPointerType *PTTo =
1731 ToType->getAs<ObjCObjectPointerType>()) {
1732 if (const ObjCObjectPointerType *PTFr =
1733 FromType->getAs<ObjCObjectPointerType>())
1734 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1735 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001736 }
1737 return false;
1738 }
1739 }
1740 return true;
1741}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001742
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001743/// CheckPointerConversion - Check the pointer conversion from the
1744/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001745/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001746/// conversions for which IsPointerConversion has already returned
1747/// true. It returns true and produces a diagnostic if there was an
1748/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001749bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00001750 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001751 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001752 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001753 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00001754 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001755
Douglas Gregord7a95972010-06-08 17:35:15 +00001756 if (CXXBoolLiteralExpr* LitBool
1757 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00001758 if (!IsCStyleOrFunctionalCast && LitBool->getValue() == false)
Douglas Gregord7a95972010-06-08 17:35:15 +00001759 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1760 << ToType;
1761
Ted Kremenek6217b802009-07-29 21:53:49 +00001762 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1763 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001764 QualType FromPointeeType = FromPtrType->getPointeeType(),
1765 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001766
Douglas Gregor5fccd362010-03-03 23:55:11 +00001767 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1768 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001769 // We must have a derived-to-base conversion. Check an
1770 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001771 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1772 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001773 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001774 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001775 return true;
1776
1777 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00001778 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001779 }
1780 }
Mike Stump1eb44332009-09-09 15:08:12 +00001781 if (const ObjCObjectPointerType *FromPtrType =
John McCall183700f2009-09-21 23:43:11 +00001782 FromType->getAs<ObjCObjectPointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001783 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00001784 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001785 // Objective-C++ conversions are always okay.
1786 // FIXME: We should have a different class of conversions for the
1787 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001788 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001789 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001790
Steve Naroff14108da2009-07-10 23:34:53 +00001791 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001792 return false;
1793}
1794
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001795/// IsMemberPointerConversion - Determines whether the conversion of the
1796/// expression From, which has the (possibly adjusted) type FromType, can be
1797/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1798/// If so, returns true and places the converted type (that might differ from
1799/// ToType in its cv-qualifiers at some level) into ConvertedType.
1800bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregorce940492009-09-25 04:25:58 +00001801 QualType ToType,
1802 bool InOverloadResolution,
1803 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001804 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001805 if (!ToTypePtr)
1806 return false;
1807
1808 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00001809 if (From->isNullPointerConstant(Context,
1810 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1811 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001812 ConvertedType = ToType;
1813 return true;
1814 }
1815
1816 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001817 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001818 if (!FromTypePtr)
1819 return false;
1820
1821 // A pointer to member of B can be converted to a pointer to member of D,
1822 // where D is derived from B (C++ 4.11p2).
1823 QualType FromClass(FromTypePtr->getClass(), 0);
1824 QualType ToClass(ToTypePtr->getClass(), 0);
1825 // FIXME: What happens when these are dependent? Is this function even called?
1826
1827 if (IsDerivedFrom(ToClass, FromClass)) {
1828 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1829 ToClass.getTypePtr());
1830 return true;
1831 }
1832
1833 return false;
1834}
Douglas Gregor43c79c22009-12-09 00:47:37 +00001835
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001836/// CheckMemberPointerConversion - Check the member pointer conversion from the
1837/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00001838/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001839/// for which IsMemberPointerConversion has already returned true. It returns
1840/// true and produces a diagnostic if there was an error, or returns false
1841/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001842bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00001843 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001844 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001845 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001846 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001847 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001848 if (!FromPtrType) {
1849 // This must be a null pointer to member pointer conversion
Douglas Gregorce940492009-09-25 04:25:58 +00001850 assert(From->isNullPointerConstant(Context,
1851 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001852 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00001853 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001854 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001855 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001856
Ted Kremenek6217b802009-07-29 21:53:49 +00001857 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001858 assert(ToPtrType && "No member pointer cast has a target type "
1859 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001860
Sebastian Redl21593ac2009-01-28 18:33:18 +00001861 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1862 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001863
Sebastian Redl21593ac2009-01-28 18:33:18 +00001864 // FIXME: What about dependent types?
1865 assert(FromClass->isRecordType() && "Pointer into non-class.");
1866 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001867
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001868 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001869 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00001870 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1871 assert(DerivationOkay &&
1872 "Should not have been called if derivation isn't OK.");
1873 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001874
Sebastian Redl21593ac2009-01-28 18:33:18 +00001875 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1876 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001877 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1878 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1879 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1880 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001881 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001882
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001883 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001884 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1885 << FromClass << ToClass << QualType(VBase, 0)
1886 << From->getSourceRange();
1887 return true;
1888 }
1889
John McCall6b2accb2010-02-10 09:31:12 +00001890 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00001891 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1892 Paths.front(),
1893 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00001894
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001895 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001896 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00001897 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001898 return false;
1899}
1900
Douglas Gregor98cd5992008-10-21 23:43:52 +00001901/// IsQualificationConversion - Determines whether the conversion from
1902/// an rvalue of type FromType to ToType is a qualification conversion
1903/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001904bool
1905Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001906 FromType = Context.getCanonicalType(FromType);
1907 ToType = Context.getCanonicalType(ToType);
1908
1909 // If FromType and ToType are the same type, this is not a
1910 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00001911 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00001912 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001913
Douglas Gregor98cd5992008-10-21 23:43:52 +00001914 // (C++ 4.4p4):
1915 // A conversion can add cv-qualifiers at levels other than the first
1916 // in multi-level pointers, subject to the following rules: [...]
1917 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001918 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00001919 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001920 // Within each iteration of the loop, we check the qualifiers to
1921 // determine if this still looks like a qualification
1922 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001923 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001924 // until there are no more pointers or pointers-to-members left to
1925 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001926 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001927
1928 // -- for every j > 0, if const is in cv 1,j then const is in cv
1929 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001930 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001931 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001932
Douglas Gregor98cd5992008-10-21 23:43:52 +00001933 // -- if the cv 1,j and cv 2,j are different, then const is in
1934 // every cv for 0 < k < j.
1935 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001936 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001937 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001938
Douglas Gregor98cd5992008-10-21 23:43:52 +00001939 // Keep track of whether all prior cv-qualifiers in the "to" type
1940 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00001941 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00001942 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001943 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001944
1945 // We are left with FromType and ToType being the pointee types
1946 // after unwrapping the original FromType and ToType the same number
1947 // of types. If we unwrapped any pointers, and if FromType and
1948 // ToType have the same unqualified type (since we checked
1949 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001950 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00001951}
1952
Douglas Gregor734d9862009-01-30 23:27:23 +00001953/// Determines whether there is a user-defined conversion sequence
1954/// (C++ [over.ics.user]) that converts expression From to the type
1955/// ToType. If such a conversion exists, User will contain the
1956/// user-defined conversion sequence that performs such a conversion
1957/// and this routine will return true. Otherwise, this routine returns
1958/// false and User is unspecified.
1959///
Douglas Gregor734d9862009-01-30 23:27:23 +00001960/// \param AllowExplicit true if the conversion should consider C++0x
1961/// "explicit" conversion functions as well as non-explicit conversion
1962/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00001963static OverloadingResult
1964IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1965 UserDefinedConversionSequence& User,
1966 OverloadCandidateSet& CandidateSet,
1967 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001968 // Whether we will only visit constructors.
1969 bool ConstructorsOnly = false;
1970
1971 // If the type we are conversion to is a class type, enumerate its
1972 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00001973 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001974 // C++ [over.match.ctor]p1:
1975 // When objects of class type are direct-initialized (8.5), or
1976 // copy-initialized from an expression of the same or a
1977 // derived class type (8.5), overload resolution selects the
1978 // constructor. [...] For copy-initialization, the candidate
1979 // functions are all the converting constructors (12.3.1) of
1980 // that class. The argument list is the expression-list within
1981 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00001982 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001983 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001984 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001985 ConstructorsOnly = true;
1986
John McCall120d63c2010-08-24 20:38:10 +00001987 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag())) {
Douglas Gregor393896f2009-11-05 13:06:35 +00001988 // We're not going to find any constructors.
1989 } else if (CXXRecordDecl *ToRecordDecl
1990 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001991 DeclContext::lookup_iterator Con, ConEnd;
John McCall120d63c2010-08-24 20:38:10 +00001992 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001993 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00001994 NamedDecl *D = *Con;
1995 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1996
Douglas Gregordec06662009-08-21 18:42:58 +00001997 // Find the constructor (which may be a template).
1998 CXXConstructorDecl *Constructor = 0;
1999 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00002000 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00002001 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00002002 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00002003 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2004 else
John McCall9aa472c2010-03-19 07:35:19 +00002005 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002006
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00002007 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00002008 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00002009 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00002010 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2011 /*ExplicitArgs*/ 0,
2012 &From, 1, CandidateSet,
2013 /*SuppressUserConversions=*/
2014 !ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00002015 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00002016 // Allow one user-defined conversion when user specifies a
2017 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00002018 S.AddOverloadCandidate(Constructor, FoundDecl,
2019 &From, 1, CandidateSet,
2020 /*SuppressUserConversions=*/
2021 !ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00002022 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002023 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002024 }
2025 }
2026
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002027 // Enumerate conversion functions, if we're allowed to.
2028 if (ConstructorsOnly) {
John McCall120d63c2010-08-24 20:38:10 +00002029 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2030 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00002031 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00002032 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002033 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002034 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002035 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2036 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00002037 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002038 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002039 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00002040 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00002041 DeclAccessPair FoundDecl = I.getPair();
2042 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00002043 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2044 if (isa<UsingShadowDecl>(D))
2045 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2046
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002047 CXXConversionDecl *Conv;
2048 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00002049 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2050 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002051 else
John McCall32daa422010-03-31 01:36:47 +00002052 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002053
2054 if (AllowExplicit || !Conv->isExplicit()) {
2055 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00002056 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2057 ActingContext, From, ToType,
2058 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002059 else
John McCall120d63c2010-08-24 20:38:10 +00002060 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2061 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002062 }
2063 }
2064 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002065 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002066
2067 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002068 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00002069 case OR_Success:
2070 // Record the standard conversion we used and the conversion function.
2071 if (CXXConstructorDecl *Constructor
2072 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
2073 // C++ [over.ics.user]p1:
2074 // If the user-defined conversion is specified by a
2075 // constructor (12.3.1), the initial standard conversion
2076 // sequence converts the source type to the type required by
2077 // the argument of the constructor.
2078 //
2079 QualType ThisType = Constructor->getThisType(S.Context);
2080 if (Best->Conversions[0].isEllipsis())
2081 User.EllipsisConversion = true;
2082 else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002083 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002084 User.EllipsisConversion = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002085 }
John McCall120d63c2010-08-24 20:38:10 +00002086 User.ConversionFunction = Constructor;
2087 User.After.setAsIdentityConversion();
2088 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2089 User.After.setAllToTypes(ToType);
2090 return OR_Success;
2091 } else if (CXXConversionDecl *Conversion
2092 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2093 // C++ [over.ics.user]p1:
2094 //
2095 // [...] If the user-defined conversion is specified by a
2096 // conversion function (12.3.2), the initial standard
2097 // conversion sequence converts the source type to the
2098 // implicit object parameter of the conversion function.
2099 User.Before = Best->Conversions[0].Standard;
2100 User.ConversionFunction = Conversion;
2101 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002102
John McCall120d63c2010-08-24 20:38:10 +00002103 // C++ [over.ics.user]p2:
2104 // The second standard conversion sequence converts the
2105 // result of the user-defined conversion to the target type
2106 // for the sequence. Since an implicit conversion sequence
2107 // is an initialization, the special rules for
2108 // initialization by user-defined conversion apply when
2109 // selecting the best user-defined conversion for a
2110 // user-defined conversion sequence (see 13.3.3 and
2111 // 13.3.3.1).
2112 User.After = Best->FinalConversion;
2113 return OR_Success;
2114 } else {
2115 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002116 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002117 }
2118
John McCall120d63c2010-08-24 20:38:10 +00002119 case OR_No_Viable_Function:
2120 return OR_No_Viable_Function;
2121 case OR_Deleted:
2122 // No conversion here! We're done.
2123 return OR_Deleted;
2124
2125 case OR_Ambiguous:
2126 return OR_Ambiguous;
2127 }
2128
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002129 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002130}
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002131
2132bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002133Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002134 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00002135 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002136 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00002137 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002138 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002139 if (OvResult == OR_Ambiguous)
2140 Diag(From->getSourceRange().getBegin(),
2141 diag::err_typecheck_ambiguous_condition)
2142 << From->getType() << ToType << From->getSourceRange();
2143 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2144 Diag(From->getSourceRange().getBegin(),
2145 diag::err_typecheck_nonviable_condition)
2146 << From->getType() << ToType << From->getSourceRange();
2147 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002148 return false;
John McCall120d63c2010-08-24 20:38:10 +00002149 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002150 return true;
2151}
Douglas Gregor60d62c22008-10-31 16:23:19 +00002152
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002153/// CompareImplicitConversionSequences - Compare two implicit
2154/// conversion sequences to determine whether one is better than the
2155/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00002156static ImplicitConversionSequence::CompareKind
2157CompareImplicitConversionSequences(Sema &S,
2158 const ImplicitConversionSequence& ICS1,
2159 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002160{
2161 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2162 // conversion sequences (as defined in 13.3.3.1)
2163 // -- a standard conversion sequence (13.3.3.1.1) is a better
2164 // conversion sequence than a user-defined conversion sequence or
2165 // an ellipsis conversion sequence, and
2166 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2167 // conversion sequence than an ellipsis conversion sequence
2168 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002169 //
John McCall1d318332010-01-12 00:44:57 +00002170 // C++0x [over.best.ics]p10:
2171 // For the purpose of ranking implicit conversion sequences as
2172 // described in 13.3.3.2, the ambiguous conversion sequence is
2173 // treated as a user-defined sequence that is indistinguishable
2174 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002175 if (ICS1.getKindRank() < ICS2.getKindRank())
2176 return ImplicitConversionSequence::Better;
2177 else if (ICS2.getKindRank() < ICS1.getKindRank())
2178 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002179
Benjamin Kramerb6eee072010-04-18 12:05:54 +00002180 // The following checks require both conversion sequences to be of
2181 // the same kind.
2182 if (ICS1.getKind() != ICS2.getKind())
2183 return ImplicitConversionSequence::Indistinguishable;
2184
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002185 // Two implicit conversion sequences of the same form are
2186 // indistinguishable conversion sequences unless one of the
2187 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00002188 if (ICS1.isStandard())
John McCall120d63c2010-08-24 20:38:10 +00002189 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00002190 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002191 // User-defined conversion sequence U1 is a better conversion
2192 // sequence than another user-defined conversion sequence U2 if
2193 // they contain the same user-defined conversion function or
2194 // constructor and if the second standard conversion sequence of
2195 // U1 is better than the second standard conversion sequence of
2196 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002197 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002198 ICS2.UserDefined.ConversionFunction)
John McCall120d63c2010-08-24 20:38:10 +00002199 return CompareStandardConversionSequences(S,
2200 ICS1.UserDefined.After,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002201 ICS2.UserDefined.After);
2202 }
2203
2204 return ImplicitConversionSequence::Indistinguishable;
2205}
2206
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002207static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2208 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2209 Qualifiers Quals;
2210 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2211 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2212 }
2213
2214 return Context.hasSameUnqualifiedType(T1, T2);
2215}
2216
Douglas Gregorad323a82010-01-27 03:51:04 +00002217// Per 13.3.3.2p3, compare the given standard conversion sequences to
2218// determine if one is a proper subset of the other.
2219static ImplicitConversionSequence::CompareKind
2220compareStandardConversionSubsets(ASTContext &Context,
2221 const StandardConversionSequence& SCS1,
2222 const StandardConversionSequence& SCS2) {
2223 ImplicitConversionSequence::CompareKind Result
2224 = ImplicitConversionSequence::Indistinguishable;
2225
Douglas Gregorae65f4b2010-05-23 22:10:15 +00002226 // the identity conversion sequence is considered to be a subsequence of
2227 // any non-identity conversion sequence
2228 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2229 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2230 return ImplicitConversionSequence::Better;
2231 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2232 return ImplicitConversionSequence::Worse;
2233 }
2234
Douglas Gregorad323a82010-01-27 03:51:04 +00002235 if (SCS1.Second != SCS2.Second) {
2236 if (SCS1.Second == ICK_Identity)
2237 Result = ImplicitConversionSequence::Better;
2238 else if (SCS2.Second == ICK_Identity)
2239 Result = ImplicitConversionSequence::Worse;
2240 else
2241 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002242 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00002243 return ImplicitConversionSequence::Indistinguishable;
2244
2245 if (SCS1.Third == SCS2.Third) {
2246 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2247 : ImplicitConversionSequence::Indistinguishable;
2248 }
2249
2250 if (SCS1.Third == ICK_Identity)
2251 return Result == ImplicitConversionSequence::Worse
2252 ? ImplicitConversionSequence::Indistinguishable
2253 : ImplicitConversionSequence::Better;
2254
2255 if (SCS2.Third == ICK_Identity)
2256 return Result == ImplicitConversionSequence::Better
2257 ? ImplicitConversionSequence::Indistinguishable
2258 : ImplicitConversionSequence::Worse;
2259
2260 return ImplicitConversionSequence::Indistinguishable;
2261}
2262
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002263/// CompareStandardConversionSequences - Compare two standard
2264/// conversion sequences to determine whether one is better than the
2265/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00002266static ImplicitConversionSequence::CompareKind
2267CompareStandardConversionSequences(Sema &S,
2268 const StandardConversionSequence& SCS1,
2269 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002270{
2271 // Standard conversion sequence S1 is a better conversion sequence
2272 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2273
2274 // -- S1 is a proper subsequence of S2 (comparing the conversion
2275 // sequences in the canonical form defined by 13.3.3.1.1,
2276 // excluding any Lvalue Transformation; the identity conversion
2277 // sequence is considered to be a subsequence of any
2278 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00002279 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00002280 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00002281 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002282
2283 // -- the rank of S1 is better than the rank of S2 (by the rules
2284 // defined below), or, if not that,
2285 ImplicitConversionRank Rank1 = SCS1.getRank();
2286 ImplicitConversionRank Rank2 = SCS2.getRank();
2287 if (Rank1 < Rank2)
2288 return ImplicitConversionSequence::Better;
2289 else if (Rank2 < Rank1)
2290 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002291
Douglas Gregor57373262008-10-22 14:17:15 +00002292 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2293 // are indistinguishable unless one of the following rules
2294 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00002295
Douglas Gregor57373262008-10-22 14:17:15 +00002296 // A conversion that is not a conversion of a pointer, or
2297 // pointer to member, to bool is better than another conversion
2298 // that is such a conversion.
2299 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2300 return SCS2.isPointerConversionToBool()
2301 ? ImplicitConversionSequence::Better
2302 : ImplicitConversionSequence::Worse;
2303
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002304 // C++ [over.ics.rank]p4b2:
2305 //
2306 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002307 // conversion of B* to A* is better than conversion of B* to
2308 // void*, and conversion of A* to void* is better than conversion
2309 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00002310 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00002311 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002312 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00002313 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002314 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2315 // Exactly one of the conversion sequences is a conversion to
2316 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002317 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2318 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002319 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2320 // Neither conversion sequence converts to a void pointer; compare
2321 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002322 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00002323 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002324 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002325 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2326 // Both conversion sequences are conversions to void
2327 // pointers. Compare the source types to determine if there's an
2328 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00002329 QualType FromType1 = SCS1.getFromType();
2330 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002331
2332 // Adjust the types we're converting from via the array-to-pointer
2333 // conversion, if we need to.
2334 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002335 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002336 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002337 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002338
Douglas Gregor01919692009-12-13 21:37:05 +00002339 QualType FromPointee1
2340 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2341 QualType FromPointee2
2342 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002343
John McCall120d63c2010-08-24 20:38:10 +00002344 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00002345 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002346 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00002347 return ImplicitConversionSequence::Worse;
2348
2349 // Objective-C++: If one interface is more specific than the
2350 // other, it is the better one.
John McCallc12c5bb2010-05-15 11:32:37 +00002351 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2352 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor01919692009-12-13 21:37:05 +00002353 if (FromIface1 && FromIface1) {
John McCall120d63c2010-08-24 20:38:10 +00002354 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor01919692009-12-13 21:37:05 +00002355 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002356 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor01919692009-12-13 21:37:05 +00002357 return ImplicitConversionSequence::Worse;
2358 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002359 }
Douglas Gregor57373262008-10-22 14:17:15 +00002360
2361 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2362 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00002363 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00002364 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002365 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00002366
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002367 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002368 // C++0x [over.ics.rank]p3b4:
2369 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2370 // implicit object parameter of a non-static member function declared
2371 // without a ref-qualifier, and S1 binds an rvalue reference to an
2372 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00002373 // FIXME: We don't know if we're dealing with the implicit object parameter,
2374 // or if the member function in this case has a ref qualifier.
2375 // (Of course, we don't have ref qualifiers yet.)
2376 if (SCS1.RRefBinding != SCS2.RRefBinding)
2377 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2378 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002379
2380 // C++ [over.ics.rank]p3b4:
2381 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2382 // which the references refer are the same type except for
2383 // top-level cv-qualifiers, and the type to which the reference
2384 // initialized by S2 refers is more cv-qualified than the type
2385 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00002386 QualType T1 = SCS1.getToType(2);
2387 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00002388 T1 = S.Context.getCanonicalType(T1);
2389 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002390 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00002391 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2392 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002393 if (UnqualT1 == UnqualT2) {
2394 // If the type is an array type, promote the element qualifiers to the type
2395 // for comparison.
2396 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00002397 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002398 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00002399 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002400 if (T2.isMoreQualifiedThan(T1))
2401 return ImplicitConversionSequence::Better;
2402 else if (T1.isMoreQualifiedThan(T2))
2403 return ImplicitConversionSequence::Worse;
2404 }
2405 }
Douglas Gregor57373262008-10-22 14:17:15 +00002406
2407 return ImplicitConversionSequence::Indistinguishable;
2408}
2409
2410/// CompareQualificationConversions - Compares two standard conversion
2411/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00002412/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2413ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00002414CompareQualificationConversions(Sema &S,
2415 const StandardConversionSequence& SCS1,
2416 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00002417 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00002418 // -- S1 and S2 differ only in their qualification conversion and
2419 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2420 // cv-qualification signature of type T1 is a proper subset of
2421 // the cv-qualification signature of type T2, and S1 is not the
2422 // deprecated string literal array-to-pointer conversion (4.2).
2423 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2424 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2425 return ImplicitConversionSequence::Indistinguishable;
2426
2427 // FIXME: the example in the standard doesn't use a qualification
2428 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00002429 QualType T1 = SCS1.getToType(2);
2430 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00002431 T1 = S.Context.getCanonicalType(T1);
2432 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002433 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00002434 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2435 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00002436
2437 // If the types are the same, we won't learn anything by unwrapped
2438 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00002439 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00002440 return ImplicitConversionSequence::Indistinguishable;
2441
Chandler Carruth28e318c2009-12-29 07:16:59 +00002442 // If the type is an array type, promote the element qualifiers to the type
2443 // for comparison.
2444 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00002445 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002446 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00002447 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002448
Mike Stump1eb44332009-09-09 15:08:12 +00002449 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00002450 = ImplicitConversionSequence::Indistinguishable;
John McCall120d63c2010-08-24 20:38:10 +00002451 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00002452 // Within each iteration of the loop, we check the qualifiers to
2453 // determine if this still looks like a qualification
2454 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002455 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00002456 // until there are no more pointers or pointers-to-members left
2457 // to unwrap. This essentially mimics what
2458 // IsQualificationConversion does, but here we're checking for a
2459 // strict subset of qualifiers.
2460 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2461 // The qualifiers are the same, so this doesn't tell us anything
2462 // about how the sequences rank.
2463 ;
2464 else if (T2.isMoreQualifiedThan(T1)) {
2465 // T1 has fewer qualifiers, so it could be the better sequence.
2466 if (Result == ImplicitConversionSequence::Worse)
2467 // Neither has qualifiers that are a subset of the other's
2468 // qualifiers.
2469 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002470
Douglas Gregor57373262008-10-22 14:17:15 +00002471 Result = ImplicitConversionSequence::Better;
2472 } else if (T1.isMoreQualifiedThan(T2)) {
2473 // T2 has fewer qualifiers, so it could be the better sequence.
2474 if (Result == ImplicitConversionSequence::Better)
2475 // Neither has qualifiers that are a subset of the other's
2476 // qualifiers.
2477 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002478
Douglas Gregor57373262008-10-22 14:17:15 +00002479 Result = ImplicitConversionSequence::Worse;
2480 } else {
2481 // Qualifiers are disjoint.
2482 return ImplicitConversionSequence::Indistinguishable;
2483 }
2484
2485 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00002486 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00002487 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002488 }
2489
Douglas Gregor57373262008-10-22 14:17:15 +00002490 // Check that the winning standard conversion sequence isn't using
2491 // the deprecated string literal array to pointer conversion.
2492 switch (Result) {
2493 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00002494 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002495 Result = ImplicitConversionSequence::Indistinguishable;
2496 break;
2497
2498 case ImplicitConversionSequence::Indistinguishable:
2499 break;
2500
2501 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00002502 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002503 Result = ImplicitConversionSequence::Indistinguishable;
2504 break;
2505 }
2506
2507 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002508}
2509
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002510/// CompareDerivedToBaseConversions - Compares two standard conversion
2511/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00002512/// various kinds of derived-to-base conversions (C++
2513/// [over.ics.rank]p4b3). As part of these checks, we also look at
2514/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002515ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00002516CompareDerivedToBaseConversions(Sema &S,
2517 const StandardConversionSequence& SCS1,
2518 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00002519 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002520 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00002521 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002522 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002523
2524 // Adjust the types we're converting from via the array-to-pointer
2525 // conversion, if we need to.
2526 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002527 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002528 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002529 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002530
2531 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00002532 FromType1 = S.Context.getCanonicalType(FromType1);
2533 ToType1 = S.Context.getCanonicalType(ToType1);
2534 FromType2 = S.Context.getCanonicalType(FromType2);
2535 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002536
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002537 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002538 //
2539 // If class B is derived directly or indirectly from class A and
2540 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002541 //
2542 // For Objective-C, we let A, B, and C also be Objective-C
2543 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002544
2545 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00002546 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00002547 SCS2.Second == ICK_Pointer_Conversion &&
2548 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2549 FromType1->isPointerType() && FromType2->isPointerType() &&
2550 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002551 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002552 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002553 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002554 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002555 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002556 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002557 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002558 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002559
John McCallc12c5bb2010-05-15 11:32:37 +00002560 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2561 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2562 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2563 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002564
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002565 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002566 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002567 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002568 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002569 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002570 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00002571
2572 if (ToIface1 && ToIface2) {
John McCall120d63c2010-08-24 20:38:10 +00002573 if (S.Context.canAssignObjCInterfaces(ToIface2, ToIface1))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002574 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002575 else if (S.Context.canAssignObjCInterfaces(ToIface1, ToIface2))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002576 return ImplicitConversionSequence::Worse;
2577 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002578 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002579
2580 // -- conversion of B* to A* is better than conversion of C* to A*,
2581 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002582 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002583 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002584 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002585 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00002586
Douglas Gregorcb7de522008-11-26 23:31:11 +00002587 if (FromIface1 && FromIface2) {
John McCall120d63c2010-08-24 20:38:10 +00002588 if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002589 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002590 else if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002591 return ImplicitConversionSequence::Worse;
2592 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002593 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002594 }
2595
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002596 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002597 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2598 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2599 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2600 const MemberPointerType * FromMemPointer1 =
2601 FromType1->getAs<MemberPointerType>();
2602 const MemberPointerType * ToMemPointer1 =
2603 ToType1->getAs<MemberPointerType>();
2604 const MemberPointerType * FromMemPointer2 =
2605 FromType2->getAs<MemberPointerType>();
2606 const MemberPointerType * ToMemPointer2 =
2607 ToType2->getAs<MemberPointerType>();
2608 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2609 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2610 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2611 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2612 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2613 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2614 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2615 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002616 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002617 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002618 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002619 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00002620 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002621 return ImplicitConversionSequence::Better;
2622 }
2623 // conversion of B::* to C::* is better than conversion of A::* to C::*
2624 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002625 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002626 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002627 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002628 return ImplicitConversionSequence::Worse;
2629 }
2630 }
2631
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002632 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002633 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00002634 // -- binding of an expression of type C to a reference of type
2635 // B& is better than binding an expression of type C to a
2636 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00002637 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2638 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2639 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002640 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002641 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002642 return ImplicitConversionSequence::Worse;
2643 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002644
Douglas Gregor225c41e2008-11-03 19:09:14 +00002645 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00002646 // -- binding of an expression of type B to a reference of type
2647 // A& is better than binding an expression of type C to a
2648 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00002649 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2650 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2651 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002652 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002653 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002654 return ImplicitConversionSequence::Worse;
2655 }
2656 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002657
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002658 return ImplicitConversionSequence::Indistinguishable;
2659}
2660
Douglas Gregorabe183d2010-04-13 16:31:36 +00002661/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2662/// determine whether they are reference-related,
2663/// reference-compatible, reference-compatible with added
2664/// qualification, or incompatible, for use in C++ initialization by
2665/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2666/// type, and the first type (T1) is the pointee type of the reference
2667/// type being initialized.
2668Sema::ReferenceCompareResult
2669Sema::CompareReferenceRelationship(SourceLocation Loc,
2670 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00002671 bool &DerivedToBase,
2672 bool &ObjCConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002673 assert(!OrigT1->isReferenceType() &&
2674 "T1 must be the pointee type of the reference type");
2675 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2676
2677 QualType T1 = Context.getCanonicalType(OrigT1);
2678 QualType T2 = Context.getCanonicalType(OrigT2);
2679 Qualifiers T1Quals, T2Quals;
2680 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2681 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2682
2683 // C++ [dcl.init.ref]p4:
2684 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2685 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2686 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00002687 DerivedToBase = false;
2688 ObjCConversion = false;
2689 if (UnqualT1 == UnqualT2) {
2690 // Nothing to do.
2691 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00002692 IsDerivedFrom(UnqualT2, UnqualT1))
2693 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00002694 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2695 UnqualT2->isObjCObjectOrInterfaceType() &&
2696 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2697 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002698 else
2699 return Ref_Incompatible;
2700
2701 // At this point, we know that T1 and T2 are reference-related (at
2702 // least).
2703
2704 // If the type is an array type, promote the element qualifiers to the type
2705 // for comparison.
2706 if (isa<ArrayType>(T1) && T1Quals)
2707 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2708 if (isa<ArrayType>(T2) && T2Quals)
2709 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2710
2711 // C++ [dcl.init.ref]p4:
2712 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2713 // reference-related to T2 and cv1 is the same cv-qualification
2714 // as, or greater cv-qualification than, cv2. For purposes of
2715 // overload resolution, cases for which cv1 is greater
2716 // cv-qualification than cv2 are identified as
2717 // reference-compatible with added qualification (see 13.3.3.2).
2718 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2719 return Ref_Compatible;
2720 else if (T1.isMoreQualifiedThan(T2))
2721 return Ref_Compatible_With_Added_Qualification;
2722 else
2723 return Ref_Related;
2724}
2725
Douglas Gregor604eb652010-08-11 02:15:33 +00002726/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00002727/// with DeclType. Return true if something definite is found.
2728static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00002729FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2730 QualType DeclType, SourceLocation DeclLoc,
2731 Expr *Init, QualType T2, bool AllowRvalues,
2732 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00002733 assert(T2->isRecordType() && "Can only find conversions of record types.");
2734 CXXRecordDecl *T2RecordDecl
2735 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2736
Douglas Gregor604eb652010-08-11 02:15:33 +00002737 QualType ToType
2738 = AllowRvalues? DeclType->getAs<ReferenceType>()->getPointeeType()
2739 : DeclType;
2740
Sebastian Redl4680bf22010-06-30 18:13:39 +00002741 OverloadCandidateSet CandidateSet(DeclLoc);
2742 const UnresolvedSetImpl *Conversions
2743 = T2RecordDecl->getVisibleConversionFunctions();
2744 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2745 E = Conversions->end(); I != E; ++I) {
2746 NamedDecl *D = *I;
2747 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2748 if (isa<UsingShadowDecl>(D))
2749 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2750
2751 FunctionTemplateDecl *ConvTemplate
2752 = dyn_cast<FunctionTemplateDecl>(D);
2753 CXXConversionDecl *Conv;
2754 if (ConvTemplate)
2755 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2756 else
2757 Conv = cast<CXXConversionDecl>(D);
2758
Douglas Gregor604eb652010-08-11 02:15:33 +00002759 // If this is an explicit conversion, and we're not allowed to consider
2760 // explicit conversions, skip it.
2761 if (!AllowExplicit && Conv->isExplicit())
2762 continue;
2763
2764 if (AllowRvalues) {
2765 bool DerivedToBase = false;
2766 bool ObjCConversion = false;
2767 if (!ConvTemplate &&
2768 S.CompareReferenceRelationship(DeclLoc,
2769 Conv->getConversionType().getNonReferenceType().getUnqualifiedType(),
2770 DeclType.getNonReferenceType().getUnqualifiedType(),
2771 DerivedToBase, ObjCConversion)
2772 == Sema::Ref_Incompatible)
2773 continue;
2774 } else {
2775 // If the conversion function doesn't return a reference type,
2776 // it can't be considered for this conversion. An rvalue reference
2777 // is only acceptable if its referencee is a function type.
2778
2779 const ReferenceType *RefType =
2780 Conv->getConversionType()->getAs<ReferenceType>();
2781 if (!RefType ||
2782 (!RefType->isLValueReferenceType() &&
2783 !RefType->getPointeeType()->isFunctionType()))
2784 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002785 }
Douglas Gregor604eb652010-08-11 02:15:33 +00002786
2787 if (ConvTemplate)
2788 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2789 Init, ToType, CandidateSet);
2790 else
2791 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2792 ToType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002793 }
2794
2795 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002796 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00002797 case OR_Success:
2798 // C++ [over.ics.ref]p1:
2799 //
2800 // [...] If the parameter binds directly to the result of
2801 // applying a conversion function to the argument
2802 // expression, the implicit conversion sequence is a
2803 // user-defined conversion sequence (13.3.3.1.2), with the
2804 // second standard conversion sequence either an identity
2805 // conversion or, if the conversion function returns an
2806 // entity of a type that is a derived class of the parameter
2807 // type, a derived-to-base Conversion.
2808 if (!Best->FinalConversion.DirectBinding)
2809 return false;
2810
2811 ICS.setUserDefined();
2812 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2813 ICS.UserDefined.After = Best->FinalConversion;
2814 ICS.UserDefined.ConversionFunction = Best->Function;
2815 ICS.UserDefined.EllipsisConversion = false;
2816 assert(ICS.UserDefined.After.ReferenceBinding &&
2817 ICS.UserDefined.After.DirectBinding &&
2818 "Expected a direct reference binding!");
2819 return true;
2820
2821 case OR_Ambiguous:
2822 ICS.setAmbiguous();
2823 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2824 Cand != CandidateSet.end(); ++Cand)
2825 if (Cand->Viable)
2826 ICS.Ambiguous.addConversion(Cand->Function);
2827 return true;
2828
2829 case OR_No_Viable_Function:
2830 case OR_Deleted:
2831 // There was no suitable conversion, or we found a deleted
2832 // conversion; continue with other checks.
2833 return false;
2834 }
Eric Christopher1c3d5022010-06-30 18:36:32 +00002835
2836 return false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002837}
2838
Douglas Gregorabe183d2010-04-13 16:31:36 +00002839/// \brief Compute an implicit conversion sequence for reference
2840/// initialization.
2841static ImplicitConversionSequence
2842TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2843 SourceLocation DeclLoc,
2844 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00002845 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002846 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2847
2848 // Most paths end in a failed conversion.
2849 ImplicitConversionSequence ICS;
2850 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2851
2852 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2853 QualType T2 = Init->getType();
2854
2855 // If the initializer is the address of an overloaded function, try
2856 // to resolve the overloaded function. If all goes well, T2 is the
2857 // type of the resulting function.
2858 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2859 DeclAccessPair Found;
2860 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2861 false, Found))
2862 T2 = Fn->getType();
2863 }
2864
2865 // Compute some basic properties of the types and the initializer.
2866 bool isRValRef = DeclType->isRValueReferenceType();
2867 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002868 bool ObjCConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002869 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002870 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00002871 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
2872 ObjCConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002873
Douglas Gregorabe183d2010-04-13 16:31:36 +00002874
Sebastian Redl4680bf22010-06-30 18:13:39 +00002875 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00002876 // A reference to type "cv1 T1" is initialized by an expression
2877 // of type "cv2 T2" as follows:
2878
Sebastian Redl4680bf22010-06-30 18:13:39 +00002879 // -- If reference is an lvalue reference and the initializer expression
2880 // The next bullet point (T1 is a function) is pretty much equivalent to this
2881 // one, so it's handled here.
2882 if (!isRValRef || T1->isFunctionType()) {
2883 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2884 // reference-compatible with "cv2 T2," or
2885 //
2886 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2887 if (InitCategory.isLValue() &&
2888 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002889 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00002890 // When a parameter of reference type binds directly (8.5.3)
2891 // to an argument expression, the implicit conversion sequence
2892 // is the identity conversion, unless the argument expression
2893 // has a type that is a derived class of the parameter type,
2894 // in which case the implicit conversion sequence is a
2895 // derived-to-base Conversion (13.3.3.1).
2896 ICS.setStandard();
2897 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00002898 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2899 : ObjCConversion? ICK_Compatible_Conversion
2900 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002901 ICS.Standard.Third = ICK_Identity;
2902 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2903 ICS.Standard.setToType(0, T2);
2904 ICS.Standard.setToType(1, T1);
2905 ICS.Standard.setToType(2, T1);
2906 ICS.Standard.ReferenceBinding = true;
2907 ICS.Standard.DirectBinding = true;
2908 ICS.Standard.RRefBinding = isRValRef;
2909 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002910
Sebastian Redl4680bf22010-06-30 18:13:39 +00002911 // Nothing more to do: the inaccessibility/ambiguity check for
2912 // derived-to-base conversions is suppressed when we're
2913 // computing the implicit conversion sequence (C++
2914 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00002915 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002916 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00002917
Sebastian Redl4680bf22010-06-30 18:13:39 +00002918 // -- has a class type (i.e., T2 is a class type), where T1 is
2919 // not reference-related to T2, and can be implicitly
2920 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2921 // is reference-compatible with "cv3 T3" 92) (this
2922 // conversion is selected by enumerating the applicable
2923 // conversion functions (13.3.1.6) and choosing the best
2924 // one through overload resolution (13.3)),
2925 if (!SuppressUserConversions && T2->isRecordType() &&
2926 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2927 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00002928 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2929 Init, T2, /*AllowRvalues=*/false,
2930 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00002931 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002932 }
2933 }
2934
Sebastian Redl4680bf22010-06-30 18:13:39 +00002935 // -- Otherwise, the reference shall be an lvalue reference to a
2936 // non-volatile const type (i.e., cv1 shall be const), or the reference
2937 // shall be an rvalue reference and the initializer expression shall be
2938 // an rvalue or have a function type.
Douglas Gregor66821b52010-04-18 09:22:00 +00002939 //
2940 // We actually handle one oddity of C++ [over.ics.ref] at this
2941 // point, which is that, due to p2 (which short-circuits reference
2942 // binding by only attempting a simple conversion for non-direct
2943 // bindings) and p3's strange wording, we allow a const volatile
2944 // reference to bind to an rvalue. Hence the check for the presence
2945 // of "const" rather than checking for "const" being the only
2946 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00002947 // This is also the point where rvalue references and lvalue inits no longer
2948 // go together.
2949 if ((!isRValRef && !T1.isConstQualified()) ||
2950 (isRValRef && InitCategory.isLValue()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00002951 return ICS;
2952
Sebastian Redl4680bf22010-06-30 18:13:39 +00002953 // -- If T1 is a function type, then
2954 // -- if T2 is the same type as T1, the reference is bound to the
2955 // initializer expression lvalue;
2956 // -- if T2 is a class type and the initializer expression can be
2957 // implicitly converted to an lvalue of type T1 [...], the
2958 // reference is bound to the function lvalue that is the result
2959 // of the conversion;
2960 // This is the same as for the lvalue case above, so it was handled there.
2961 // -- otherwise, the program is ill-formed.
2962 // This is the one difference to the lvalue case.
2963 if (T1->isFunctionType())
2964 return ICS;
2965
2966 // -- Otherwise, if T2 is a class type and
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002967 // -- the initializer expression is an rvalue and "cv1 T1"
2968 // is reference-compatible with "cv2 T2," or
Douglas Gregorabe183d2010-04-13 16:31:36 +00002969 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002970 // -- T1 is not reference-related to T2 and the initializer
2971 // expression can be implicitly converted to an rvalue
2972 // of type "cv3 T3" (this conversion is selected by
2973 // enumerating the applicable conversion functions
2974 // (13.3.1.6) and choosing the best one through overload
2975 // resolution (13.3)),
Douglas Gregorabe183d2010-04-13 16:31:36 +00002976 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002977 // then the reference is bound to the initializer
2978 // expression rvalue in the first case and to the object
2979 // that is the result of the conversion in the second case
2980 // (or, in either case, to the appropriate base class
2981 // subobject of the object).
Douglas Gregor604eb652010-08-11 02:15:33 +00002982 if (T2->isRecordType()) {
2983 // First case: "cv1 T1" is reference-compatible with "cv2 T2". This is a
2984 // direct binding in C++0x but not in C++03.
2985 if (InitCategory.isRValue() &&
2986 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2987 ICS.setStandard();
2988 ICS.Standard.First = ICK_Identity;
2989 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2990 : ObjCConversion? ICK_Compatible_Conversion
2991 : ICK_Identity;
2992 ICS.Standard.Third = ICK_Identity;
2993 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2994 ICS.Standard.setToType(0, T2);
2995 ICS.Standard.setToType(1, T1);
2996 ICS.Standard.setToType(2, T1);
2997 ICS.Standard.ReferenceBinding = true;
2998 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
2999 ICS.Standard.RRefBinding = isRValRef;
3000 ICS.Standard.CopyConstructor = 0;
3001 return ICS;
3002 }
3003
3004 // Second case: not reference-related.
3005 if (RefRelationship == Sema::Ref_Incompatible &&
3006 !S.RequireCompleteType(DeclLoc, T2, 0) &&
3007 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3008 Init, T2, /*AllowRvalues=*/true,
3009 AllowExplicit))
3010 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003011 }
Douglas Gregor604eb652010-08-11 02:15:33 +00003012
Douglas Gregorabe183d2010-04-13 16:31:36 +00003013 // -- Otherwise, a temporary of type "cv1 T1" is created and
3014 // initialized from the initializer expression using the
3015 // rules for a non-reference copy initialization (8.5). The
3016 // reference is then bound to the temporary. If T1 is
3017 // reference-related to T2, cv1 must be the same
3018 // cv-qualification as, or greater cv-qualification than,
3019 // cv2; otherwise, the program is ill-formed.
3020 if (RefRelationship == Sema::Ref_Related) {
3021 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3022 // we would be reference-compatible or reference-compatible with
3023 // added qualification. But that wasn't the case, so the reference
3024 // initialization fails.
3025 return ICS;
3026 }
3027
3028 // If at least one of the types is a class type, the types are not
3029 // related, and we aren't allowed any user conversions, the
3030 // reference binding fails. This case is important for breaking
3031 // recursion, since TryImplicitConversion below will attempt to
3032 // create a temporary through the use of a copy constructor.
3033 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3034 (T1->isRecordType() || T2->isRecordType()))
3035 return ICS;
3036
3037 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00003038 // When a parameter of reference type is not bound directly to
3039 // an argument expression, the conversion sequence is the one
3040 // required to convert the argument expression to the
3041 // underlying type of the reference according to
3042 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3043 // to copy-initializing a temporary of the underlying type with
3044 // the argument expression. Any difference in top-level
3045 // cv-qualification is subsumed by the initialization itself
3046 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00003047 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3048 /*AllowExplicit=*/false,
3049 /*InOverloadResolution=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003050
3051 // Of course, that's still a reference binding.
3052 if (ICS.isStandard()) {
3053 ICS.Standard.ReferenceBinding = true;
3054 ICS.Standard.RRefBinding = isRValRef;
3055 } else if (ICS.isUserDefined()) {
3056 ICS.UserDefined.After.ReferenceBinding = true;
3057 ICS.UserDefined.After.RRefBinding = isRValRef;
3058 }
3059 return ICS;
3060}
3061
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003062/// TryCopyInitialization - Try to copy-initialize a value of type
3063/// ToType from the expression From. Return the implicit conversion
3064/// sequence required to pass this argument, which may be a bad
3065/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00003066/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00003067/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00003068static ImplicitConversionSequence
3069TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregorb7f9e6a2010-04-16 17:53:55 +00003070 bool SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00003071 bool InOverloadResolution) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003072 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00003073 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00003074 /*FIXME:*/From->getLocStart(),
3075 SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00003076 /*AllowExplicit=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003077
John McCall120d63c2010-08-24 20:38:10 +00003078 return TryImplicitConversion(S, From, ToType,
3079 SuppressUserConversions,
3080 /*AllowExplicit=*/false,
3081 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003082}
3083
Douglas Gregor96176b32008-11-18 23:14:02 +00003084/// TryObjectArgumentInitialization - Try to initialize the object
3085/// parameter of the given member function (@c Method) from the
3086/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00003087static ImplicitConversionSequence
3088TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
3089 CXXMethodDecl *Method,
3090 CXXRecordDecl *ActingContext) {
3091 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00003092 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3093 // const volatile object.
3094 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3095 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00003096 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00003097
3098 // Set up the conversion sequence as a "bad" conversion, to allow us
3099 // to exit early.
3100 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00003101
3102 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00003103 QualType FromType = OrigFromType;
Ted Kremenek6217b802009-07-29 21:53:49 +00003104 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00003105 FromType = PT->getPointeeType();
3106
3107 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00003108
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00003109 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor96176b32008-11-18 23:14:02 +00003110 // where X is the class of which the function is a member
3111 // (C++ [over.match.funcs]p4). However, when finding an implicit
3112 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00003113 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00003114 // (C++ [over.match.funcs]p5). We perform a simplified version of
3115 // reference binding here, that allows class rvalues to bind to
3116 // non-constant references.
3117
3118 // First check the qualifiers. We don't care about lvalue-vs-rvalue
3119 // with the implicit object parameter (C++ [over.match.funcs]p5).
John McCall120d63c2010-08-24 20:38:10 +00003120 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00003121 if (ImplicitParamType.getCVRQualifiers()
3122 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00003123 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00003124 ICS.setBad(BadConversionSequence::bad_qualifiers,
3125 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003126 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003127 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003128
3129 // Check that we have either the same type or a derived type. It
3130 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00003131 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00003132 ImplicitConversionKind SecondKind;
3133 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3134 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00003135 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00003136 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00003137 else {
John McCallb1bdc622010-02-25 01:37:24 +00003138 ICS.setBad(BadConversionSequence::unrelated_class,
3139 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003140 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003141 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003142
3143 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00003144 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00003145 ICS.Standard.setAsIdentityConversion();
3146 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00003147 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003148 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003149 ICS.Standard.ReferenceBinding = true;
3150 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00003151 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003152 return ICS;
3153}
3154
3155/// PerformObjectArgumentInitialization - Perform initialization of
3156/// the implicit object parameter for the given Method with the given
3157/// expression.
3158bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00003159Sema::PerformObjectArgumentInitialization(Expr *&From,
3160 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00003161 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00003162 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003163 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00003164 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00003165 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003166
Ted Kremenek6217b802009-07-29 21:53:49 +00003167 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003168 FromRecordType = PT->getPointeeType();
3169 DestType = Method->getThisType(Context);
3170 } else {
3171 FromRecordType = From->getType();
3172 DestType = ImplicitParamRecordType;
3173 }
3174
John McCall701c89e2009-12-03 04:06:58 +00003175 // Note that we always use the true parent context when performing
3176 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003177 ImplicitConversionSequence ICS
John McCall120d63c2010-08-24 20:38:10 +00003178 = TryObjectArgumentInitialization(*this, From->getType(), Method,
John McCall701c89e2009-12-03 04:06:58 +00003179 Method->getParent());
John McCall1d318332010-01-12 00:44:57 +00003180 if (ICS.isBad())
Douglas Gregor96176b32008-11-18 23:14:02 +00003181 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003182 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00003183 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003184
Douglas Gregor5fccd362010-03-03 23:55:11 +00003185 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall6bb80172010-03-30 21:47:33 +00003186 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor96176b32008-11-18 23:14:02 +00003187
Douglas Gregor5fccd362010-03-03 23:55:11 +00003188 if (!Context.hasSameType(From->getType(), DestType))
John McCall2de56d12010-08-25 11:45:40 +00003189 ImpCastExprToType(From, DestType, CK_NoOp,
John McCall5baba9d2010-08-25 10:28:54 +00003190 From->getType()->isPointerType() ? VK_RValue : VK_LValue);
Douglas Gregor96176b32008-11-18 23:14:02 +00003191 return false;
3192}
3193
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003194/// TryContextuallyConvertToBool - Attempt to contextually convert the
3195/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00003196static ImplicitConversionSequence
3197TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00003198 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00003199 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00003200 // FIXME: Are these flags correct?
3201 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00003202 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00003203 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003204}
3205
3206/// PerformContextuallyConvertToBool - Perform a contextual conversion
3207/// of the expression From to bool (C++0x [conv]p3).
3208bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
John McCall120d63c2010-08-24 20:38:10 +00003209 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00003210 if (!ICS.isBad())
3211 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003212
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003213 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003214 return Diag(From->getSourceRange().getBegin(),
3215 diag::err_typecheck_bool_condition)
3216 << From->getType() << From->getSourceRange();
3217 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003218}
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003219
3220/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3221/// expression From to 'id'.
John McCall120d63c2010-08-24 20:38:10 +00003222static ImplicitConversionSequence
3223TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3224 QualType Ty = S.Context.getObjCIdType();
3225 return TryImplicitConversion(S, From, Ty,
3226 // FIXME: Are these flags correct?
3227 /*SuppressUserConversions=*/false,
3228 /*AllowExplicit=*/true,
3229 /*InOverloadResolution=*/false);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003230}
John McCall120d63c2010-08-24 20:38:10 +00003231
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003232/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3233/// of the expression From to 'id'.
3234bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCallc12c5bb2010-05-15 11:32:37 +00003235 QualType Ty = Context.getObjCIdType();
John McCall120d63c2010-08-24 20:38:10 +00003236 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003237 if (!ICS.isBad())
3238 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3239 return true;
3240}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003241
Douglas Gregorc30614b2010-06-29 23:17:37 +00003242/// \brief Attempt to convert the given expression to an integral or
3243/// enumeration type.
3244///
3245/// This routine will attempt to convert an expression of class type to an
3246/// integral or enumeration type, if that class type only has a single
3247/// conversion to an integral or enumeration type.
3248///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003249/// \param Loc The source location of the construct that requires the
3250/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00003251///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003252/// \param FromE The expression we're converting from.
3253///
3254/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3255/// have integral or enumeration type.
3256///
3257/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3258/// incomplete class type.
3259///
3260/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3261/// explicit conversion function (because no implicit conversion functions
3262/// were available). This is a recovery mode.
3263///
3264/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3265/// showing which conversion was picked.
3266///
3267/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3268/// conversion function that could convert to integral or enumeration type.
3269///
3270/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3271/// usable conversion function.
3272///
3273/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3274/// function, which may be an extension in this case.
3275///
3276/// \returns The expression, converted to an integral or enumeration type if
3277/// successful.
John McCall60d7b3a2010-08-24 06:29:42 +00003278ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003279Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorc30614b2010-06-29 23:17:37 +00003280 const PartialDiagnostic &NotIntDiag,
3281 const PartialDiagnostic &IncompleteDiag,
3282 const PartialDiagnostic &ExplicitConvDiag,
3283 const PartialDiagnostic &ExplicitConvNote,
3284 const PartialDiagnostic &AmbigDiag,
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003285 const PartialDiagnostic &AmbigNote,
3286 const PartialDiagnostic &ConvDiag) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00003287 // We can't perform any more checking for type-dependent expressions.
3288 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00003289 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003290
3291 // If the expression already has integral or enumeration type, we're golden.
3292 QualType T = From->getType();
3293 if (T->isIntegralOrEnumerationType())
John McCall9ae2f072010-08-23 23:25:46 +00003294 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003295
3296 // FIXME: Check for missing '()' if T is a function type?
3297
3298 // If we don't have a class type in C++, there's no way we can get an
3299 // expression of integral or enumeration type.
3300 const RecordType *RecordTy = T->getAs<RecordType>();
3301 if (!RecordTy || !getLangOptions().CPlusPlus) {
3302 Diag(Loc, NotIntDiag)
3303 << T << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00003304 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003305 }
3306
3307 // We must have a complete class type.
3308 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCall9ae2f072010-08-23 23:25:46 +00003309 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003310
3311 // Look for a conversion to an integral or enumeration type.
3312 UnresolvedSet<4> ViableConversions;
3313 UnresolvedSet<4> ExplicitConversions;
3314 const UnresolvedSetImpl *Conversions
3315 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3316
3317 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3318 E = Conversions->end();
3319 I != E;
3320 ++I) {
3321 if (CXXConversionDecl *Conversion
3322 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3323 if (Conversion->getConversionType().getNonReferenceType()
3324 ->isIntegralOrEnumerationType()) {
3325 if (Conversion->isExplicit())
3326 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3327 else
3328 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3329 }
3330 }
3331
3332 switch (ViableConversions.size()) {
3333 case 0:
3334 if (ExplicitConversions.size() == 1) {
3335 DeclAccessPair Found = ExplicitConversions[0];
3336 CXXConversionDecl *Conversion
3337 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3338
3339 // The user probably meant to invoke the given explicit
3340 // conversion; use it.
3341 QualType ConvTy
3342 = Conversion->getConversionType().getNonReferenceType();
3343 std::string TypeStr;
3344 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3345
3346 Diag(Loc, ExplicitConvDiag)
3347 << T << ConvTy
3348 << FixItHint::CreateInsertion(From->getLocStart(),
3349 "static_cast<" + TypeStr + ">(")
3350 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3351 ")");
3352 Diag(Conversion->getLocation(), ExplicitConvNote)
3353 << ConvTy->isEnumeralType() << ConvTy;
3354
3355 // If we aren't in a SFINAE context, build a call to the
3356 // explicit conversion function.
3357 if (isSFINAEContext())
3358 return ExprError();
3359
3360 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
John McCall9ae2f072010-08-23 23:25:46 +00003361 From = BuildCXXMemberCallExpr(From, Found, Conversion);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003362 }
3363
3364 // We'll complain below about a non-integral condition type.
3365 break;
3366
3367 case 1: {
3368 // Apply this conversion.
3369 DeclAccessPair Found = ViableConversions[0];
3370 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003371
3372 CXXConversionDecl *Conversion
3373 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3374 QualType ConvTy
3375 = Conversion->getConversionType().getNonReferenceType();
3376 if (ConvDiag.getDiagID()) {
3377 if (isSFINAEContext())
3378 return ExprError();
3379
3380 Diag(Loc, ConvDiag)
3381 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3382 }
3383
John McCall9ae2f072010-08-23 23:25:46 +00003384 From = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorc30614b2010-06-29 23:17:37 +00003385 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregorc30614b2010-06-29 23:17:37 +00003386 break;
3387 }
3388
3389 default:
3390 Diag(Loc, AmbigDiag)
3391 << T << From->getSourceRange();
3392 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3393 CXXConversionDecl *Conv
3394 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3395 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3396 Diag(Conv->getLocation(), AmbigNote)
3397 << ConvTy->isEnumeralType() << ConvTy;
3398 }
John McCall9ae2f072010-08-23 23:25:46 +00003399 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003400 }
3401
Douglas Gregoracb0bd82010-06-29 23:25:20 +00003402 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorc30614b2010-06-29 23:17:37 +00003403 Diag(Loc, NotIntDiag)
3404 << From->getType() << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00003405
John McCall9ae2f072010-08-23 23:25:46 +00003406 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003407}
3408
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003409/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00003410/// candidate functions, using the given function call arguments. If
3411/// @p SuppressUserConversions, then don't allow user-defined
3412/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003413///
3414/// \para PartialOverloading true if we are performing "partial" overloading
3415/// based on an incomplete set of function arguments. This feature is used by
3416/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00003417void
3418Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00003419 DeclAccessPair FoundDecl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003420 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00003421 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00003422 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003423 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00003424 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003425 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003426 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00003427 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00003428 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00003429
Douglas Gregor88a35142008-12-22 05:46:06 +00003430 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003431 if (!isa<CXXConstructorDecl>(Method)) {
3432 // If we get here, it's because we're calling a member function
3433 // that is named without a member access expression (e.g.,
3434 // "this->f") that was either written explicitly or created
3435 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00003436 // function, e.g., X::f(). We use an empty type for the implied
3437 // object argument (C++ [over.call.func]p3), and the acting context
3438 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00003439 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall701c89e2009-12-03 04:06:58 +00003440 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003441 SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003442 return;
3443 }
3444 // We treat a constructor like a non-member function, since its object
3445 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00003446 }
3447
Douglas Gregorfd476482009-11-13 23:59:09 +00003448 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00003449 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00003450
Douglas Gregor7edfb692009-11-23 12:27:39 +00003451 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003452 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003453
Douglas Gregor66724ea2009-11-14 01:20:54 +00003454 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3455 // C++ [class.copy]p3:
3456 // A member function template is never instantiated to perform the copy
3457 // of a class object to an object of its class type.
3458 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3459 if (NumArgs == 1 &&
3460 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor12116062010-02-21 18:30:38 +00003461 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3462 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00003463 return;
3464 }
3465
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003466 // Add this candidate
3467 CandidateSet.push_back(OverloadCandidate());
3468 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003469 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003470 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00003471 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003472 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003473 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003474
3475 unsigned NumArgsInProto = Proto->getNumArgs();
3476
3477 // (C++ 13.3.2p2): A candidate function having fewer than m
3478 // parameters is viable only if it has an ellipsis in its parameter
3479 // list (8.3.5).
Douglas Gregor5bd1a112009-09-23 14:56:09 +00003480 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3481 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003482 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003483 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003484 return;
3485 }
3486
3487 // (C++ 13.3.2p2): A candidate function having more than m parameters
3488 // is viable only if the (m+1)st parameter has a default argument
3489 // (8.3.6). For the purposes of overload resolution, the
3490 // parameter list is truncated on the right, so that there are
3491 // exactly m parameters.
3492 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003493 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003494 // Not enough arguments.
3495 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003496 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003497 return;
3498 }
3499
3500 // Determine the implicit conversion sequences for each of the
3501 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003502 Candidate.Conversions.resize(NumArgs);
3503 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3504 if (ArgIdx < NumArgsInProto) {
3505 // (C++ 13.3.2p3): for F to be a viable function, there shall
3506 // exist for each argument an implicit conversion sequence
3507 // (13.3.3.1) that converts that argument to the corresponding
3508 // parameter of F.
3509 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003510 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003511 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003512 SuppressUserConversions,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003513 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003514 if (Candidate.Conversions[ArgIdx].isBad()) {
3515 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003516 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00003517 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00003518 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003519 } else {
3520 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3521 // argument for which there is no corresponding parameter is
3522 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003523 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003524 }
3525 }
3526}
3527
Douglas Gregor063daf62009-03-13 18:40:31 +00003528/// \brief Add all of the function declarations in the given function set to
3529/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00003530void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00003531 Expr **Args, unsigned NumArgs,
3532 OverloadCandidateSet& CandidateSet,
3533 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00003534 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00003535 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3536 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003537 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003538 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003539 cast<CXXMethodDecl>(FD)->getParent(),
3540 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003541 CandidateSet, SuppressUserConversions);
3542 else
John McCall9aa472c2010-03-19 07:35:19 +00003543 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00003544 SuppressUserConversions);
3545 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003546 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00003547 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3548 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003549 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003550 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00003551 /*FIXME: explicit args */ 0,
John McCall701c89e2009-12-03 04:06:58 +00003552 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003553 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00003554 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00003555 else
John McCall9aa472c2010-03-19 07:35:19 +00003556 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCalld5532b62009-11-23 01:53:49 +00003557 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00003558 Args, NumArgs, CandidateSet,
3559 SuppressUserConversions);
3560 }
Douglas Gregor364e0212009-06-27 21:05:07 +00003561 }
Douglas Gregor063daf62009-03-13 18:40:31 +00003562}
3563
John McCall314be4e2009-11-17 07:50:12 +00003564/// AddMethodCandidate - Adds a named decl (which is some kind of
3565/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00003566void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003567 QualType ObjectType,
John McCall314be4e2009-11-17 07:50:12 +00003568 Expr **Args, unsigned NumArgs,
3569 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003570 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00003571 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003572 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00003573
3574 if (isa<UsingShadowDecl>(Decl))
3575 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3576
3577 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3578 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3579 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00003580 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3581 /*ExplicitArgs*/ 0,
John McCall701c89e2009-12-03 04:06:58 +00003582 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00003583 CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003584 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003585 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003586 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall701c89e2009-12-03 04:06:58 +00003587 ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003588 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003589 }
3590}
3591
Douglas Gregor96176b32008-11-18 23:14:02 +00003592/// AddMethodCandidate - Adds the given C++ member function to the set
3593/// of candidate functions, using the given function call arguments
3594/// and the object argument (@c Object). For example, in a call
3595/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3596/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3597/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00003598/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00003599void
John McCall9aa472c2010-03-19 07:35:19 +00003600Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003601 CXXRecordDecl *ActingContext, QualType ObjectType,
3602 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00003603 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003604 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00003605 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003606 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00003607 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003608 assert(!isa<CXXConstructorDecl>(Method) &&
3609 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00003610
Douglas Gregor3f396022009-09-28 04:47:19 +00003611 if (!CandidateSet.isNewCandidate(Method))
3612 return;
3613
Douglas Gregor7edfb692009-11-23 12:27:39 +00003614 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003615 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003616
Douglas Gregor96176b32008-11-18 23:14:02 +00003617 // Add this candidate
3618 CandidateSet.push_back(OverloadCandidate());
3619 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003620 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00003621 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003622 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003623 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003624
3625 unsigned NumArgsInProto = Proto->getNumArgs();
3626
3627 // (C++ 13.3.2p2): A candidate function having fewer than m
3628 // parameters is viable only if it has an ellipsis in its parameter
3629 // list (8.3.5).
3630 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3631 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003632 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003633 return;
3634 }
3635
3636 // (C++ 13.3.2p2): A candidate function having more than m parameters
3637 // is viable only if the (m+1)st parameter has a default argument
3638 // (8.3.6). For the purposes of overload resolution, the
3639 // parameter list is truncated on the right, so that there are
3640 // exactly m parameters.
3641 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3642 if (NumArgs < MinRequiredArgs) {
3643 // Not enough arguments.
3644 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003645 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003646 return;
3647 }
3648
3649 Candidate.Viable = true;
3650 Candidate.Conversions.resize(NumArgs + 1);
3651
John McCall701c89e2009-12-03 04:06:58 +00003652 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00003653 // The implicit object argument is ignored.
3654 Candidate.IgnoreObjectArgument = true;
3655 else {
3656 // Determine the implicit conversion sequence for the object
3657 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00003658 Candidate.Conversions[0]
John McCall120d63c2010-08-24 20:38:10 +00003659 = TryObjectArgumentInitialization(*this, ObjectType, Method,
3660 ActingContext);
John McCall1d318332010-01-12 00:44:57 +00003661 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003662 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003663 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00003664 return;
3665 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003666 }
3667
3668 // Determine the implicit conversion sequences for each of the
3669 // arguments.
3670 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3671 if (ArgIdx < NumArgsInProto) {
3672 // (C++ 13.3.2p3): for F to be a viable function, there shall
3673 // exist for each argument an implicit conversion sequence
3674 // (13.3.3.1) that converts that argument to the corresponding
3675 // parameter of F.
3676 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003677 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003678 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003679 SuppressUserConversions,
Anders Carlsson08972922009-08-28 15:33:32 +00003680 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003681 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00003682 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003683 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00003684 break;
3685 }
3686 } else {
3687 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3688 // argument for which there is no corresponding parameter is
3689 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003690 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00003691 }
3692 }
3693}
Douglas Gregora9333192010-05-08 17:41:32 +00003694
Douglas Gregor6b906862009-08-21 00:16:32 +00003695/// \brief Add a C++ member function template as a candidate to the candidate
3696/// set, using template argument deduction to produce an appropriate member
3697/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003698void
Douglas Gregor6b906862009-08-21 00:16:32 +00003699Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00003700 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003701 CXXRecordDecl *ActingContext,
John McCalld5532b62009-11-23 01:53:49 +00003702 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00003703 QualType ObjectType,
3704 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003705 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003706 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003707 if (!CandidateSet.isNewCandidate(MethodTmpl))
3708 return;
3709
Douglas Gregor6b906862009-08-21 00:16:32 +00003710 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003711 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00003712 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003713 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00003714 // candidate functions in the usual way.113) A given name can refer to one
3715 // or more function templates and also to a set of overloaded non-template
3716 // functions. In such a case, the candidate functions generated from each
3717 // function template are combined with the set of non-template candidate
3718 // functions.
John McCall5769d612010-02-08 23:07:23 +00003719 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00003720 FunctionDecl *Specialization = 0;
3721 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003722 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003723 Args, NumArgs, Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003724 CandidateSet.push_back(OverloadCandidate());
3725 OverloadCandidate &Candidate = CandidateSet.back();
3726 Candidate.FoundDecl = FoundDecl;
3727 Candidate.Function = MethodTmpl->getTemplatedDecl();
3728 Candidate.Viable = false;
3729 Candidate.FailureKind = ovl_fail_bad_deduction;
3730 Candidate.IsSurrogate = false;
3731 Candidate.IgnoreObjectArgument = false;
3732 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3733 Info);
3734 return;
3735 }
Mike Stump1eb44332009-09-09 15:08:12 +00003736
Douglas Gregor6b906862009-08-21 00:16:32 +00003737 // Add the function template specialization produced by template argument
3738 // deduction as a candidate.
3739 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00003740 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00003741 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00003742 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003743 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003744 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00003745}
3746
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003747/// \brief Add a C++ function template specialization as a candidate
3748/// in the candidate set, using template argument deduction to produce
3749/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003750void
Douglas Gregore53060f2009-06-25 22:08:12 +00003751Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003752 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00003753 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00003754 Expr **Args, unsigned NumArgs,
3755 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003756 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003757 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3758 return;
3759
Douglas Gregore53060f2009-06-25 22:08:12 +00003760 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003761 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00003762 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003763 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00003764 // candidate functions in the usual way.113) A given name can refer to one
3765 // or more function templates and also to a set of overloaded non-template
3766 // functions. In such a case, the candidate functions generated from each
3767 // function template are combined with the set of non-template candidate
3768 // functions.
John McCall5769d612010-02-08 23:07:23 +00003769 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00003770 FunctionDecl *Specialization = 0;
3771 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003772 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003773 Args, NumArgs, Specialization, Info)) {
John McCall578b69b2009-12-16 08:11:27 +00003774 CandidateSet.push_back(OverloadCandidate());
3775 OverloadCandidate &Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003776 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00003777 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3778 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003779 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00003780 Candidate.IsSurrogate = false;
3781 Candidate.IgnoreObjectArgument = false;
Douglas Gregorff5adac2010-05-08 20:18:54 +00003782 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3783 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00003784 return;
3785 }
Mike Stump1eb44332009-09-09 15:08:12 +00003786
Douglas Gregore53060f2009-06-25 22:08:12 +00003787 // Add the function template specialization produced by template argument
3788 // deduction as a candidate.
3789 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003790 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003791 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00003792}
Mike Stump1eb44332009-09-09 15:08:12 +00003793
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003794/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00003795/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003796/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00003797/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003798/// (which may or may not be the same type as the type that the
3799/// conversion function produces).
3800void
3801Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003802 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003803 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003804 Expr *From, QualType ToType,
3805 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003806 assert(!Conversion->getDescribedFunctionTemplate() &&
3807 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003808 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00003809 if (!CandidateSet.isNewCandidate(Conversion))
3810 return;
3811
Douglas Gregor7edfb692009-11-23 12:27:39 +00003812 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003813 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003814
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003815 // Add this candidate
3816 CandidateSet.push_back(OverloadCandidate());
3817 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003818 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003819 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003820 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003821 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003822 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003823 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003824 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003825 Candidate.Viable = true;
3826 Candidate.Conversions.resize(1);
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003827
Douglas Gregorbca39322010-08-19 15:37:02 +00003828 // C++ [over.match.funcs]p4:
3829 // For conversion functions, the function is considered to be a member of
3830 // the class of the implicit implied object argument for the purpose of
3831 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003832 //
3833 // Determine the implicit conversion sequence for the implicit
3834 // object parameter.
3835 QualType ImplicitParamType = From->getType();
3836 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
3837 ImplicitParamType = FromPtrType->getPointeeType();
3838 CXXRecordDecl *ConversionContext
3839 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
3840
3841 Candidate.Conversions[0]
John McCall120d63c2010-08-24 20:38:10 +00003842 = TryObjectArgumentInitialization(*this, From->getType(), Conversion,
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003843 ConversionContext);
3844
John McCall1d318332010-01-12 00:44:57 +00003845 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003846 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003847 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003848 return;
3849 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003850
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003851 // We won't go through a user-define type conversion function to convert a
3852 // derived to base as such conversions are given Conversion Rank. They only
3853 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3854 QualType FromCanon
3855 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3856 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3857 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3858 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003859 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003860 return;
3861 }
3862
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003863 // To determine what the conversion from the result of calling the
3864 // conversion function to the type we're eventually trying to
3865 // convert to (ToType), we need to synthesize a call to the
3866 // conversion function and attempt copy initialization from it. This
3867 // makes sure that we get the right semantics with respect to
3868 // lvalues/rvalues and the type. Fortunately, we can allocate this
3869 // call on the stack and we don't need its arguments to be
3870 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00003871 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003872 From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00003873 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
3874 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00003875 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00003876 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00003877
3878 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00003879 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3880 // allocator).
Mike Stump1eb44332009-09-09 15:08:12 +00003881 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregor63982352010-07-13 18:40:04 +00003882 Conversion->getConversionType().getNonLValueExprType(Context),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003883 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00003884 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00003885 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00003886 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003887 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00003888
John McCall1d318332010-01-12 00:44:57 +00003889 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003890 case ImplicitConversionSequence::StandardConversion:
3891 Candidate.FinalConversion = ICS.Standard;
Douglas Gregorc520c842010-04-12 23:42:09 +00003892
3893 // C++ [over.ics.user]p3:
3894 // If the user-defined conversion is specified by a specialization of a
3895 // conversion function template, the second standard conversion sequence
3896 // shall have exact match rank.
3897 if (Conversion->getPrimaryTemplate() &&
3898 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3899 Candidate.Viable = false;
3900 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3901 }
3902
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003903 break;
3904
3905 case ImplicitConversionSequence::BadConversion:
3906 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003907 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003908 break;
3909
3910 default:
Mike Stump1eb44332009-09-09 15:08:12 +00003911 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003912 "Can only end up with a standard conversion sequence or failure");
3913 }
3914}
3915
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003916/// \brief Adds a conversion function template specialization
3917/// candidate to the overload set, using template argument deduction
3918/// to deduce the template arguments of the conversion function
3919/// template from the type that we are converting to (C++
3920/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00003921void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003922Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003923 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003924 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003925 Expr *From, QualType ToType,
3926 OverloadCandidateSet &CandidateSet) {
3927 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3928 "Only conversion function templates permitted here");
3929
Douglas Gregor3f396022009-09-28 04:47:19 +00003930 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3931 return;
3932
John McCall5769d612010-02-08 23:07:23 +00003933 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003934 CXXConversionDecl *Specialization = 0;
3935 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00003936 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003937 Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003938 CandidateSet.push_back(OverloadCandidate());
3939 OverloadCandidate &Candidate = CandidateSet.back();
3940 Candidate.FoundDecl = FoundDecl;
3941 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3942 Candidate.Viable = false;
3943 Candidate.FailureKind = ovl_fail_bad_deduction;
3944 Candidate.IsSurrogate = false;
3945 Candidate.IgnoreObjectArgument = false;
3946 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3947 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003948 return;
3949 }
Mike Stump1eb44332009-09-09 15:08:12 +00003950
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003951 // Add the conversion function template specialization produced by
3952 // template argument deduction as a candidate.
3953 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003954 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00003955 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003956}
3957
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003958/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3959/// converts the given @c Object to a function pointer via the
3960/// conversion function @c Conversion, and then attempts to call it
3961/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3962/// the type of function that we'll eventually be calling.
3963void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003964 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003965 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00003966 const FunctionProtoType *Proto,
John McCall701c89e2009-12-03 04:06:58 +00003967 QualType ObjectType,
3968 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003969 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003970 if (!CandidateSet.isNewCandidate(Conversion))
3971 return;
3972
Douglas Gregor7edfb692009-11-23 12:27:39 +00003973 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003974 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003975
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003976 CandidateSet.push_back(OverloadCandidate());
3977 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003978 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003979 Candidate.Function = 0;
3980 Candidate.Surrogate = Conversion;
3981 Candidate.Viable = true;
3982 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003983 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003984 Candidate.Conversions.resize(NumArgs + 1);
3985
3986 // Determine the implicit conversion sequence for the implicit
3987 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00003988 ImplicitConversionSequence ObjectInit
John McCall120d63c2010-08-24 20:38:10 +00003989 = TryObjectArgumentInitialization(*this, ObjectType, Conversion,
3990 ActingContext);
John McCall1d318332010-01-12 00:44:57 +00003991 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003992 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003993 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00003994 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003995 return;
3996 }
3997
3998 // The first conversion is actually a user-defined conversion whose
3999 // first conversion is ObjectInit's standard conversion (which is
4000 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00004001 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004002 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00004003 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004004 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00004005 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004006 = Candidate.Conversions[0].UserDefined.Before;
4007 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4008
Mike Stump1eb44332009-09-09 15:08:12 +00004009 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004010 unsigned NumArgsInProto = Proto->getNumArgs();
4011
4012 // (C++ 13.3.2p2): A candidate function having fewer than m
4013 // parameters is viable only if it has an ellipsis in its parameter
4014 // list (8.3.5).
4015 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4016 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004017 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004018 return;
4019 }
4020
4021 // Function types don't have any default arguments, so just check if
4022 // we have enough arguments.
4023 if (NumArgs < NumArgsInProto) {
4024 // Not enough arguments.
4025 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004026 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004027 return;
4028 }
4029
4030 // Determine the implicit conversion sequences for each of the
4031 // arguments.
4032 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4033 if (ArgIdx < NumArgsInProto) {
4034 // (C++ 13.3.2p3): for F to be a viable function, there shall
4035 // exist for each argument an implicit conversion sequence
4036 // (13.3.3.1) that converts that argument to the corresponding
4037 // parameter of F.
4038 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00004039 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004040 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00004041 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00004042 /*InOverloadResolution=*/false);
John McCall1d318332010-01-12 00:44:57 +00004043 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004044 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004045 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004046 break;
4047 }
4048 } else {
4049 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4050 // argument for which there is no corresponding parameter is
4051 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00004052 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004053 }
4054 }
4055}
4056
Douglas Gregor063daf62009-03-13 18:40:31 +00004057/// \brief Add overload candidates for overloaded operators that are
4058/// member functions.
4059///
4060/// Add the overloaded operator candidates that are member functions
4061/// for the operator Op that was used in an operator expression such
4062/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4063/// CandidateSet will store the added overload candidates. (C++
4064/// [over.match.oper]).
4065void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4066 SourceLocation OpLoc,
4067 Expr **Args, unsigned NumArgs,
4068 OverloadCandidateSet& CandidateSet,
4069 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00004070 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4071
4072 // C++ [over.match.oper]p3:
4073 // For a unary operator @ with an operand of a type whose
4074 // cv-unqualified version is T1, and for a binary operator @ with
4075 // a left operand of a type whose cv-unqualified version is T1 and
4076 // a right operand of a type whose cv-unqualified version is T2,
4077 // three sets of candidate functions, designated member
4078 // candidates, non-member candidates and built-in candidates, are
4079 // constructed as follows:
4080 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00004081
4082 // -- If T1 is a class type, the set of member candidates is the
4083 // result of the qualified lookup of T1::operator@
4084 // (13.3.1.1.1); otherwise, the set of member candidates is
4085 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00004086 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004087 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004088 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004089 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004090
John McCalla24dc2e2009-11-17 02:14:36 +00004091 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4092 LookupQualifiedName(Operators, T1Rec->getDecl());
4093 Operators.suppressDiagnostics();
4094
Mike Stump1eb44332009-09-09 15:08:12 +00004095 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004096 OperEnd = Operators.end();
4097 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00004098 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00004099 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall701c89e2009-12-03 04:06:58 +00004100 Args + 1, NumArgs - 1, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00004101 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00004102 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004103}
4104
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004105/// AddBuiltinCandidate - Add a candidate for a built-in
4106/// operator. ResultTy and ParamTys are the result and parameter types
4107/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004108/// arguments being passed to the candidate. IsAssignmentOperator
4109/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004110/// operator. NumContextualBoolArguments is the number of arguments
4111/// (at the beginning of the argument list) that will be contextually
4112/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00004113void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004114 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004115 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004116 bool IsAssignmentOperator,
4117 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00004118 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004119 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004120
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004121 // Add this candidate
4122 CandidateSet.push_back(OverloadCandidate());
4123 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004124 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004125 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00004126 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004127 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004128 Candidate.BuiltinTypes.ResultTy = ResultTy;
4129 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4130 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4131
4132 // Determine the implicit conversion sequences for each of the
4133 // arguments.
4134 Candidate.Viable = true;
4135 Candidate.Conversions.resize(NumArgs);
4136 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004137 // C++ [over.match.oper]p4:
4138 // For the built-in assignment operators, conversions of the
4139 // left operand are restricted as follows:
4140 // -- no temporaries are introduced to hold the left operand, and
4141 // -- no user-defined conversions are applied to the left
4142 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00004143 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004144 //
4145 // We block these conversions by turning off user-defined
4146 // conversions, since that is the only way that initialization of
4147 // a reference to a non-class type can occur from something that
4148 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004149 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00004150 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004151 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00004152 Candidate.Conversions[ArgIdx]
4153 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004154 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00004155 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004156 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00004157 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00004158 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004159 }
John McCall1d318332010-01-12 00:44:57 +00004160 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004161 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004162 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00004163 break;
4164 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004165 }
4166}
4167
4168/// BuiltinCandidateTypeSet - A set of types that will be used for the
4169/// candidate operator functions for built-in operators (C++
4170/// [over.built]). The types are separated into pointer types and
4171/// enumeration types.
4172class BuiltinCandidateTypeSet {
4173 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004174 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004175
4176 /// PointerTypes - The set of pointer types that will be used in the
4177 /// built-in candidates.
4178 TypeSet PointerTypes;
4179
Sebastian Redl78eb8742009-04-19 21:53:20 +00004180 /// MemberPointerTypes - The set of member pointer types that will be
4181 /// used in the built-in candidates.
4182 TypeSet MemberPointerTypes;
4183
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004184 /// EnumerationTypes - The set of enumeration types that will be
4185 /// used in the built-in candidates.
4186 TypeSet EnumerationTypes;
4187
Douglas Gregor26bcf672010-05-19 03:21:00 +00004188 /// \brief The set of vector types that will be used in the built-in
4189 /// candidates.
4190 TypeSet VectorTypes;
4191
Douglas Gregor5842ba92009-08-24 15:23:48 +00004192 /// Sema - The semantic analysis instance where we are building the
4193 /// candidate type set.
4194 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00004195
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004196 /// Context - The AST context in which we will build the type sets.
4197 ASTContext &Context;
4198
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004199 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4200 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00004201 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004202
4203public:
4204 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004205 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004206
Mike Stump1eb44332009-09-09 15:08:12 +00004207 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor5842ba92009-08-24 15:23:48 +00004208 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004209
Douglas Gregor573d9c32009-10-21 23:19:44 +00004210 void AddTypesConvertedFrom(QualType Ty,
4211 SourceLocation Loc,
4212 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004213 bool AllowExplicitConversions,
4214 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004215
4216 /// pointer_begin - First pointer type found;
4217 iterator pointer_begin() { return PointerTypes.begin(); }
4218
Sebastian Redl78eb8742009-04-19 21:53:20 +00004219 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004220 iterator pointer_end() { return PointerTypes.end(); }
4221
Sebastian Redl78eb8742009-04-19 21:53:20 +00004222 /// member_pointer_begin - First member pointer type found;
4223 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4224
4225 /// member_pointer_end - Past the last member pointer type found;
4226 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4227
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004228 /// enumeration_begin - First enumeration type found;
4229 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4230
Sebastian Redl78eb8742009-04-19 21:53:20 +00004231 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004232 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004233
4234 iterator vector_begin() { return VectorTypes.begin(); }
4235 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004236};
4237
Sebastian Redl78eb8742009-04-19 21:53:20 +00004238/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004239/// the set of pointer types along with any more-qualified variants of
4240/// that type. For example, if @p Ty is "int const *", this routine
4241/// will add "int const *", "int const volatile *", "int const
4242/// restrict *", and "int const volatile restrict *" to the set of
4243/// pointer types. Returns true if the add of @p Ty itself succeeded,
4244/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00004245///
4246/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004247bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00004248BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4249 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00004250
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004251 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004252 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004253 return false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004254
4255 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00004256 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004257 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004258 if (!PointerTy) {
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004259 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004260 PointeeTy = PTy->getPointeeType();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004261 buildObjCPtr = true;
4262 }
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004263 else
4264 assert(false && "type was not a pointer type!");
4265 }
4266 else
4267 PointeeTy = PointerTy->getPointeeType();
4268
Sebastian Redla9efada2009-11-18 20:39:26 +00004269 // Don't add qualified variants of arrays. For one, they're not allowed
4270 // (the qualifier would sink to the element type), and for another, the
4271 // only overload situation where it matters is subscript or pointer +- int,
4272 // and those shouldn't have qualifier variants anyway.
4273 if (PointeeTy->isArrayType())
4274 return true;
John McCall0953e762009-09-24 19:53:00 +00004275 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00004276 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00004277 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004278 bool hasVolatile = VisibleQuals.hasVolatile();
4279 bool hasRestrict = VisibleQuals.hasRestrict();
4280
John McCall0953e762009-09-24 19:53:00 +00004281 // Iterate through all strict supersets of BaseCVR.
4282 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4283 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004284 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4285 // in the types.
4286 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4287 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00004288 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004289 if (!buildObjCPtr)
4290 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4291 else
4292 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004293 }
4294
4295 return true;
4296}
4297
Sebastian Redl78eb8742009-04-19 21:53:20 +00004298/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4299/// to the set of pointer types along with any more-qualified variants of
4300/// that type. For example, if @p Ty is "int const *", this routine
4301/// will add "int const *", "int const volatile *", "int const
4302/// restrict *", and "int const volatile restrict *" to the set of
4303/// pointer types. Returns true if the add of @p Ty itself succeeded,
4304/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00004305///
4306/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004307bool
4308BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4309 QualType Ty) {
4310 // Insert this type.
4311 if (!MemberPointerTypes.insert(Ty))
4312 return false;
4313
John McCall0953e762009-09-24 19:53:00 +00004314 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4315 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00004316
John McCall0953e762009-09-24 19:53:00 +00004317 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00004318 // Don't add qualified variants of arrays. For one, they're not allowed
4319 // (the qualifier would sink to the element type), and for another, the
4320 // only overload situation where it matters is subscript or pointer +- int,
4321 // and those shouldn't have qualifier variants anyway.
4322 if (PointeeTy->isArrayType())
4323 return true;
John McCall0953e762009-09-24 19:53:00 +00004324 const Type *ClassTy = PointerTy->getClass();
4325
4326 // Iterate through all strict supersets of the pointee type's CVR
4327 // qualifiers.
4328 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4329 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4330 if ((CVR | BaseCVR) != CVR) continue;
4331
4332 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4333 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00004334 }
4335
4336 return true;
4337}
4338
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004339/// AddTypesConvertedFrom - Add each of the types to which the type @p
4340/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00004341/// primarily interested in pointer types and enumeration types. We also
4342/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004343/// AllowUserConversions is true if we should look at the conversion
4344/// functions of a class type, and AllowExplicitConversions if we
4345/// should also include the explicit conversion functions of a class
4346/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00004347void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004348BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004349 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004350 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004351 bool AllowExplicitConversions,
4352 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004353 // Only deal with canonical types.
4354 Ty = Context.getCanonicalType(Ty);
4355
4356 // Look through reference types; they aren't part of the type of an
4357 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00004358 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004359 Ty = RefTy->getPointeeType();
4360
4361 // We don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004362 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004363
Sebastian Redla65b5512009-11-05 16:36:20 +00004364 // If we're dealing with an array type, decay to the pointer.
4365 if (Ty->isArrayType())
4366 Ty = SemaRef.Context.getArrayDecayedType(Ty);
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004367 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4368 PointerTypes.insert(Ty);
4369 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004370 // Insert our type, and its more-qualified variants, into the set
4371 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004372 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004373 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00004374 } else if (Ty->isMemberPointerType()) {
4375 // Member pointers are far easier, since the pointee can't be converted.
4376 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4377 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004378 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00004379 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004380 } else if (Ty->isVectorType()) {
4381 VectorTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004382 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004383 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00004384 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00004385 // No conversion functions in incomplete types.
4386 return;
4387 }
Mike Stump1eb44332009-09-09 15:08:12 +00004388
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004389 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00004390 const UnresolvedSetImpl *Conversions
Fariborz Jahanianca4fb042009-10-07 17:26:09 +00004391 = ClassDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00004392 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004393 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00004394 NamedDecl *D = I.getDecl();
4395 if (isa<UsingShadowDecl>(D))
4396 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004397
Mike Stump1eb44332009-09-09 15:08:12 +00004398 // Skip conversion function templates; they don't tell us anything
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004399 // about which builtin types we can convert to.
John McCall32daa422010-03-31 01:36:47 +00004400 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004401 continue;
4402
John McCall32daa422010-03-31 01:36:47 +00004403 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004404 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00004405 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004406 VisibleQuals);
4407 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004408 }
4409 }
4410 }
4411}
4412
Douglas Gregor19b7b152009-08-24 13:43:27 +00004413/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4414/// the volatile- and non-volatile-qualified assignment operators for the
4415/// given type to the candidate set.
4416static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4417 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00004418 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004419 unsigned NumArgs,
4420 OverloadCandidateSet &CandidateSet) {
4421 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00004422
Douglas Gregor19b7b152009-08-24 13:43:27 +00004423 // T& operator=(T&, T)
4424 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4425 ParamTypes[1] = T;
4426 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4427 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004428
Douglas Gregor19b7b152009-08-24 13:43:27 +00004429 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4430 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00004431 ParamTypes[0]
4432 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00004433 ParamTypes[1] = T;
4434 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00004435 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00004436 }
4437}
Mike Stump1eb44332009-09-09 15:08:12 +00004438
Sebastian Redl9994a342009-10-25 17:03:50 +00004439/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4440/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004441static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4442 Qualifiers VRQuals;
4443 const RecordType *TyRec;
4444 if (const MemberPointerType *RHSMPType =
4445 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004446 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004447 else
4448 TyRec = ArgExpr->getType()->getAs<RecordType>();
4449 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004450 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004451 VRQuals.addVolatile();
4452 VRQuals.addRestrict();
4453 return VRQuals;
4454 }
4455
4456 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00004457 if (!ClassDecl->hasDefinition())
4458 return VRQuals;
4459
John McCalleec51cf2010-01-20 00:46:10 +00004460 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00004461 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004462
John McCalleec51cf2010-01-20 00:46:10 +00004463 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004464 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00004465 NamedDecl *D = I.getDecl();
4466 if (isa<UsingShadowDecl>(D))
4467 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4468 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004469 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4470 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4471 CanTy = ResTypeRef->getPointeeType();
4472 // Need to go down the pointer/mempointer chain and add qualifiers
4473 // as see them.
4474 bool done = false;
4475 while (!done) {
4476 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4477 CanTy = ResTypePtr->getPointeeType();
4478 else if (const MemberPointerType *ResTypeMPtr =
4479 CanTy->getAs<MemberPointerType>())
4480 CanTy = ResTypeMPtr->getPointeeType();
4481 else
4482 done = true;
4483 if (CanTy.isVolatileQualified())
4484 VRQuals.addVolatile();
4485 if (CanTy.isRestrictQualified())
4486 VRQuals.addRestrict();
4487 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4488 return VRQuals;
4489 }
4490 }
4491 }
4492 return VRQuals;
4493}
4494
Douglas Gregor74253732008-11-19 15:42:04 +00004495/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4496/// operator overloads to the candidate set (C++ [over.built]), based
4497/// on the operator @p Op and the arguments given. For example, if the
4498/// operator is a binary '+', this routine might add "int
4499/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004500void
Mike Stump1eb44332009-09-09 15:08:12 +00004501Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004502 SourceLocation OpLoc,
Douglas Gregor74253732008-11-19 15:42:04 +00004503 Expr **Args, unsigned NumArgs,
4504 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004505 // The set of "promoted arithmetic types", which are the arithmetic
4506 // types are that preserved by promotion (C++ [over.built]p2). Note
4507 // that the first few of these types are the promoted integral
4508 // types; these types need to be first.
4509 // FIXME: What about complex?
4510 const unsigned FirstIntegralType = 0;
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00004511 const unsigned LastIntegralType = 15;
4512 const unsigned FirstPromotedIntegralType = 9,
4513 LastPromotedIntegralType = 15;
4514 const unsigned FirstPromotedArithmeticType = 9,
4515 LastPromotedArithmeticType = 18;
4516 const unsigned NumArithmeticTypes = 18;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004517 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump1eb44332009-09-09 15:08:12 +00004518 Context.BoolTy, Context.CharTy, Context.WCharTy,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00004519 Context.Char16Ty, Context.Char32Ty,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004520 Context.SignedCharTy, Context.ShortTy,
4521 Context.UnsignedCharTy, Context.UnsignedShortTy,
4522 Context.IntTy, Context.LongTy, Context.LongLongTy,
4523 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
4524 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
4525 };
Douglas Gregor652371a2009-10-21 22:01:30 +00004526 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
4527 "Invalid first promoted integral type");
4528 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4529 == Context.UnsignedLongLongTy &&
4530 "Invalid last promoted integral type");
4531 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
4532 "Invalid first promoted arithmetic type");
4533 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4534 == Context.LongDoubleTy &&
4535 "Invalid last promoted arithmetic type");
4536
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004537 // Find all of the types that the arguments can convert to, but only
4538 // if the operator we're looking at has built-in operator candidates
4539 // that make use of these types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004540 Qualifiers VisibleTypeConversionsQuals;
4541 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004542 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4543 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4544
Douglas Gregorfec56e72010-11-03 17:00:07 +00004545 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
4546 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4547 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
4548 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4549 OpLoc,
4550 true,
4551 (Op == OO_Exclaim ||
4552 Op == OO_AmpAmp ||
4553 Op == OO_PipePipe),
4554 VisibleTypeConversionsQuals);
4555 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004556
Douglas Gregor661b4932010-09-12 04:28:07 +00004557 // C++ [over.built]p1:
4558 // If there is a user-written candidate with the same name and parameter
4559 // types as a built-in candidate operator function, the built-in operator
4560 // function is hidden and is not included in the set of candidate functions.
4561 //
4562 // The text is actually in a note, but if we don't implement it then we end
4563 // up with ambiguities when the user provides an overloaded operator for
4564 // an enumeration type. Note that only enumeration types have this problem,
4565 // so we track which enumeration types we've seen operators for.
4566 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
4567 UserDefinedBinaryOperators;
4568
Douglas Gregorfec56e72010-11-03 17:00:07 +00004569 /// Set of (canonical) types that we've already handled.
4570 llvm::SmallPtrSet<QualType, 8> AddedTypes;
4571
4572 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4573 if (CandidateTypes[ArgIdx].enumeration_begin()
4574 != CandidateTypes[ArgIdx].enumeration_end()) {
4575 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
4576 CEnd = CandidateSet.end();
4577 C != CEnd; ++C) {
4578 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
4579 continue;
4580
4581 // Check if the first parameter is of enumeration type.
4582 QualType FirstParamType
4583 = C->Function->getParamDecl(0)->getType().getUnqualifiedType();
4584 if (!FirstParamType->isEnumeralType())
4585 continue;
4586
4587 // Check if the second parameter is of enumeration type.
4588 QualType SecondParamType
4589 = C->Function->getParamDecl(1)->getType().getUnqualifiedType();
4590 if (!SecondParamType->isEnumeralType())
4591 continue;
Douglas Gregor661b4932010-09-12 04:28:07 +00004592
Douglas Gregorfec56e72010-11-03 17:00:07 +00004593 // Add this operator to the set of known user-defined operators.
4594 UserDefinedBinaryOperators.insert(
4595 std::make_pair(Context.getCanonicalType(FirstParamType),
4596 Context.getCanonicalType(SecondParamType)));
4597 }
Douglas Gregor661b4932010-09-12 04:28:07 +00004598 }
4599 }
4600
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004601 bool isComparison = false;
4602 switch (Op) {
4603 case OO_None:
4604 case NUM_OVERLOADED_OPERATORS:
4605 assert(false && "Expected an overloaded operator");
4606 break;
4607
Douglas Gregor74253732008-11-19 15:42:04 +00004608 case OO_Star: // '*' is either unary or binary
Mike Stump1eb44332009-09-09 15:08:12 +00004609 if (NumArgs == 1)
Douglas Gregor74253732008-11-19 15:42:04 +00004610 goto UnaryStar;
4611 else
4612 goto BinaryStar;
4613 break;
4614
4615 case OO_Plus: // '+' is either unary or binary
4616 if (NumArgs == 1)
4617 goto UnaryPlus;
4618 else
4619 goto BinaryPlus;
4620 break;
4621
4622 case OO_Minus: // '-' is either unary or binary
4623 if (NumArgs == 1)
4624 goto UnaryMinus;
4625 else
4626 goto BinaryMinus;
4627 break;
4628
4629 case OO_Amp: // '&' is either unary or binary
4630 if (NumArgs == 1)
4631 goto UnaryAmp;
4632 else
4633 goto BinaryAmp;
4634
4635 case OO_PlusPlus:
4636 case OO_MinusMinus:
4637 // C++ [over.built]p3:
4638 //
4639 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4640 // is either volatile or empty, there exist candidate operator
4641 // functions of the form
4642 //
4643 // VQ T& operator++(VQ T&);
4644 // T operator++(VQ T&, int);
4645 //
4646 // C++ [over.built]p4:
4647 //
4648 // For every pair (T, VQ), where T is an arithmetic type other
4649 // than bool, and VQ is either volatile or empty, there exist
4650 // candidate operator functions of the form
4651 //
4652 // VQ T& operator--(VQ T&);
4653 // T operator--(VQ T&, int);
Mike Stump1eb44332009-09-09 15:08:12 +00004654 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor74253732008-11-19 15:42:04 +00004655 Arith < NumArithmeticTypes; ++Arith) {
4656 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump1eb44332009-09-09 15:08:12 +00004657 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004658 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00004659
4660 // Non-volatile version.
4661 if (NumArgs == 1)
4662 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4663 else
4664 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004665 // heuristic to reduce number of builtin candidates in the set.
4666 // Add volatile version only if there are conversions to a volatile type.
4667 if (VisibleTypeConversionsQuals.hasVolatile()) {
4668 // Volatile version
4669 ParamTypes[0]
4670 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4671 if (NumArgs == 1)
4672 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4673 else
4674 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4675 }
Douglas Gregor74253732008-11-19 15:42:04 +00004676 }
4677
4678 // C++ [over.built]p5:
4679 //
4680 // For every pair (T, VQ), where T is a cv-qualified or
4681 // cv-unqualified object type, and VQ is either volatile or
4682 // empty, there exist candidate operator functions of the form
4683 //
4684 // T*VQ& operator++(T*VQ&);
4685 // T*VQ& operator--(T*VQ&);
4686 // T* operator++(T*VQ&, int);
4687 // T* operator--(T*VQ&, int);
Douglas Gregorfec56e72010-11-03 17:00:07 +00004688 for (BuiltinCandidateTypeSet::iterator
4689 Ptr = CandidateTypes[0].pointer_begin(),
4690 PtrEnd = CandidateTypes[0].pointer_end();
4691 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor74253732008-11-19 15:42:04 +00004692 // Skip pointer types that aren't pointers to object types.
Eli Friedman13578692010-08-05 02:49:48 +00004693 if (!(*Ptr)->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00004694 continue;
4695
Mike Stump1eb44332009-09-09 15:08:12 +00004696 QualType ParamTypes[2] = {
4697 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00004698 };
Mike Stump1eb44332009-09-09 15:08:12 +00004699
Douglas Gregor74253732008-11-19 15:42:04 +00004700 // Without volatile
4701 if (NumArgs == 1)
4702 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4703 else
4704 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4705
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004706 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4707 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00004708 // With volatile
John McCall0953e762009-09-24 19:53:00 +00004709 ParamTypes[0]
4710 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor74253732008-11-19 15:42:04 +00004711 if (NumArgs == 1)
4712 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4713 else
4714 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4715 }
4716 }
4717 break;
4718
4719 UnaryStar:
4720 // C++ [over.built]p6:
4721 // For every cv-qualified or cv-unqualified object type T, there
4722 // exist candidate operator functions of the form
4723 //
4724 // T& operator*(T*);
4725 //
4726 // C++ [over.built]p7:
4727 // For every function type T, there exist candidate operator
4728 // functions of the form
4729 // T& operator*(T*);
Douglas Gregorfec56e72010-11-03 17:00:07 +00004730 for (BuiltinCandidateTypeSet::iterator
4731 Ptr = CandidateTypes[0].pointer_begin(),
4732 PtrEnd = CandidateTypes[0].pointer_end();
4733 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor74253732008-11-19 15:42:04 +00004734 QualType ParamTy = *Ptr;
Argyrios Kyrtzidis42d0f2a2010-08-23 07:12:16 +00004735 QualType PointeeTy = ParamTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004736 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00004737 &ParamTy, Args, 1, CandidateSet);
4738 }
4739 break;
4740
4741 UnaryPlus:
4742 // C++ [over.built]p8:
4743 // For every type T, there exist candidate operator functions of
4744 // the form
4745 //
4746 // T* operator+(T*);
Douglas Gregorfec56e72010-11-03 17:00:07 +00004747 for (BuiltinCandidateTypeSet::iterator
4748 Ptr = CandidateTypes[0].pointer_begin(),
4749 PtrEnd = CandidateTypes[0].pointer_end();
4750 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor74253732008-11-19 15:42:04 +00004751 QualType ParamTy = *Ptr;
4752 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4753 }
Mike Stump1eb44332009-09-09 15:08:12 +00004754
Douglas Gregor74253732008-11-19 15:42:04 +00004755 // Fall through
4756
4757 UnaryMinus:
4758 // C++ [over.built]p9:
4759 // For every promoted arithmetic type T, there exist candidate
4760 // operator functions of the form
4761 //
4762 // T operator+(T);
4763 // T operator-(T);
Mike Stump1eb44332009-09-09 15:08:12 +00004764 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor74253732008-11-19 15:42:04 +00004765 Arith < LastPromotedArithmeticType; ++Arith) {
4766 QualType ArithTy = ArithmeticTypes[Arith];
4767 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4768 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004769
4770 // Extension: We also add these operators for vector types.
Douglas Gregorfec56e72010-11-03 17:00:07 +00004771 for (BuiltinCandidateTypeSet::iterator
4772 Vec = CandidateTypes[0].vector_begin(),
4773 VecEnd = CandidateTypes[0].vector_end();
Douglas Gregor26bcf672010-05-19 03:21:00 +00004774 Vec != VecEnd; ++Vec) {
4775 QualType VecTy = *Vec;
4776 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4777 }
Douglas Gregor74253732008-11-19 15:42:04 +00004778 break;
4779
4780 case OO_Tilde:
4781 // C++ [over.built]p10:
4782 // For every promoted integral type T, there exist candidate
4783 // operator functions of the form
4784 //
4785 // T operator~(T);
Mike Stump1eb44332009-09-09 15:08:12 +00004786 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor74253732008-11-19 15:42:04 +00004787 Int < LastPromotedIntegralType; ++Int) {
4788 QualType IntTy = ArithmeticTypes[Int];
4789 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4790 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004791
4792 // Extension: We also add this operator for vector types.
Douglas Gregorfec56e72010-11-03 17:00:07 +00004793 for (BuiltinCandidateTypeSet::iterator
4794 Vec = CandidateTypes[0].vector_begin(),
4795 VecEnd = CandidateTypes[0].vector_end();
Douglas Gregor26bcf672010-05-19 03:21:00 +00004796 Vec != VecEnd; ++Vec) {
4797 QualType VecTy = *Vec;
4798 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4799 }
Douglas Gregor74253732008-11-19 15:42:04 +00004800 break;
4801
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004802 case OO_New:
4803 case OO_Delete:
4804 case OO_Array_New:
4805 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004806 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00004807 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004808 break;
4809
4810 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00004811 UnaryAmp:
4812 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004813 // C++ [over.match.oper]p3:
4814 // -- For the operator ',', the unary operator '&', or the
4815 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004816 break;
4817
Douglas Gregor19b7b152009-08-24 13:43:27 +00004818 case OO_EqualEqual:
4819 case OO_ExclaimEqual:
4820 // C++ [over.match.oper]p16:
Mike Stump1eb44332009-09-09 15:08:12 +00004821 // For every pointer to member type T, there exist candidate operator
4822 // functions of the form
Douglas Gregor19b7b152009-08-24 13:43:27 +00004823 //
4824 // bool operator==(T,T);
4825 // bool operator!=(T,T);
Douglas Gregorfec56e72010-11-03 17:00:07 +00004826 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4827 for (BuiltinCandidateTypeSet::iterator
4828 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
4829 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
4830 MemPtr != MemPtrEnd;
4831 ++MemPtr) {
4832 // Don't add the same builtin candidate twice.
4833 if (!AddedTypes.insert(Context.getCanonicalType(*MemPtr)))
4834 continue;
4835
4836 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4837 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4838 }
Douglas Gregor19b7b152009-08-24 13:43:27 +00004839 }
Douglas Gregorfec56e72010-11-03 17:00:07 +00004840 AddedTypes.clear();
4841
Douglas Gregor19b7b152009-08-24 13:43:27 +00004842 // Fall through
Mike Stump1eb44332009-09-09 15:08:12 +00004843
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004844 case OO_Less:
4845 case OO_Greater:
4846 case OO_LessEqual:
4847 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004848 // C++ [over.built]p15:
4849 //
4850 // For every pointer or enumeration type T, there exist
4851 // candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004852 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004853 // bool operator<(T, T);
4854 // bool operator>(T, T);
4855 // bool operator<=(T, T);
4856 // bool operator>=(T, T);
4857 // bool operator==(T, T);
4858 // bool operator!=(T, T);
Douglas Gregorfec56e72010-11-03 17:00:07 +00004859 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4860 for (BuiltinCandidateTypeSet::iterator
4861 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
4862 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
4863 Ptr != PtrEnd; ++Ptr) {
4864 // Don't add the same builtin candidate twice.
4865 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
4866 continue;
4867
4868 QualType ParamTypes[2] = { *Ptr, *Ptr };
Douglas Gregor661b4932010-09-12 04:28:07 +00004869 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorfec56e72010-11-03 17:00:07 +00004870 }
4871 for (BuiltinCandidateTypeSet::iterator
4872 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
4873 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
4874 Enum != EnumEnd; ++Enum) {
4875 // Don't add the same builtin candidate twice.
4876 if (!AddedTypes.insert(Context.getCanonicalType(*Enum)))
4877 continue;
4878
4879 QualType ParamTypes[2] = { *Enum, *Enum };
4880 CanQualType CanonType = Context.getCanonicalType(*Enum);
4881 if (!UserDefinedBinaryOperators.count(
4882 std::make_pair(CanonType, CanonType)))
4883 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4884 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004885 }
Douglas Gregorfec56e72010-11-03 17:00:07 +00004886 AddedTypes.clear();
4887
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004888 // Fall through.
4889 isComparison = true;
4890
Douglas Gregor74253732008-11-19 15:42:04 +00004891 BinaryPlus:
4892 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004893 if (!isComparison) {
4894 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4895
4896 // C++ [over.built]p13:
4897 //
4898 // For every cv-qualified or cv-unqualified object type T
4899 // there exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004900 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004901 // T* operator+(T*, ptrdiff_t);
4902 // T& operator[](T*, ptrdiff_t); [BELOW]
4903 // T* operator-(T*, ptrdiff_t);
4904 // T* operator+(ptrdiff_t, T*);
4905 // T& operator[](ptrdiff_t, T*); [BELOW]
4906 //
4907 // C++ [over.built]p14:
4908 //
4909 // For every T, where T is a pointer to object type, there
4910 // exist candidate operator functions of the form
4911 //
4912 // ptrdiff_t operator-(T, T);
Douglas Gregorfec56e72010-11-03 17:00:07 +00004913 for (BuiltinCandidateTypeSet::iterator
4914 Ptr = CandidateTypes[0].pointer_begin(),
4915 PtrEnd = CandidateTypes[0].pointer_end();
4916 Ptr != PtrEnd; ++Ptr) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004917 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4918
4919 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4920 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4921
Douglas Gregorfec56e72010-11-03 17:00:07 +00004922 if (Op == OO_Minus) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004923 // ptrdiff_t operator-(T, T);
Douglas Gregorfec56e72010-11-03 17:00:07 +00004924 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
4925 continue;
4926
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004927 ParamTypes[1] = *Ptr;
4928 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4929 Args, 2, CandidateSet);
4930 }
4931 }
Douglas Gregorfec56e72010-11-03 17:00:07 +00004932
4933 for (BuiltinCandidateTypeSet::iterator
4934 Ptr = CandidateTypes[1].pointer_begin(),
4935 PtrEnd = CandidateTypes[1].pointer_end();
4936 Ptr != PtrEnd; ++Ptr) {
4937 if (Op == OO_Plus) {
4938 // T* operator+(ptrdiff_t, T*);
4939 QualType ParamTypes[2] = { Context.getPointerDiffType(), *Ptr };
4940 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4941 } else {
4942 // ptrdiff_t operator-(T, T);
4943 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
4944 continue;
4945
4946 QualType ParamTypes[2] = { *Ptr, *Ptr };
4947 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4948 Args, 2, CandidateSet);
4949 }
4950 }
4951
4952 AddedTypes.clear();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004953 }
4954 // Fall through
4955
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004956 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00004957 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004958 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004959 // C++ [over.built]p12:
4960 //
4961 // For every pair of promoted arithmetic types L and R, there
4962 // exist candidate operator functions of the form
4963 //
4964 // LR operator*(L, R);
4965 // LR operator/(L, R);
4966 // LR operator+(L, R);
4967 // LR operator-(L, R);
4968 // bool operator<(L, R);
4969 // bool operator>(L, R);
4970 // bool operator<=(L, R);
4971 // bool operator>=(L, R);
4972 // bool operator==(L, R);
4973 // bool operator!=(L, R);
4974 //
4975 // where LR is the result of the usual arithmetic conversions
4976 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004977 //
4978 // C++ [over.built]p24:
4979 //
4980 // For every pair of promoted arithmetic types L and R, there exist
4981 // candidate operator functions of the form
4982 //
4983 // LR operator?(bool, L, R);
4984 //
4985 // where LR is the result of the usual arithmetic conversions
4986 // between types L and R.
4987 // Our candidates ignore the first parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00004988 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004989 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004990 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004991 Right < LastPromotedArithmeticType; ++Right) {
4992 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00004993 QualType Result
4994 = isComparison
4995 ? Context.BoolTy
4996 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004997 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4998 }
4999 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00005000
5001 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5002 // conditional operator for vector types.
Douglas Gregorfec56e72010-11-03 17:00:07 +00005003 for (BuiltinCandidateTypeSet::iterator
5004 Vec1 = CandidateTypes[0].vector_begin(),
5005 Vec1End = CandidateTypes[0].vector_end();
Douglas Gregor26bcf672010-05-19 03:21:00 +00005006 Vec1 != Vec1End; ++Vec1)
5007 for (BuiltinCandidateTypeSet::iterator
Douglas Gregorfec56e72010-11-03 17:00:07 +00005008 Vec2 = CandidateTypes[1].vector_begin(),
5009 Vec2End = CandidateTypes[1].vector_end();
Douglas Gregor26bcf672010-05-19 03:21:00 +00005010 Vec2 != Vec2End; ++Vec2) {
5011 QualType LandR[2] = { *Vec1, *Vec2 };
5012 QualType Result;
5013 if (isComparison)
5014 Result = Context.BoolTy;
5015 else {
5016 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5017 Result = *Vec1;
5018 else
5019 Result = *Vec2;
5020 }
5021
5022 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5023 }
5024
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005025 break;
5026
5027 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00005028 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005029 case OO_Caret:
5030 case OO_Pipe:
5031 case OO_LessLess:
5032 case OO_GreaterGreater:
5033 // C++ [over.built]p17:
5034 //
5035 // For every pair of promoted integral types L and R, there
5036 // exist candidate operator functions of the form
5037 //
5038 // LR operator%(L, R);
5039 // LR operator&(L, R);
5040 // LR operator^(L, R);
5041 // LR operator|(L, R);
5042 // L operator<<(L, R);
5043 // L operator>>(L, R);
5044 //
5045 // where LR is the result of the usual arithmetic conversions
5046 // between types L and R.
Mike Stump1eb44332009-09-09 15:08:12 +00005047 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005048 Left < LastPromotedIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00005049 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005050 Right < LastPromotedIntegralType; ++Right) {
5051 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
5052 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5053 ? LandR[0]
Eli Friedmana95d7572009-08-19 07:44:53 +00005054 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005055 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5056 }
5057 }
5058 break;
5059
5060 case OO_Equal:
5061 // C++ [over.built]p20:
5062 //
5063 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00005064 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005065 // empty, there exist candidate operator functions of the form
5066 //
5067 // VQ T& operator=(VQ T&, T);
Douglas Gregorfec56e72010-11-03 17:00:07 +00005068 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5069 for (BuiltinCandidateTypeSet::iterator
5070 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5071 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5072 Enum != EnumEnd; ++Enum) {
5073 if (!AddedTypes.insert(Context.getCanonicalType(*Enum)))
5074 continue;
5075
5076 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
5077 CandidateSet);
5078 }
5079
5080 for (BuiltinCandidateTypeSet::iterator
5081 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5082 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5083 MemPtr != MemPtrEnd; ++MemPtr) {
5084 if (!AddedTypes.insert(Context.getCanonicalType(*MemPtr)))
5085 continue;
5086
5087 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
5088 CandidateSet);
5089 }
5090 }
5091 AddedTypes.clear();
Douglas Gregor26bcf672010-05-19 03:21:00 +00005092
5093 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005094
5095 case OO_PlusEqual:
5096 case OO_MinusEqual:
5097 // C++ [over.built]p19:
5098 //
5099 // For every pair (T, VQ), where T is any type and VQ is either
5100 // volatile or empty, there exist candidate operator functions
5101 // of the form
5102 //
5103 // T*VQ& operator=(T*VQ&, T*);
5104 //
5105 // C++ [over.built]p21:
5106 //
5107 // For every pair (T, VQ), where T is a cv-qualified or
5108 // cv-unqualified object type and VQ is either volatile or
5109 // empty, there exist candidate operator functions of the form
5110 //
5111 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5112 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
Douglas Gregorfec56e72010-11-03 17:00:07 +00005113 for (BuiltinCandidateTypeSet::iterator
5114 Ptr = CandidateTypes[0].pointer_begin(),
5115 PtrEnd = CandidateTypes[0].pointer_end();
5116 Ptr != PtrEnd; ++Ptr) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005117 QualType ParamTypes[2];
5118 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
5119
Douglas Gregorfec56e72010-11-03 17:00:07 +00005120 // If this is operator=, keep track of the builtin candidates we added.
5121 if (Op == OO_Equal)
5122 AddedTypes.insert(Context.getCanonicalType(*Ptr));
5123
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005124 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005125 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005126 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5127 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005128
Fariborz Jahanian8621d012009-10-19 21:30:45 +00005129 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5130 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00005131 // volatile version
John McCall0953e762009-09-24 19:53:00 +00005132 ParamTypes[0]
5133 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005134 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5135 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00005136 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005137 }
Douglas Gregorfec56e72010-11-03 17:00:07 +00005138
5139 if (Op == OO_Equal) {
5140 for (BuiltinCandidateTypeSet::iterator
5141 Ptr = CandidateTypes[1].pointer_begin(),
5142 PtrEnd = CandidateTypes[1].pointer_end();
5143 Ptr != PtrEnd; ++Ptr) {
5144 // Make sure we don't add the same candidate twice.
5145 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5146 continue;
5147
5148 QualType ParamTypes[2] = { Context.getLValueReferenceType(*Ptr), *Ptr };
5149
5150 // non-volatile version
5151 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5152 /*IsAssigmentOperator=*/true);
5153
5154 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5155 VisibleTypeConversionsQuals.hasVolatile()) {
5156 // volatile version
5157 ParamTypes[0]
5158 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
5159 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5160 /*IsAssigmentOperator=*/true);
5161 }
5162 }
5163 AddedTypes.clear();
5164 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005165 // Fall through.
5166
5167 case OO_StarEqual:
5168 case OO_SlashEqual:
5169 // C++ [over.built]p18:
5170 //
5171 // For every triple (L, VQ, R), where L is an arithmetic type,
5172 // VQ is either volatile or empty, and R is a promoted
5173 // arithmetic type, there exist candidate operator functions of
5174 // the form
5175 //
5176 // VQ L& operator=(VQ L&, R);
5177 // VQ L& operator*=(VQ L&, R);
5178 // VQ L& operator/=(VQ L&, R);
5179 // VQ L& operator+=(VQ L&, R);
5180 // VQ L& operator-=(VQ L&, R);
5181 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00005182 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005183 Right < LastPromotedArithmeticType; ++Right) {
5184 QualType ParamTypes[2];
5185 ParamTypes[1] = ArithmeticTypes[Right];
5186
5187 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005188 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005189 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5190 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005191
5192 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanian8621d012009-10-19 21:30:45 +00005193 if (VisibleTypeConversionsQuals.hasVolatile()) {
5194 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
5195 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5196 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5197 /*IsAssigmentOperator=*/Op == OO_Equal);
5198 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005199 }
5200 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00005201
5202 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
Douglas Gregorfec56e72010-11-03 17:00:07 +00005203 for (BuiltinCandidateTypeSet::iterator
5204 Vec1 = CandidateTypes[0].vector_begin(),
5205 Vec1End = CandidateTypes[0].vector_end();
Douglas Gregor26bcf672010-05-19 03:21:00 +00005206 Vec1 != Vec1End; ++Vec1)
5207 for (BuiltinCandidateTypeSet::iterator
Douglas Gregorfec56e72010-11-03 17:00:07 +00005208 Vec2 = CandidateTypes[1].vector_begin(),
5209 Vec2End = CandidateTypes[1].vector_end();
Douglas Gregor26bcf672010-05-19 03:21:00 +00005210 Vec2 != Vec2End; ++Vec2) {
5211 QualType ParamTypes[2];
5212 ParamTypes[1] = *Vec2;
5213 // Add this built-in operator as a candidate (VQ is empty).
5214 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
5215 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5216 /*IsAssigmentOperator=*/Op == OO_Equal);
5217
5218 // Add this built-in operator as a candidate (VQ is 'volatile').
5219 if (VisibleTypeConversionsQuals.hasVolatile()) {
5220 ParamTypes[0] = Context.getVolatileType(*Vec1);
5221 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5222 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5223 /*IsAssigmentOperator=*/Op == OO_Equal);
5224 }
5225 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005226 break;
5227
5228 case OO_PercentEqual:
5229 case OO_LessLessEqual:
5230 case OO_GreaterGreaterEqual:
5231 case OO_AmpEqual:
5232 case OO_CaretEqual:
5233 case OO_PipeEqual:
5234 // C++ [over.built]p22:
5235 //
5236 // For every triple (L, VQ, R), where L is an integral type, VQ
5237 // is either volatile or empty, and R is a promoted integral
5238 // type, there exist candidate operator functions of the form
5239 //
5240 // VQ L& operator%=(VQ L&, R);
5241 // VQ L& operator<<=(VQ L&, R);
5242 // VQ L& operator>>=(VQ L&, R);
5243 // VQ L& operator&=(VQ L&, R);
5244 // VQ L& operator^=(VQ L&, R);
5245 // VQ L& operator|=(VQ L&, R);
5246 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00005247 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005248 Right < LastPromotedIntegralType; ++Right) {
5249 QualType ParamTypes[2];
5250 ParamTypes[1] = ArithmeticTypes[Right];
5251
5252 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005253 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005254 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian035c46f2009-10-20 00:04:40 +00005255 if (VisibleTypeConversionsQuals.hasVolatile()) {
5256 // Add this built-in operator as a candidate (VQ is 'volatile').
5257 ParamTypes[0] = ArithmeticTypes[Left];
5258 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
5259 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5260 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5261 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005262 }
5263 }
5264 break;
5265
Douglas Gregor74253732008-11-19 15:42:04 +00005266 case OO_Exclaim: {
5267 // C++ [over.operator]p23:
5268 //
5269 // There also exist candidate operator functions of the form
5270 //
Mike Stump1eb44332009-09-09 15:08:12 +00005271 // bool operator!(bool);
Douglas Gregor74253732008-11-19 15:42:04 +00005272 // bool operator&&(bool, bool); [BELOW]
5273 // bool operator||(bool, bool); [BELOW]
5274 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005275 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5276 /*IsAssignmentOperator=*/false,
5277 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00005278 break;
5279 }
5280
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005281 case OO_AmpAmp:
5282 case OO_PipePipe: {
5283 // C++ [over.operator]p23:
5284 //
5285 // There also exist candidate operator functions of the form
5286 //
Douglas Gregor74253732008-11-19 15:42:04 +00005287 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005288 // bool operator&&(bool, bool);
5289 // bool operator||(bool, bool);
5290 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005291 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5292 /*IsAssignmentOperator=*/false,
5293 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005294 break;
5295 }
5296
5297 case OO_Subscript:
5298 // C++ [over.built]p13:
5299 //
5300 // For every cv-qualified or cv-unqualified object type T there
5301 // exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00005302 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005303 // T* operator+(T*, ptrdiff_t); [ABOVE]
5304 // T& operator[](T*, ptrdiff_t);
5305 // T* operator-(T*, ptrdiff_t); [ABOVE]
5306 // T* operator+(ptrdiff_t, T*); [ABOVE]
5307 // T& operator[](ptrdiff_t, T*);
Douglas Gregorfec56e72010-11-03 17:00:07 +00005308 for (BuiltinCandidateTypeSet::iterator
5309 Ptr = CandidateTypes[0].pointer_begin(),
5310 PtrEnd = CandidateTypes[0].pointer_end();
5311 Ptr != PtrEnd; ++Ptr) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005312 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Argyrios Kyrtzidis42d0f2a2010-08-23 07:12:16 +00005313 QualType PointeeType = (*Ptr)->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005314 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005315
5316 // T& operator[](T*, ptrdiff_t)
5317 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorfec56e72010-11-03 17:00:07 +00005318 }
5319
5320 for (BuiltinCandidateTypeSet::iterator
5321 Ptr = CandidateTypes[1].pointer_begin(),
5322 PtrEnd = CandidateTypes[1].pointer_end();
5323 Ptr != PtrEnd; ++Ptr) {
5324 QualType ParamTypes[2] = { Context.getPointerDiffType(), *Ptr };
5325 QualType PointeeType = (*Ptr)->getPointeeType();
5326 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
5327
5328 // T& operator[](ptrdiff_t, T*)
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005329 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorfec56e72010-11-03 17:00:07 +00005330 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005331 break;
5332
5333 case OO_ArrowStar:
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005334 // C++ [over.built]p11:
5335 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5336 // C1 is the same type as C2 or is a derived class of C2, T is an object
5337 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5338 // there exist candidate operator functions of the form
Douglas Gregorfec56e72010-11-03 17:00:07 +00005339 //
5340 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5341 //
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005342 // where CV12 is the union of CV1 and CV2.
5343 {
Douglas Gregorfec56e72010-11-03 17:00:07 +00005344 for (BuiltinCandidateTypeSet::iterator
5345 Ptr = CandidateTypes[0].pointer_begin(),
5346 PtrEnd = CandidateTypes[0].pointer_end();
5347 Ptr != PtrEnd; ++Ptr) {
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005348 QualType C1Ty = (*Ptr);
5349 QualType C1;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00005350 QualifierCollector Q1;
Argyrios Kyrtzidis42d0f2a2010-08-23 07:12:16 +00005351 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5352 if (!isa<RecordType>(C1))
5353 continue;
5354 // heuristic to reduce number of builtin candidates in the set.
5355 // Add volatile/restrict version only if there are conversions to a
5356 // volatile/restrict type.
5357 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5358 continue;
5359 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5360 continue;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005361 for (BuiltinCandidateTypeSet::iterator
Douglas Gregorfec56e72010-11-03 17:00:07 +00005362 MemPtr = CandidateTypes[1].member_pointer_begin(),
5363 MemPtrEnd = CandidateTypes[1].member_pointer_end();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005364 MemPtr != MemPtrEnd; ++MemPtr) {
5365 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5366 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian43036972009-10-07 16:56:50 +00005367 C2 = C2.getUnqualifiedType();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005368 if (C1 != C2 && !IsDerivedFrom(C1, C2))
5369 break;
5370 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5371 // build CV12 T&
5372 QualType T = mptr->getPointeeType();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005373 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5374 T.isVolatileQualified())
5375 continue;
5376 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5377 T.isRestrictQualified())
5378 continue;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00005379 T = Q1.apply(T);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005380 QualType ResultTy = Context.getLValueReferenceType(T);
5381 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5382 }
5383 }
5384 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005385 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005386
5387 case OO_Conditional:
5388 // Note that we don't consider the first argument, since it has been
5389 // contextually converted to bool long ago. The candidates below are
5390 // therefore added as binary.
5391 //
Douglas Gregor5a1f97e2010-10-15 00:50:56 +00005392 // C++ [over.built]p25:
5393 // For every type T, where T is a pointer, pointer-to-member, or scoped
5394 // enumeration type, there exist candidate operator functions of the form
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005395 //
5396 // T operator?(bool, T, T);
5397 //
Douglas Gregorfec56e72010-11-03 17:00:07 +00005398 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5399 for (BuiltinCandidateTypeSet::iterator
5400 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5401 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5402 Ptr != PtrEnd; ++Ptr) {
5403 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5404 continue;
5405
5406 QualType ParamTypes[2] = { *Ptr, *Ptr };
5407 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5408 }
5409
5410 for (BuiltinCandidateTypeSet::iterator
5411 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5412 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5413 MemPtr != MemPtrEnd; ++MemPtr) {
5414 if (!AddedTypes.insert(Context.getCanonicalType(*MemPtr)))
5415 continue;
5416
5417 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5418 AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
5419 }
5420
5421 if (getLangOptions().CPlusPlus0x) {
5422 for (BuiltinCandidateTypeSet::iterator
5423 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5424 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5425 Enum != EnumEnd; ++Enum) {
5426 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
5427 continue;
5428
5429 if (!AddedTypes.insert(Context.getCanonicalType(*Enum)))
5430 continue;
5431
5432 QualType ParamTypes[2] = { *Enum, *Enum };
5433 AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
5434 }
5435 }
Douglas Gregor5a1f97e2010-10-15 00:50:56 +00005436 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005437 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005438 }
5439}
5440
Douglas Gregorfa047642009-02-04 00:32:51 +00005441/// \brief Add function candidates found via argument-dependent lookup
5442/// to the set of overloading candidates.
5443///
5444/// This routine performs argument-dependent name lookup based on the
5445/// given function name (which may also be an operator name) and adds
5446/// all of the overload candidates found by ADL to the overload
5447/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00005448void
Douglas Gregorfa047642009-02-04 00:32:51 +00005449Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00005450 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00005451 Expr **Args, unsigned NumArgs,
John McCalld5532b62009-11-23 01:53:49 +00005452 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005453 OverloadCandidateSet& CandidateSet,
5454 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00005455 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00005456
John McCalla113e722010-01-26 06:04:06 +00005457 // FIXME: This approach for uniquing ADL results (and removing
5458 // redundant candidates from the set) relies on pointer-equality,
5459 // which means we need to key off the canonical decl. However,
5460 // always going back to the canonical decl might not get us the
5461 // right set of default arguments. What default arguments are
5462 // we supposed to consider on ADL candidates, anyway?
5463
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005464 // FIXME: Pass in the explicit template arguments?
John McCall7edb5fd2010-01-26 07:16:45 +00005465 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00005466
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005467 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005468 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5469 CandEnd = CandidateSet.end();
5470 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00005471 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00005472 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00005473 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00005474 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00005475 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005476
5477 // For each of the ADL candidates we found, add it to the overload
5478 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00005479 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00005480 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00005481 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00005482 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005483 continue;
5484
John McCall9aa472c2010-03-19 07:35:19 +00005485 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00005486 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005487 } else
John McCall6e266892010-01-26 03:27:55 +00005488 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00005489 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00005490 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00005491 }
Douglas Gregorfa047642009-02-04 00:32:51 +00005492}
5493
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005494/// isBetterOverloadCandidate - Determines whether the first overload
5495/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00005496bool
John McCall120d63c2010-08-24 20:38:10 +00005497isBetterOverloadCandidate(Sema &S,
5498 const OverloadCandidate& Cand1,
5499 const OverloadCandidate& Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005500 SourceLocation Loc,
5501 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005502 // Define viable functions to be better candidates than non-viable
5503 // functions.
5504 if (!Cand2.Viable)
5505 return Cand1.Viable;
5506 else if (!Cand1.Viable)
5507 return false;
5508
Douglas Gregor88a35142008-12-22 05:46:06 +00005509 // C++ [over.match.best]p1:
5510 //
5511 // -- if F is a static member function, ICS1(F) is defined such
5512 // that ICS1(F) is neither better nor worse than ICS1(G) for
5513 // any function G, and, symmetrically, ICS1(G) is neither
5514 // better nor worse than ICS1(F).
5515 unsigned StartArg = 0;
5516 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5517 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005518
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005519 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00005520 // A viable function F1 is defined to be a better function than another
5521 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005522 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005523 unsigned NumArgs = Cand1.Conversions.size();
5524 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5525 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005526 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00005527 switch (CompareImplicitConversionSequences(S,
5528 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005529 Cand2.Conversions[ArgIdx])) {
5530 case ImplicitConversionSequence::Better:
5531 // Cand1 has a better conversion sequence.
5532 HasBetterConversion = true;
5533 break;
5534
5535 case ImplicitConversionSequence::Worse:
5536 // Cand1 can't be better than Cand2.
5537 return false;
5538
5539 case ImplicitConversionSequence::Indistinguishable:
5540 // Do nothing.
5541 break;
5542 }
5543 }
5544
Mike Stump1eb44332009-09-09 15:08:12 +00005545 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005546 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005547 if (HasBetterConversion)
5548 return true;
5549
Mike Stump1eb44332009-09-09 15:08:12 +00005550 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005551 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00005552 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005553 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5554 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005555
5556 // -- F1 and F2 are function template specializations, and the function
5557 // template for F1 is more specialized than the template for F2
5558 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005559 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00005560 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5561 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005562 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00005563 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5564 Cand2.Function->getPrimaryTemplate(),
5565 Loc,
Douglas Gregor5d7d3752009-09-14 23:02:14 +00005566 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5567 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005568 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005569
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005570 // -- the context is an initialization by user-defined conversion
5571 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5572 // from the return type of F1 to the destination type (i.e.,
5573 // the type of the entity being initialized) is a better
5574 // conversion sequence than the standard conversion sequence
5575 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005576 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00005577 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005578 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall120d63c2010-08-24 20:38:10 +00005579 switch (CompareStandardConversionSequences(S,
5580 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005581 Cand2.FinalConversion)) {
5582 case ImplicitConversionSequence::Better:
5583 // Cand1 has a better conversion sequence.
5584 return true;
5585
5586 case ImplicitConversionSequence::Worse:
5587 // Cand1 can't be better than Cand2.
5588 return false;
5589
5590 case ImplicitConversionSequence::Indistinguishable:
5591 // Do nothing
5592 break;
5593 }
5594 }
5595
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005596 return false;
5597}
5598
Mike Stump1eb44332009-09-09 15:08:12 +00005599/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00005600/// within an overload candidate set.
5601///
5602/// \param CandidateSet the set of candidate functions.
5603///
5604/// \param Loc the location of the function name (or operator symbol) for
5605/// which overload resolution occurs.
5606///
Mike Stump1eb44332009-09-09 15:08:12 +00005607/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00005608/// function, Best points to the candidate function found.
5609///
5610/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00005611OverloadingResult
5612OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005613 iterator& Best,
5614 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005615 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00005616 Best = end();
5617 for (iterator Cand = begin(); Cand != end(); ++Cand) {
5618 if (Cand->Viable)
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005619 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
5620 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005621 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005622 }
5623
5624 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00005625 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005626 return OR_No_Viable_Function;
5627
5628 // Make sure that this function is better than every other viable
5629 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00005630 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00005631 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005632 Cand != Best &&
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005633 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
5634 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00005635 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005636 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005637 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005638 }
Mike Stump1eb44332009-09-09 15:08:12 +00005639
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005640 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005641 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00005642 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005643 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005644 return OR_Deleted;
5645
Douglas Gregore0762c92009-06-19 23:52:42 +00005646 // C++ [basic.def.odr]p2:
5647 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00005648 // when referred to from a potentially-evaluated expression. [Note: this
5649 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00005650 // (clause 13), user-defined conversions (12.3.2), allocation function for
5651 // placement new (5.3.4), as well as non-default initialization (8.5).
5652 if (Best->Function)
John McCall120d63c2010-08-24 20:38:10 +00005653 S.MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor9b623632010-10-12 23:32:35 +00005654
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005655 return OR_Success;
5656}
5657
John McCall3c80f572010-01-12 02:15:36 +00005658namespace {
5659
5660enum OverloadCandidateKind {
5661 oc_function,
5662 oc_method,
5663 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00005664 oc_function_template,
5665 oc_method_template,
5666 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00005667 oc_implicit_default_constructor,
5668 oc_implicit_copy_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00005669 oc_implicit_copy_assignment
John McCall3c80f572010-01-12 02:15:36 +00005670};
5671
John McCall220ccbf2010-01-13 00:25:19 +00005672OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5673 FunctionDecl *Fn,
5674 std::string &Description) {
5675 bool isTemplate = false;
5676
5677 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5678 isTemplate = true;
5679 Description = S.getTemplateArgumentBindingsText(
5680 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5681 }
John McCallb1622a12010-01-06 09:43:14 +00005682
5683 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00005684 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00005685 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00005686
John McCall3c80f572010-01-12 02:15:36 +00005687 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5688 : oc_implicit_default_constructor;
John McCallb1622a12010-01-06 09:43:14 +00005689 }
5690
5691 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5692 // This actually gets spelled 'candidate function' for now, but
5693 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00005694 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00005695 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00005696
Douglas Gregor3e9438b2010-09-27 22:37:28 +00005697 assert(Meth->isCopyAssignmentOperator()
John McCallb1622a12010-01-06 09:43:14 +00005698 && "implicit method is not copy assignment operator?");
John McCall3c80f572010-01-12 02:15:36 +00005699 return oc_implicit_copy_assignment;
5700 }
5701
John McCall220ccbf2010-01-13 00:25:19 +00005702 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00005703}
5704
5705} // end anonymous namespace
5706
5707// Notes the location of an overload candidate.
5708void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCall220ccbf2010-01-13 00:25:19 +00005709 std::string FnDesc;
5710 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5711 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5712 << (unsigned) K << FnDesc;
John McCallb1622a12010-01-06 09:43:14 +00005713}
5714
John McCall1d318332010-01-12 00:44:57 +00005715/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5716/// "lead" diagnostic; it will be given two arguments, the source and
5717/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00005718void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
5719 Sema &S,
5720 SourceLocation CaretLoc,
5721 const PartialDiagnostic &PDiag) const {
5722 S.Diag(CaretLoc, PDiag)
5723 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall1d318332010-01-12 00:44:57 +00005724 for (AmbiguousConversionSequence::const_iterator
John McCall120d63c2010-08-24 20:38:10 +00005725 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
5726 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00005727 }
John McCall81201622010-01-08 04:41:39 +00005728}
5729
John McCall1d318332010-01-12 00:44:57 +00005730namespace {
5731
John McCalladbb8f82010-01-13 09:16:55 +00005732void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5733 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5734 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00005735 assert(Cand->Function && "for now, candidate must be a function");
5736 FunctionDecl *Fn = Cand->Function;
5737
5738 // There's a conversion slot for the object argument if this is a
5739 // non-constructor method. Note that 'I' corresponds the
5740 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00005741 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00005742 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00005743 if (I == 0)
5744 isObjectArgument = true;
5745 else
5746 I--;
John McCall220ccbf2010-01-13 00:25:19 +00005747 }
5748
John McCall220ccbf2010-01-13 00:25:19 +00005749 std::string FnDesc;
5750 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5751
John McCalladbb8f82010-01-13 09:16:55 +00005752 Expr *FromExpr = Conv.Bad.FromExpr;
5753 QualType FromTy = Conv.Bad.getFromType();
5754 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00005755
John McCall5920dbb2010-02-02 02:42:52 +00005756 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00005757 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00005758 Expr *E = FromExpr->IgnoreParens();
5759 if (isa<UnaryOperator>(E))
5760 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00005761 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00005762
5763 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5764 << (unsigned) FnKind << FnDesc
5765 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5766 << ToTy << Name << I+1;
5767 return;
5768 }
5769
John McCall258b2032010-01-23 08:10:49 +00005770 // Do some hand-waving analysis to see if the non-viability is due
5771 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00005772 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5773 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5774 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5775 CToTy = RT->getPointeeType();
5776 else {
5777 // TODO: detect and diagnose the full richness of const mismatches.
5778 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5779 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5780 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5781 }
5782
5783 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5784 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5785 // It is dumb that we have to do this here.
5786 while (isa<ArrayType>(CFromTy))
5787 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5788 while (isa<ArrayType>(CToTy))
5789 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5790
5791 Qualifiers FromQs = CFromTy.getQualifiers();
5792 Qualifiers ToQs = CToTy.getQualifiers();
5793
5794 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5795 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5796 << (unsigned) FnKind << FnDesc
5797 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5798 << FromTy
5799 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5800 << (unsigned) isObjectArgument << I+1;
5801 return;
5802 }
5803
5804 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5805 assert(CVR && "unexpected qualifiers mismatch");
5806
5807 if (isObjectArgument) {
5808 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5809 << (unsigned) FnKind << FnDesc
5810 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5811 << FromTy << (CVR - 1);
5812 } else {
5813 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5814 << (unsigned) FnKind << FnDesc
5815 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5816 << FromTy << (CVR - 1) << I+1;
5817 }
5818 return;
5819 }
5820
John McCall258b2032010-01-23 08:10:49 +00005821 // Diagnose references or pointers to incomplete types differently,
5822 // since it's far from impossible that the incompleteness triggered
5823 // the failure.
5824 QualType TempFromTy = FromTy.getNonReferenceType();
5825 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5826 TempFromTy = PTy->getPointeeType();
5827 if (TempFromTy->isIncompleteType()) {
5828 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5829 << (unsigned) FnKind << FnDesc
5830 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5831 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5832 return;
5833 }
5834
Douglas Gregor85789812010-06-30 23:01:39 +00005835 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005836 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00005837 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
5838 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
5839 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5840 FromPtrTy->getPointeeType()) &&
5841 !FromPtrTy->getPointeeType()->isIncompleteType() &&
5842 !ToPtrTy->getPointeeType()->isIncompleteType() &&
5843 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
5844 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005845 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00005846 }
5847 } else if (const ObjCObjectPointerType *FromPtrTy
5848 = FromTy->getAs<ObjCObjectPointerType>()) {
5849 if (const ObjCObjectPointerType *ToPtrTy
5850 = ToTy->getAs<ObjCObjectPointerType>())
5851 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
5852 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
5853 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5854 FromPtrTy->getPointeeType()) &&
5855 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005856 BaseToDerivedConversion = 2;
5857 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
5858 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
5859 !FromTy->isIncompleteType() &&
5860 !ToRefTy->getPointeeType()->isIncompleteType() &&
5861 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
5862 BaseToDerivedConversion = 3;
5863 }
5864
5865 if (BaseToDerivedConversion) {
Douglas Gregor85789812010-06-30 23:01:39 +00005866 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005867 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00005868 << (unsigned) FnKind << FnDesc
5869 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005870 << (BaseToDerivedConversion - 1)
Douglas Gregor85789812010-06-30 23:01:39 +00005871 << FromTy << ToTy << I+1;
5872 return;
5873 }
5874
John McCall651f3ee2010-01-14 03:28:57 +00005875 // TODO: specialize more based on the kind of mismatch
John McCall220ccbf2010-01-13 00:25:19 +00005876 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5877 << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00005878 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalle81e15e2010-01-14 00:56:20 +00005879 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCalladbb8f82010-01-13 09:16:55 +00005880}
5881
5882void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5883 unsigned NumFormalArgs) {
5884 // TODO: treat calls to a missing default constructor as a special case
5885
5886 FunctionDecl *Fn = Cand->Function;
5887 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5888
5889 unsigned MinParams = Fn->getMinRequiredArguments();
5890
5891 // at least / at most / exactly
Douglas Gregora18592e2010-05-08 18:13:28 +00005892 // FIXME: variadic templates "at most" should account for parameter packs
John McCalladbb8f82010-01-13 09:16:55 +00005893 unsigned mode, modeCount;
5894 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00005895 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5896 (Cand->FailureKind == ovl_fail_bad_deduction &&
5897 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCalladbb8f82010-01-13 09:16:55 +00005898 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5899 mode = 0; // "at least"
5900 else
5901 mode = 2; // "exactly"
5902 modeCount = MinParams;
5903 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00005904 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5905 (Cand->FailureKind == ovl_fail_bad_deduction &&
5906 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00005907 if (MinParams != FnTy->getNumArgs())
5908 mode = 1; // "at most"
5909 else
5910 mode = 2; // "exactly"
5911 modeCount = FnTy->getNumArgs();
5912 }
5913
5914 std::string Description;
5915 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5916
5917 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregora18592e2010-05-08 18:13:28 +00005918 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5919 << modeCount << NumFormalArgs;
John McCall220ccbf2010-01-13 00:25:19 +00005920}
5921
John McCall342fec42010-02-01 18:53:26 +00005922/// Diagnose a failed template-argument deduction.
5923void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5924 Expr **Args, unsigned NumArgs) {
5925 FunctionDecl *Fn = Cand->Function; // pattern
5926
Douglas Gregora9333192010-05-08 17:41:32 +00005927 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00005928 NamedDecl *ParamD;
5929 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5930 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5931 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00005932 switch (Cand->DeductionFailure.Result) {
5933 case Sema::TDK_Success:
5934 llvm_unreachable("TDK_success while diagnosing bad deduction");
5935
5936 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00005937 assert(ParamD && "no parameter found for incomplete deduction result");
5938 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5939 << ParamD->getDeclName();
5940 return;
5941 }
5942
John McCall57e97782010-08-05 09:05:08 +00005943 case Sema::TDK_Underqualified: {
5944 assert(ParamD && "no parameter found for bad qualifiers deduction result");
5945 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
5946
5947 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
5948
5949 // Param will have been canonicalized, but it should just be a
5950 // qualified version of ParamD, so move the qualifiers to that.
5951 QualifierCollector Qs(S.Context);
5952 Qs.strip(Param);
5953 QualType NonCanonParam = Qs.apply(TParam->getTypeForDecl());
5954 assert(S.Context.hasSameType(Param, NonCanonParam));
5955
5956 // Arg has also been canonicalized, but there's nothing we can do
5957 // about that. It also doesn't matter as much, because it won't
5958 // have any template parameters in it (because deduction isn't
5959 // done on dependent types).
5960 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
5961
5962 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
5963 << ParamD->getDeclName() << Arg << NonCanonParam;
5964 return;
5965 }
5966
5967 case Sema::TDK_Inconsistent: {
Douglas Gregorf1a84452010-05-08 19:15:54 +00005968 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00005969 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00005970 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00005971 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00005972 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00005973 which = 1;
5974 else {
Douglas Gregora9333192010-05-08 17:41:32 +00005975 which = 2;
5976 }
5977
5978 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5979 << which << ParamD->getDeclName()
5980 << *Cand->DeductionFailure.getFirstArg()
5981 << *Cand->DeductionFailure.getSecondArg();
5982 return;
5983 }
Douglas Gregora18592e2010-05-08 18:13:28 +00005984
Douglas Gregorf1a84452010-05-08 19:15:54 +00005985 case Sema::TDK_InvalidExplicitArguments:
5986 assert(ParamD && "no parameter found for invalid explicit arguments");
5987 if (ParamD->getDeclName())
5988 S.Diag(Fn->getLocation(),
5989 diag::note_ovl_candidate_explicit_arg_mismatch_named)
5990 << ParamD->getDeclName();
5991 else {
5992 int index = 0;
5993 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5994 index = TTP->getIndex();
5995 else if (NonTypeTemplateParmDecl *NTTP
5996 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5997 index = NTTP->getIndex();
5998 else
5999 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
6000 S.Diag(Fn->getLocation(),
6001 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
6002 << (index + 1);
6003 }
6004 return;
6005
Douglas Gregora18592e2010-05-08 18:13:28 +00006006 case Sema::TDK_TooManyArguments:
6007 case Sema::TDK_TooFewArguments:
6008 DiagnoseArityMismatch(S, Cand, NumArgs);
6009 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00006010
6011 case Sema::TDK_InstantiationDepth:
6012 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
6013 return;
6014
6015 case Sema::TDK_SubstitutionFailure: {
6016 std::string ArgString;
6017 if (TemplateArgumentList *Args
6018 = Cand->DeductionFailure.getTemplateArgumentList())
6019 ArgString = S.getTemplateArgumentBindingsText(
6020 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
6021 *Args);
6022 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
6023 << ArgString;
6024 return;
6025 }
Douglas Gregora9333192010-05-08 17:41:32 +00006026
John McCall342fec42010-02-01 18:53:26 +00006027 // TODO: diagnose these individually, then kill off
6028 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00006029 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00006030 case Sema::TDK_FailedOverloadResolution:
6031 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
6032 return;
6033 }
6034}
6035
6036/// Generates a 'note' diagnostic for an overload candidate. We've
6037/// already generated a primary error at the call site.
6038///
6039/// It really does need to be a single diagnostic with its caret
6040/// pointed at the candidate declaration. Yes, this creates some
6041/// major challenges of technical writing. Yes, this makes pointing
6042/// out problems with specific arguments quite awkward. It's still
6043/// better than generating twenty screens of text for every failed
6044/// overload.
6045///
6046/// It would be great to be able to express per-candidate problems
6047/// more richly for those diagnostic clients that cared, but we'd
6048/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00006049void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
6050 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00006051 FunctionDecl *Fn = Cand->Function;
6052
John McCall81201622010-01-08 04:41:39 +00006053 // Note deleted candidates, but only if they're viable.
John McCall3c80f572010-01-12 02:15:36 +00006054 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCall220ccbf2010-01-13 00:25:19 +00006055 std::string FnDesc;
6056 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00006057
6058 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00006059 << FnKind << FnDesc << Fn->isDeleted();
John McCalla1d7d622010-01-08 00:58:21 +00006060 return;
John McCall81201622010-01-08 04:41:39 +00006061 }
6062
John McCall220ccbf2010-01-13 00:25:19 +00006063 // We don't really have anything else to say about viable candidates.
6064 if (Cand->Viable) {
6065 S.NoteOverloadCandidate(Fn);
6066 return;
6067 }
John McCall1d318332010-01-12 00:44:57 +00006068
John McCalladbb8f82010-01-13 09:16:55 +00006069 switch (Cand->FailureKind) {
6070 case ovl_fail_too_many_arguments:
6071 case ovl_fail_too_few_arguments:
6072 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00006073
John McCalladbb8f82010-01-13 09:16:55 +00006074 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00006075 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
6076
John McCall717e8912010-01-23 05:17:32 +00006077 case ovl_fail_trivial_conversion:
6078 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00006079 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00006080 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00006081
John McCallb1bdc622010-02-25 01:37:24 +00006082 case ovl_fail_bad_conversion: {
6083 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
6084 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00006085 if (Cand->Conversions[I].isBad())
6086 return DiagnoseBadConversion(S, Cand, I);
6087
6088 // FIXME: this currently happens when we're called from SemaInit
6089 // when user-conversion overload fails. Figure out how to handle
6090 // those conditions and diagnose them well.
6091 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00006092 }
John McCallb1bdc622010-02-25 01:37:24 +00006093 }
John McCalla1d7d622010-01-08 00:58:21 +00006094}
6095
6096void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
6097 // Desugar the type of the surrogate down to a function type,
6098 // retaining as many typedefs as possible while still showing
6099 // the function type (and, therefore, its parameter types).
6100 QualType FnType = Cand->Surrogate->getConversionType();
6101 bool isLValueReference = false;
6102 bool isRValueReference = false;
6103 bool isPointer = false;
6104 if (const LValueReferenceType *FnTypeRef =
6105 FnType->getAs<LValueReferenceType>()) {
6106 FnType = FnTypeRef->getPointeeType();
6107 isLValueReference = true;
6108 } else if (const RValueReferenceType *FnTypeRef =
6109 FnType->getAs<RValueReferenceType>()) {
6110 FnType = FnTypeRef->getPointeeType();
6111 isRValueReference = true;
6112 }
6113 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
6114 FnType = FnTypePtr->getPointeeType();
6115 isPointer = true;
6116 }
6117 // Desugar down to a function type.
6118 FnType = QualType(FnType->getAs<FunctionType>(), 0);
6119 // Reconstruct the pointer/reference as appropriate.
6120 if (isPointer) FnType = S.Context.getPointerType(FnType);
6121 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
6122 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
6123
6124 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
6125 << FnType;
6126}
6127
6128void NoteBuiltinOperatorCandidate(Sema &S,
6129 const char *Opc,
6130 SourceLocation OpLoc,
6131 OverloadCandidate *Cand) {
6132 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
6133 std::string TypeStr("operator");
6134 TypeStr += Opc;
6135 TypeStr += "(";
6136 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6137 if (Cand->Conversions.size() == 1) {
6138 TypeStr += ")";
6139 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6140 } else {
6141 TypeStr += ", ";
6142 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6143 TypeStr += ")";
6144 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
6145 }
6146}
6147
6148void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
6149 OverloadCandidate *Cand) {
6150 unsigned NoOperands = Cand->Conversions.size();
6151 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
6152 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00006153 if (ICS.isBad()) break; // all meaningless after first invalid
6154 if (!ICS.isAmbiguous()) continue;
6155
John McCall120d63c2010-08-24 20:38:10 +00006156 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006157 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00006158 }
6159}
6160
John McCall1b77e732010-01-15 23:32:50 +00006161SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
6162 if (Cand->Function)
6163 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00006164 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00006165 return Cand->Surrogate->getLocation();
6166 return SourceLocation();
6167}
6168
John McCallbf65c0b2010-01-12 00:48:53 +00006169struct CompareOverloadCandidatesForDisplay {
6170 Sema &S;
6171 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00006172
6173 bool operator()(const OverloadCandidate *L,
6174 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00006175 // Fast-path this check.
6176 if (L == R) return false;
6177
John McCall81201622010-01-08 04:41:39 +00006178 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00006179 if (L->Viable) {
6180 if (!R->Viable) return true;
6181
6182 // TODO: introduce a tri-valued comparison for overload
6183 // candidates. Would be more worthwhile if we had a sort
6184 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00006185 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6186 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00006187 } else if (R->Viable)
6188 return false;
John McCall81201622010-01-08 04:41:39 +00006189
John McCall1b77e732010-01-15 23:32:50 +00006190 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00006191
John McCall1b77e732010-01-15 23:32:50 +00006192 // Criteria by which we can sort non-viable candidates:
6193 if (!L->Viable) {
6194 // 1. Arity mismatches come after other candidates.
6195 if (L->FailureKind == ovl_fail_too_many_arguments ||
6196 L->FailureKind == ovl_fail_too_few_arguments)
6197 return false;
6198 if (R->FailureKind == ovl_fail_too_many_arguments ||
6199 R->FailureKind == ovl_fail_too_few_arguments)
6200 return true;
John McCall81201622010-01-08 04:41:39 +00006201
John McCall717e8912010-01-23 05:17:32 +00006202 // 2. Bad conversions come first and are ordered by the number
6203 // of bad conversions and quality of good conversions.
6204 if (L->FailureKind == ovl_fail_bad_conversion) {
6205 if (R->FailureKind != ovl_fail_bad_conversion)
6206 return true;
6207
6208 // If there's any ordering between the defined conversions...
6209 // FIXME: this might not be transitive.
6210 assert(L->Conversions.size() == R->Conversions.size());
6211
6212 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00006213 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6214 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00006215 switch (CompareImplicitConversionSequences(S,
6216 L->Conversions[I],
6217 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00006218 case ImplicitConversionSequence::Better:
6219 leftBetter++;
6220 break;
6221
6222 case ImplicitConversionSequence::Worse:
6223 leftBetter--;
6224 break;
6225
6226 case ImplicitConversionSequence::Indistinguishable:
6227 break;
6228 }
6229 }
6230 if (leftBetter > 0) return true;
6231 if (leftBetter < 0) return false;
6232
6233 } else if (R->FailureKind == ovl_fail_bad_conversion)
6234 return false;
6235
John McCall1b77e732010-01-15 23:32:50 +00006236 // TODO: others?
6237 }
6238
6239 // Sort everything else by location.
6240 SourceLocation LLoc = GetLocationForCandidate(L);
6241 SourceLocation RLoc = GetLocationForCandidate(R);
6242
6243 // Put candidates without locations (e.g. builtins) at the end.
6244 if (LLoc.isInvalid()) return false;
6245 if (RLoc.isInvalid()) return true;
6246
6247 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00006248 }
6249};
6250
John McCall717e8912010-01-23 05:17:32 +00006251/// CompleteNonViableCandidate - Normally, overload resolution only
6252/// computes up to the first
6253void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6254 Expr **Args, unsigned NumArgs) {
6255 assert(!Cand->Viable);
6256
6257 // Don't do anything on failures other than bad conversion.
6258 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6259
6260 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00006261 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCall717e8912010-01-23 05:17:32 +00006262 unsigned ConvCount = Cand->Conversions.size();
6263 while (true) {
6264 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6265 ConvIdx++;
6266 if (Cand->Conversions[ConvIdx - 1].isBad())
6267 break;
6268 }
6269
6270 if (ConvIdx == ConvCount)
6271 return;
6272
John McCallb1bdc622010-02-25 01:37:24 +00006273 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6274 "remaining conversion is initialized?");
6275
Douglas Gregor23ef6c02010-04-16 17:45:54 +00006276 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00006277 // operation somehow.
6278 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00006279
6280 const FunctionProtoType* Proto;
6281 unsigned ArgIdx = ConvIdx;
6282
6283 if (Cand->IsSurrogate) {
6284 QualType ConvType
6285 = Cand->Surrogate->getConversionType().getNonReferenceType();
6286 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6287 ConvType = ConvPtrType->getPointeeType();
6288 Proto = ConvType->getAs<FunctionProtoType>();
6289 ArgIdx--;
6290 } else if (Cand->Function) {
6291 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6292 if (isa<CXXMethodDecl>(Cand->Function) &&
6293 !isa<CXXConstructorDecl>(Cand->Function))
6294 ArgIdx--;
6295 } else {
6296 // Builtin binary operator with a bad first conversion.
6297 assert(ConvCount <= 3);
6298 for (; ConvIdx != ConvCount; ++ConvIdx)
6299 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006300 = TryCopyInitialization(S, Args[ConvIdx],
6301 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6302 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00006303 /*InOverloadResolution*/ true);
John McCall717e8912010-01-23 05:17:32 +00006304 return;
6305 }
6306
6307 // Fill in the rest of the conversions.
6308 unsigned NumArgsInProto = Proto->getNumArgs();
6309 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6310 if (ArgIdx < NumArgsInProto)
6311 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006312 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6313 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00006314 /*InOverloadResolution=*/true);
John McCall717e8912010-01-23 05:17:32 +00006315 else
6316 Cand->Conversions[ConvIdx].setEllipsis();
6317 }
6318}
6319
John McCalla1d7d622010-01-08 00:58:21 +00006320} // end anonymous namespace
6321
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006322/// PrintOverloadCandidates - When overload resolution fails, prints
6323/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00006324/// set.
John McCall120d63c2010-08-24 20:38:10 +00006325void OverloadCandidateSet::NoteCandidates(Sema &S,
6326 OverloadCandidateDisplayKind OCD,
6327 Expr **Args, unsigned NumArgs,
6328 const char *Opc,
6329 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00006330 // Sort the candidates by viability and position. Sorting directly would
6331 // be prohibitive, so we make a set of pointers and sort those.
6332 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00006333 if (OCD == OCD_AllCandidates) Cands.reserve(size());
6334 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00006335 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00006336 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00006337 else if (OCD == OCD_AllCandidates) {
John McCall120d63c2010-08-24 20:38:10 +00006338 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006339 if (Cand->Function || Cand->IsSurrogate)
6340 Cands.push_back(Cand);
6341 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6342 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00006343 }
6344 }
6345
John McCallbf65c0b2010-01-12 00:48:53 +00006346 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00006347 CompareOverloadCandidatesForDisplay(S));
John McCall81201622010-01-08 04:41:39 +00006348
John McCall1d318332010-01-12 00:44:57 +00006349 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00006350
John McCall81201622010-01-08 04:41:39 +00006351 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall120d63c2010-08-24 20:38:10 +00006352 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006353 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00006354 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6355 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00006356
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006357 // Set an arbitrary limit on the number of candidate functions we'll spam
6358 // the user with. FIXME: This limit should depend on details of the
6359 // candidate list.
6360 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6361 break;
6362 }
6363 ++CandsShown;
6364
John McCalla1d7d622010-01-08 00:58:21 +00006365 if (Cand->Function)
John McCall120d63c2010-08-24 20:38:10 +00006366 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00006367 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00006368 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006369 else {
6370 assert(Cand->Viable &&
6371 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00006372 // Generally we only see ambiguities including viable builtin
6373 // operators if overload resolution got screwed up by an
6374 // ambiguous user-defined conversion.
6375 //
6376 // FIXME: It's quite possible for different conversions to see
6377 // different ambiguities, though.
6378 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00006379 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00006380 ReportedAmbiguousConversions = true;
6381 }
John McCalla1d7d622010-01-08 00:58:21 +00006382
John McCall1d318332010-01-12 00:44:57 +00006383 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00006384 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006385 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006386 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006387
6388 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00006389 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006390}
6391
John McCall9aa472c2010-03-19 07:35:19 +00006392static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCallc373d482010-01-27 01:50:18 +00006393 if (isa<UnresolvedLookupExpr>(E))
John McCall9aa472c2010-03-19 07:35:19 +00006394 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00006395
John McCall9aa472c2010-03-19 07:35:19 +00006396 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00006397}
6398
Douglas Gregor904eed32008-11-10 20:40:00 +00006399/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6400/// an overloaded function (C++ [over.over]), where @p From is an
6401/// expression with overloaded function type and @p ToType is the type
6402/// we're trying to resolve to. For example:
6403///
6404/// @code
6405/// int f(double);
6406/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00006407///
Douglas Gregor904eed32008-11-10 20:40:00 +00006408/// int (*pfd)(double) = f; // selects f(double)
6409/// @endcode
6410///
6411/// This routine returns the resulting FunctionDecl if it could be
6412/// resolved, and NULL otherwise. When @p Complain is true, this
6413/// routine will emit diagnostics if there is an error.
6414FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00006415Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall6bb80172010-03-30 21:47:33 +00006416 bool Complain,
6417 DeclAccessPair &FoundResult) {
Douglas Gregor904eed32008-11-10 20:40:00 +00006418 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00006419 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00006420 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00006421 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00006422 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00006423 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00006424 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00006425 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00006426 FunctionType = MemTypePtr->getPointeeType();
6427 IsMember = true;
6428 }
Douglas Gregor904eed32008-11-10 20:40:00 +00006429
Douglas Gregor904eed32008-11-10 20:40:00 +00006430 // C++ [over.over]p1:
6431 // [...] [Note: any redundant set of parentheses surrounding the
6432 // overloaded function name is ignored (5.1). ]
Douglas Gregor904eed32008-11-10 20:40:00 +00006433 // C++ [over.over]p1:
6434 // [...] The overloaded function name can be preceded by the &
6435 // operator.
John McCallc988fab2010-08-24 23:26:21 +00006436 // However, remember whether the expression has member-pointer form:
6437 // C++ [expr.unary.op]p4:
6438 // A pointer to member is only formed when an explicit & is used
6439 // and its operand is a qualified-id not enclosed in
6440 // parentheses.
John McCall9c72c602010-08-27 09:08:28 +00006441 OverloadExpr::FindResult Ovl = OverloadExpr::find(From);
6442 OverloadExpr *OvlExpr = Ovl.Expression;
John McCallc988fab2010-08-24 23:26:21 +00006443
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006444 // We expect a pointer or reference to function, or a function pointer.
6445 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6446 if (!FunctionType->isFunctionType()) {
6447 if (Complain)
6448 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6449 << OvlExpr->getName() << ToType;
6450
6451 return 0;
6452 }
6453
John McCallfb97e752010-08-24 22:52:39 +00006454 // If the overload expression doesn't have the form of a pointer to
John McCallc988fab2010-08-24 23:26:21 +00006455 // member, don't try to convert it to a pointer-to-member type.
John McCall9c72c602010-08-27 09:08:28 +00006456 if (IsMember && !Ovl.HasFormOfMemberPointer) {
John McCallfb97e752010-08-24 22:52:39 +00006457 if (!Complain) return 0;
6458
6459 // TODO: Should we condition this on whether any functions might
6460 // have matched, or is it more appropriate to do that in callers?
6461 // TODO: a fixit wouldn't hurt.
6462 Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
6463 << ToType << OvlExpr->getSourceRange();
6464 return 0;
6465 }
6466
6467 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6468 if (OvlExpr->hasExplicitTemplateArgs()) {
6469 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6470 ExplicitTemplateArgs = &ETABuffer;
6471 }
6472
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006473 assert(From->getType() == Context.OverloadTy);
Douglas Gregor904eed32008-11-10 20:40:00 +00006474
Douglas Gregor904eed32008-11-10 20:40:00 +00006475 // Look through all of the overloaded functions, searching for one
6476 // whose type matches exactly.
John McCall9aa472c2010-03-19 07:35:19 +00006477 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb7a09262010-04-01 18:32:35 +00006478 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
Douglas Gregor9b623632010-10-12 23:32:35 +00006479
Douglas Gregor00aeb522009-07-08 23:33:52 +00006480 bool FoundNonTemplateFunction = false;
John McCall7bb12da2010-02-02 06:20:04 +00006481 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6482 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00006483 // Look through any using declarations to find the underlying function.
6484 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6485
Douglas Gregor904eed32008-11-10 20:40:00 +00006486 // C++ [over.over]p3:
6487 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00006488 // targets of type "pointer-to-function" or "reference-to-function."
6489 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00006490 // type "pointer-to-member-function."
6491 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00006492
Mike Stump1eb44332009-09-09 15:08:12 +00006493 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthbd647292009-12-29 06:17:27 +00006494 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006495 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00006496 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00006497 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00006498 // static when converting to member pointer.
6499 if (Method->isStatic() == IsMember)
6500 continue;
6501 } else if (IsMember)
6502 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00006503
Douglas Gregor00aeb522009-07-08 23:33:52 +00006504 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00006505 // If the name is a function template, template argument deduction is
6506 // done (14.8.2.2), and if the argument deduction succeeds, the
6507 // resulting template argument list is used to generate a single
6508 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00006509 // overloaded functions considered.
Douglas Gregor83314aa2009-07-08 20:55:45 +00006510 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00006511 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor83314aa2009-07-08 20:55:45 +00006512 if (TemplateDeductionResult Result
John McCall7bb12da2010-02-02 06:20:04 +00006513 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00006514 FunctionType, Specialization, Info)) {
6515 // FIXME: make a note of the failed deduction for diagnostics.
6516 (void)Result;
6517 } else {
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00006518 // Template argument deduction ensures that we have an exact match.
6519 // This function template specicalization works.
Douglas Gregor9b623632010-10-12 23:32:35 +00006520 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006521 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00006522 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor9b623632010-10-12 23:32:35 +00006523 Matches.push_back(std::make_pair(I.getPair(), Specialization));
Douglas Gregor83314aa2009-07-08 20:55:45 +00006524 }
John McCallba135432009-11-21 08:51:07 +00006525
6526 continue;
Douglas Gregor83314aa2009-07-08 20:55:45 +00006527 }
Mike Stump1eb44332009-09-09 15:08:12 +00006528
Chandler Carruthbd647292009-12-29 06:17:27 +00006529 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00006530 // Skip non-static functions when converting to pointer, and static
6531 // when converting to member pointer.
6532 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00006533 continue;
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006534
6535 // If we have explicit template arguments, skip non-templates.
John McCall7bb12da2010-02-02 06:20:04 +00006536 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006537 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00006538 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00006539 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00006540
Chandler Carruthbd647292009-12-29 06:17:27 +00006541 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00006542 QualType ResultTy;
6543 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6544 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6545 ResultTy)) {
John McCall9aa472c2010-03-19 07:35:19 +00006546 Matches.push_back(std::make_pair(I.getPair(),
6547 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00006548 FoundNonTemplateFunction = true;
6549 }
Mike Stump1eb44332009-09-09 15:08:12 +00006550 }
Douglas Gregor904eed32008-11-10 20:40:00 +00006551 }
6552
Douglas Gregor00aeb522009-07-08 23:33:52 +00006553 // If there were 0 or 1 matches, we're done.
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006554 if (Matches.empty()) {
6555 if (Complain) {
6556 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6557 << OvlExpr->getName() << FunctionType;
6558 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6559 E = OvlExpr->decls_end();
6560 I != E; ++I)
6561 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6562 NoteOverloadCandidate(F);
6563 }
6564
Douglas Gregor00aeb522009-07-08 23:33:52 +00006565 return 0;
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006566 } else if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00006567 FunctionDecl *Result = Matches[0].second;
Douglas Gregor9b623632010-10-12 23:32:35 +00006568 FoundResult = Matches[0].first;
Sebastian Redl07ab2022009-10-17 21:12:09 +00006569 MarkDeclarationReferenced(From->getLocStart(), Result);
Douglas Gregor9b623632010-10-12 23:32:35 +00006570 if (Complain) {
John McCall6bb80172010-03-30 21:47:33 +00006571 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Douglas Gregor9b623632010-10-12 23:32:35 +00006572 }
Sebastian Redl07ab2022009-10-17 21:12:09 +00006573 return Result;
6574 }
Douglas Gregor00aeb522009-07-08 23:33:52 +00006575
6576 // C++ [over.over]p4:
6577 // If more than one function is selected, [...]
Douglas Gregor312a2022009-09-26 03:56:17 +00006578 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006579 // [...] and any given function template specialization F1 is
6580 // eliminated if the set contains a second function template
6581 // specialization whose function template is more specialized
6582 // than the function template of F1 according to the partial
6583 // ordering rules of 14.5.5.2.
6584
6585 // The algorithm specified above is quadratic. We instead use a
6586 // two-pass algorithm (similar to the one used to identify the
6587 // best viable function in an overload set) that identifies the
6588 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00006589
6590 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6591 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6592 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCallc373d482010-01-27 01:50:18 +00006593
6594 UnresolvedSetIterator Result =
John McCall9aa472c2010-03-19 07:35:19 +00006595 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redl07ab2022009-10-17 21:12:09 +00006596 TPOC_Other, From->getLocStart(),
6597 PDiag(),
6598 PDiag(diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00006599 << Matches[0].second->getDeclName(),
John McCall220ccbf2010-01-13 00:25:19 +00006600 PDiag(diag::note_ovl_candidate)
6601 << (unsigned) oc_function_template);
Douglas Gregor78c057e2010-09-12 08:16:09 +00006602 if (Result == MatchesCopy.end())
6603 return 0;
6604
John McCallc373d482010-01-27 01:50:18 +00006605 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall6bb80172010-03-30 21:47:33 +00006606 FoundResult = Matches[Result - MatchesCopy.begin()].first;
Douglas Gregor9b623632010-10-12 23:32:35 +00006607 if (Complain)
John McCall6bb80172010-03-30 21:47:33 +00006608 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCallc373d482010-01-27 01:50:18 +00006609 return cast<FunctionDecl>(*Result);
Douglas Gregor00aeb522009-07-08 23:33:52 +00006610 }
Mike Stump1eb44332009-09-09 15:08:12 +00006611
Douglas Gregor312a2022009-09-26 03:56:17 +00006612 // [...] any function template specializations in the set are
6613 // eliminated if the set also contains a non-template function, [...]
John McCallc373d482010-01-27 01:50:18 +00006614 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCall9aa472c2010-03-19 07:35:19 +00006615 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCallc373d482010-01-27 01:50:18 +00006616 ++I;
6617 else {
John McCall9aa472c2010-03-19 07:35:19 +00006618 Matches[I] = Matches[--N];
6619 Matches.set_size(N);
John McCallc373d482010-01-27 01:50:18 +00006620 }
6621 }
Douglas Gregor312a2022009-09-26 03:56:17 +00006622
Mike Stump1eb44332009-09-09 15:08:12 +00006623 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00006624 // selected function.
John McCallc373d482010-01-27 01:50:18 +00006625 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00006626 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall6bb80172010-03-30 21:47:33 +00006627 FoundResult = Matches[0].first;
Douglas Gregor9b623632010-10-12 23:32:35 +00006628 if (Complain)
John McCall9aa472c2010-03-19 07:35:19 +00006629 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
6630 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redl07ab2022009-10-17 21:12:09 +00006631 }
Mike Stump1eb44332009-09-09 15:08:12 +00006632
Douglas Gregor00aeb522009-07-08 23:33:52 +00006633 // FIXME: We should probably return the same thing that BestViableFunction
6634 // returns (even if we issue the diagnostics here).
Douglas Gregor8e960432010-11-08 03:40:48 +00006635 if (Complain) {
6636 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
6637 << Matches[0].second->getDeclName();
6638 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6639 NoteOverloadCandidate(Matches[I].second);
6640 }
6641
Douglas Gregor904eed32008-11-10 20:40:00 +00006642 return 0;
6643}
6644
Douglas Gregor4b52e252009-12-21 23:17:24 +00006645/// \brief Given an expression that refers to an overloaded function, try to
6646/// resolve that overloaded function expression down to a single function.
6647///
6648/// This routine can only resolve template-ids that refer to a single function
6649/// template, where that template-id refers to a single template whose template
6650/// arguments are either provided by the template-id or have defaults,
6651/// as described in C++0x [temp.arg.explicit]p3.
6652FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6653 // C++ [over.over]p1:
6654 // [...] [Note: any redundant set of parentheses surrounding the
6655 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00006656 // C++ [over.over]p1:
6657 // [...] The overloaded function name can be preceded by the &
6658 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00006659
6660 if (From->getType() != Context.OverloadTy)
6661 return 0;
6662
John McCall9c72c602010-08-27 09:08:28 +00006663 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
Douglas Gregor4b52e252009-12-21 23:17:24 +00006664
6665 // If we didn't actually find any template-ids, we're done.
John McCall7bb12da2010-02-02 06:20:04 +00006666 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00006667 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00006668
6669 TemplateArgumentListInfo ExplicitTemplateArgs;
6670 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor4b52e252009-12-21 23:17:24 +00006671
6672 // Look through all of the overloaded functions, searching for one
6673 // whose type matches exactly.
6674 FunctionDecl *Matched = 0;
John McCall7bb12da2010-02-02 06:20:04 +00006675 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6676 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00006677 // C++0x [temp.arg.explicit]p3:
6678 // [...] In contexts where deduction is done and fails, or in contexts
6679 // where deduction is not done, if a template argument list is
6680 // specified and it, along with any default template arguments,
6681 // identifies a single function template specialization, then the
6682 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00006683 FunctionTemplateDecl *FunctionTemplate
6684 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor4b52e252009-12-21 23:17:24 +00006685
6686 // C++ [over.over]p2:
6687 // If the name is a function template, template argument deduction is
6688 // done (14.8.2.2), and if the argument deduction succeeds, the
6689 // resulting template argument list is used to generate a single
6690 // function template specialization, which is added to the set of
6691 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00006692 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00006693 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00006694 if (TemplateDeductionResult Result
6695 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6696 Specialization, Info)) {
6697 // FIXME: make a note of the failed deduction for diagnostics.
6698 (void)Result;
6699 continue;
6700 }
6701
6702 // Multiple matches; we can't resolve to a single declaration.
6703 if (Matched)
6704 return 0;
6705
6706 Matched = Specialization;
6707 }
Douglas Gregor9b623632010-10-12 23:32:35 +00006708
Douglas Gregor4b52e252009-12-21 23:17:24 +00006709 return Matched;
6710}
6711
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006712/// \brief Add a single candidate to the overload set.
6713static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00006714 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00006715 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006716 Expr **Args, unsigned NumArgs,
6717 OverloadCandidateSet &CandidateSet,
6718 bool PartialOverloading) {
John McCall9aa472c2010-03-19 07:35:19 +00006719 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00006720 if (isa<UsingShadowDecl>(Callee))
6721 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6722
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006723 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00006724 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCall9aa472c2010-03-19 07:35:19 +00006725 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00006726 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006727 return;
John McCallba135432009-11-21 08:51:07 +00006728 }
6729
6730 if (FunctionTemplateDecl *FuncTemplate
6731 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00006732 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6733 ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00006734 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00006735 return;
6736 }
6737
6738 assert(false && "unhandled case in overloaded call candidate");
6739
6740 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006741}
6742
6743/// \brief Add the overload candidates named by callee and/or found by argument
6744/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00006745void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006746 Expr **Args, unsigned NumArgs,
6747 OverloadCandidateSet &CandidateSet,
6748 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00006749
6750#ifndef NDEBUG
6751 // Verify that ArgumentDependentLookup is consistent with the rules
6752 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006753 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006754 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6755 // and let Y be the lookup set produced by argument dependent
6756 // lookup (defined as follows). If X contains
6757 //
6758 // -- a declaration of a class member, or
6759 //
6760 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00006761 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006762 //
6763 // -- a declaration that is neither a function or a function
6764 // template
6765 //
6766 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00006767
John McCall3b4294e2009-12-16 12:17:52 +00006768 if (ULE->requiresADL()) {
6769 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6770 E = ULE->decls_end(); I != E; ++I) {
6771 assert(!(*I)->getDeclContext()->isRecord());
6772 assert(isa<UsingShadowDecl>(*I) ||
6773 !(*I)->getDeclContext()->isFunctionOrMethod());
6774 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00006775 }
6776 }
6777#endif
6778
John McCall3b4294e2009-12-16 12:17:52 +00006779 // It would be nice to avoid this copy.
6780 TemplateArgumentListInfo TABuffer;
6781 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6782 if (ULE->hasExplicitTemplateArgs()) {
6783 ULE->copyTemplateArgumentsInto(TABuffer);
6784 ExplicitTemplateArgs = &TABuffer;
6785 }
6786
6787 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6788 E = ULE->decls_end(); I != E; ++I)
John McCall9aa472c2010-03-19 07:35:19 +00006789 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00006790 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006791 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00006792
John McCall3b4294e2009-12-16 12:17:52 +00006793 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00006794 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6795 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006796 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006797 CandidateSet,
6798 PartialOverloading);
6799}
John McCall578b69b2009-12-16 08:11:27 +00006800
6801/// Attempts to recover from a call where no functions were found.
6802///
6803/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00006804static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006805BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00006806 UnresolvedLookupExpr *ULE,
6807 SourceLocation LParenLoc,
6808 Expr **Args, unsigned NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00006809 SourceLocation RParenLoc) {
John McCall578b69b2009-12-16 08:11:27 +00006810
6811 CXXScopeSpec SS;
6812 if (ULE->getQualifier()) {
6813 SS.setScopeRep(ULE->getQualifier());
6814 SS.setRange(ULE->getQualifierRange());
6815 }
6816
John McCall3b4294e2009-12-16 12:17:52 +00006817 TemplateArgumentListInfo TABuffer;
6818 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6819 if (ULE->hasExplicitTemplateArgs()) {
6820 ULE->copyTemplateArgumentsInto(TABuffer);
6821 ExplicitTemplateArgs = &TABuffer;
6822 }
6823
John McCall578b69b2009-12-16 08:11:27 +00006824 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6825 Sema::LookupOrdinaryName);
Douglas Gregor91f7ac72010-05-18 16:14:23 +00006826 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCallf312b1e2010-08-26 23:41:50 +00006827 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00006828
John McCall3b4294e2009-12-16 12:17:52 +00006829 assert(!R.empty() && "lookup results empty despite recovery");
6830
6831 // Build an implicit member call if appropriate. Just drop the
6832 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00006833 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00006834 if ((*R.begin())->isCXXClassMember())
6835 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6836 else if (ExplicitTemplateArgs)
6837 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6838 else
6839 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6840
6841 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00006842 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00006843
6844 // This shouldn't cause an infinite loop because we're giving it
6845 // an expression with non-empty lookup results, which should never
6846 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00006847 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +00006848 MultiExprArg(Args, NumArgs), RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00006849}
Douglas Gregord7a95972010-06-08 17:35:15 +00006850
Douglas Gregorf6b89692008-11-26 05:54:23 +00006851/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00006852/// (which eventually refers to the declaration Func) and the call
6853/// arguments Args/NumArgs, attempt to resolve the function call down
6854/// to a specific function. If overload resolution succeeds, returns
6855/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00006856/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00006857/// arguments and Fn, and returns NULL.
John McCall60d7b3a2010-08-24 06:29:42 +00006858ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006859Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00006860 SourceLocation LParenLoc,
6861 Expr **Args, unsigned NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00006862 SourceLocation RParenLoc) {
6863#ifndef NDEBUG
6864 if (ULE->requiresADL()) {
6865 // To do ADL, we must have found an unqualified name.
6866 assert(!ULE->getQualifier() && "qualified name with ADL");
6867
6868 // We don't perform ADL for implicit declarations of builtins.
6869 // Verify that this was correctly set up.
6870 FunctionDecl *F;
6871 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6872 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6873 F->getBuiltinID() && F->isImplicit())
6874 assert(0 && "performing ADL for builtin");
6875
6876 // We don't perform ADL in C.
6877 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6878 }
6879#endif
6880
John McCall5769d612010-02-08 23:07:23 +00006881 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00006882
John McCall3b4294e2009-12-16 12:17:52 +00006883 // Add the functions denoted by the callee to the set of candidate
6884 // functions, including those from argument-dependent lookup.
6885 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00006886
6887 // If we found nothing, try to recover.
6888 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6889 // bailout out if it fails.
John McCall3b4294e2009-12-16 12:17:52 +00006890 if (CandidateSet.empty())
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006891 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00006892 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00006893
Douglas Gregorf6b89692008-11-26 05:54:23 +00006894 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00006895 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00006896 case OR_Success: {
6897 FunctionDecl *FDecl = Best->Function;
John McCall9aa472c2010-03-19 07:35:19 +00006898 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00006899 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(), ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00006900 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall3b4294e2009-12-16 12:17:52 +00006901 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6902 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00006903
6904 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00006905 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00006906 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00006907 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00006908 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00006909 break;
6910
6911 case OR_Ambiguous:
6912 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00006913 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00006914 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00006915 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006916
6917 case OR_Deleted:
6918 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6919 << Best->Function->isDeleted()
John McCall3b4294e2009-12-16 12:17:52 +00006920 << ULE->getName()
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006921 << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00006922 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006923 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00006924 }
6925
Douglas Gregorff331c12010-07-25 18:17:45 +00006926 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00006927 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00006928}
6929
John McCall6e266892010-01-26 03:27:55 +00006930static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00006931 return Functions.size() > 1 ||
6932 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6933}
6934
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006935/// \brief Create a unary operation that may resolve to an overloaded
6936/// operator.
6937///
6938/// \param OpLoc The location of the operator itself (e.g., '*').
6939///
6940/// \param OpcIn The UnaryOperator::Opcode that describes this
6941/// operator.
6942///
6943/// \param Functions The set of non-member functions that will be
6944/// considered by overload resolution. The caller needs to build this
6945/// set based on the context using, e.g.,
6946/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6947/// set should not contain any member functions; those will be added
6948/// by CreateOverloadedUnaryOp().
6949///
6950/// \param input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +00006951ExprResult
John McCall6e266892010-01-26 03:27:55 +00006952Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6953 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +00006954 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006955 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006956
6957 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6958 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6959 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00006960 // TODO: provide better source location info.
6961 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006962
6963 Expr *Args[2] = { Input, 0 };
6964 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00006965
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006966 // For post-increment and post-decrement, add the implicit '0' as
6967 // the second argument, so that we know this is a post-increment or
6968 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +00006969 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006970 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00006971 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
6972 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006973 NumArgs = 2;
6974 }
6975
6976 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00006977 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +00006978 return Owned(new (Context) UnaryOperator(Input,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00006979 Opc,
6980 Context.DependentTy,
6981 OpLoc));
6982
John McCallc373d482010-01-27 01:50:18 +00006983 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00006984 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00006985 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00006986 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00006987 /*ADL*/ true, IsOverloaded(Fns),
6988 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006989 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6990 &Args[0], NumArgs,
6991 Context.DependentTy,
6992 OpLoc));
6993 }
6994
6995 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00006996 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006997
6998 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00006999 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007000
7001 // Add operator candidates that are member functions.
7002 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
7003
John McCall6e266892010-01-26 03:27:55 +00007004 // Add candidates from ADL.
7005 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregordc81c882010-02-05 05:15:43 +00007006 Args, NumArgs,
John McCall6e266892010-01-26 03:27:55 +00007007 /*ExplicitTemplateArgs*/ 0,
7008 CandidateSet);
7009
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007010 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00007011 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007012
7013 // Perform overload resolution.
7014 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007015 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007016 case OR_Success: {
7017 // We found a built-in operator or an overloaded operator.
7018 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00007019
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007020 if (FnDecl) {
7021 // We matched an overloaded operator. Build a call to that
7022 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00007023
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007024 // Convert the arguments.
7025 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00007026 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00007027
John McCall6bb80172010-03-30 21:47:33 +00007028 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
7029 Best->FoundDecl, Method))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007030 return ExprError();
7031 } else {
7032 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00007033 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +00007034 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007035 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +00007036 FnDecl->getParamDecl(0)),
Douglas Gregore1a5c172009-12-23 17:40:29 +00007037 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +00007038 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +00007039 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007040 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00007041 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007042 }
7043
John McCallb697e082010-05-06 18:15:07 +00007044 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7045
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007046 // Determine the result type
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007047 QualType ResultTy = FnDecl->getCallResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00007048
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007049 // Build the actual expression node.
7050 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7051 SourceLocation());
7052 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00007053
Eli Friedman4c3b8962009-11-18 03:58:17 +00007054 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +00007055 CallExpr *TheCall =
Anders Carlsson26a2a072009-10-13 21:19:37 +00007056 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall9ae2f072010-08-23 23:25:46 +00007057 Args, NumArgs, ResultTy, OpLoc);
John McCallb697e082010-05-06 18:15:07 +00007058
John McCall9ae2f072010-08-23 23:25:46 +00007059 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +00007060 FnDecl))
7061 return ExprError();
7062
John McCall9ae2f072010-08-23 23:25:46 +00007063 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007064 } else {
7065 // We matched a built-in operator. Convert the arguments, then
7066 // break out so that we will build the appropriate built-in
7067 // operator node.
7068 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00007069 Best->Conversions[0], AA_Passing))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007070 return ExprError();
7071
7072 break;
7073 }
7074 }
7075
7076 case OR_No_Viable_Function:
7077 // No viable function; fall through to handling this as a
7078 // built-in operator, which will produce an error message for us.
7079 break;
7080
7081 case OR_Ambiguous:
7082 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
7083 << UnaryOperator::getOpcodeStr(Opc)
7084 << Input->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007085 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
7086 Args, NumArgs,
7087 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007088 return ExprError();
7089
7090 case OR_Deleted:
7091 Diag(OpLoc, diag::err_ovl_deleted_oper)
7092 << Best->Function->isDeleted()
7093 << UnaryOperator::getOpcodeStr(Opc)
7094 << Input->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007095 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007096 return ExprError();
7097 }
7098
7099 // Either we found no viable overloaded operator or we matched a
7100 // built-in operator. In either case, fall through to trying to
7101 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +00007102 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007103}
7104
Douglas Gregor063daf62009-03-13 18:40:31 +00007105/// \brief Create a binary operation that may resolve to an overloaded
7106/// operator.
7107///
7108/// \param OpLoc The location of the operator itself (e.g., '+').
7109///
7110/// \param OpcIn The BinaryOperator::Opcode that describes this
7111/// operator.
7112///
7113/// \param Functions The set of non-member functions that will be
7114/// considered by overload resolution. The caller needs to build this
7115/// set based on the context using, e.g.,
7116/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7117/// set should not contain any member functions; those will be added
7118/// by CreateOverloadedBinOp().
7119///
7120/// \param LHS Left-hand argument.
7121/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +00007122ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00007123Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00007124 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00007125 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00007126 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00007127 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007128 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00007129
7130 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
7131 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
7132 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7133
7134 // If either side is type-dependent, create an appropriate dependent
7135 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007136 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00007137 if (Fns.empty()) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007138 // If there are no functions to store, just build a dependent
7139 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +00007140 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007141 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
7142 Context.DependentTy, OpLoc));
7143
7144 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
7145 Context.DependentTy,
7146 Context.DependentTy,
7147 Context.DependentTy,
7148 OpLoc));
7149 }
John McCall6e266892010-01-26 03:27:55 +00007150
7151 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00007152 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00007153 // TODO: provide better source location info in DNLoc component.
7154 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +00007155 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00007156 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00007157 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00007158 /*ADL*/ true, IsOverloaded(Fns),
7159 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00007160 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00007161 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00007162 Context.DependentTy,
7163 OpLoc));
7164 }
7165
7166 // If this is the .* operator, which is not overloadable, just
7167 // create a built-in binary operator.
John McCall2de56d12010-08-25 11:45:40 +00007168 if (Opc == BO_PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007169 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00007170
Sebastian Redl275c2b42009-11-18 23:10:33 +00007171 // If this is the assignment operator, we only perform overload resolution
7172 // if the left-hand side is a class or enumeration type. This is actually
7173 // a hack. The standard requires that we do overload resolution between the
7174 // various built-in candidates, but as DR507 points out, this can lead to
7175 // problems. So we do it this way, which pretty much follows what GCC does.
7176 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +00007177 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007178 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00007179
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007180 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00007181 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00007182
7183 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00007184 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00007185
7186 // Add operator candidates that are member functions.
7187 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
7188
John McCall6e266892010-01-26 03:27:55 +00007189 // Add candidates from ADL.
7190 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
7191 Args, 2,
7192 /*ExplicitTemplateArgs*/ 0,
7193 CandidateSet);
7194
Douglas Gregor063daf62009-03-13 18:40:31 +00007195 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00007196 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00007197
7198 // Perform overload resolution.
7199 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007200 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007201 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00007202 // We found a built-in operator or an overloaded operator.
7203 FunctionDecl *FnDecl = Best->Function;
7204
7205 if (FnDecl) {
7206 // We matched an overloaded operator. Build a call to that
7207 // operator.
7208
7209 // Convert the arguments.
7210 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00007211 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +00007212 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00007213
John McCall60d7b3a2010-08-24 06:29:42 +00007214 ExprResult Arg1
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007215 = PerformCopyInitialization(
7216 InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007217 Context,
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007218 FnDecl->getParamDecl(0)),
7219 SourceLocation(),
7220 Owned(Args[1]));
7221 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00007222 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007223
Douglas Gregor5fccd362010-03-03 23:55:11 +00007224 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007225 Best->FoundDecl, Method))
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007226 return ExprError();
7227
7228 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00007229 } else {
7230 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00007231 ExprResult Arg0
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007232 = PerformCopyInitialization(
7233 InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007234 Context,
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007235 FnDecl->getParamDecl(0)),
7236 SourceLocation(),
7237 Owned(Args[0]));
7238 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00007239 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007240
John McCall60d7b3a2010-08-24 06:29:42 +00007241 ExprResult Arg1
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007242 = PerformCopyInitialization(
7243 InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007244 Context,
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007245 FnDecl->getParamDecl(1)),
7246 SourceLocation(),
7247 Owned(Args[1]));
7248 if (Arg1.isInvalid())
7249 return ExprError();
7250 Args[0] = LHS = Arg0.takeAs<Expr>();
7251 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00007252 }
7253
John McCallb697e082010-05-06 18:15:07 +00007254 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7255
Douglas Gregor063daf62009-03-13 18:40:31 +00007256 // Determine the result type
7257 QualType ResultTy
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007258 = FnDecl->getType()->getAs<FunctionType>()
7259 ->getCallResultType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +00007260
7261 // Build the actual expression node.
7262 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00007263 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00007264 UsualUnaryConversions(FnExpr);
7265
John McCall9ae2f072010-08-23 23:25:46 +00007266 CXXOperatorCallExpr *TheCall =
7267 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
7268 Args, 2, ResultTy, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +00007269
John McCall9ae2f072010-08-23 23:25:46 +00007270 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00007271 FnDecl))
7272 return ExprError();
7273
John McCall9ae2f072010-08-23 23:25:46 +00007274 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +00007275 } else {
7276 // We matched a built-in operator. Convert the arguments, then
7277 // break out so that we will build the appropriate built-in
7278 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007279 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00007280 Best->Conversions[0], AA_Passing) ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007281 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00007282 Best->Conversions[1], AA_Passing))
Douglas Gregor063daf62009-03-13 18:40:31 +00007283 return ExprError();
7284
7285 break;
7286 }
7287 }
7288
Douglas Gregor33074752009-09-30 21:46:01 +00007289 case OR_No_Viable_Function: {
7290 // C++ [over.match.oper]p9:
7291 // If the operator is the operator , [...] and there are no
7292 // viable functions, then the operator is assumed to be the
7293 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +00007294 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +00007295 break;
7296
Sebastian Redl8593c782009-05-21 11:50:50 +00007297 // For class as left operand for assignment or compound assigment operator
7298 // do not fall through to handling in built-in, but report that no overloaded
7299 // assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +00007300 ExprResult Result = ExprError();
Douglas Gregor33074752009-09-30 21:46:01 +00007301 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +00007302 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00007303 Diag(OpLoc, diag::err_ovl_no_viable_oper)
7304 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007305 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00007306 } else {
7307 // No viable function; try to create a built-in operation, which will
7308 // produce an error. Then, show the non-viable candidates.
7309 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00007310 }
Douglas Gregor33074752009-09-30 21:46:01 +00007311 assert(Result.isInvalid() &&
7312 "C++ binary operator overloading is missing candidates!");
7313 if (Result.isInvalid())
John McCall120d63c2010-08-24 20:38:10 +00007314 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7315 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00007316 return move(Result);
7317 }
Douglas Gregor063daf62009-03-13 18:40:31 +00007318
7319 case OR_Ambiguous:
7320 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
7321 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007322 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007323 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7324 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00007325 return ExprError();
7326
7327 case OR_Deleted:
7328 Diag(OpLoc, diag::err_ovl_deleted_oper)
7329 << Best->Function->isDeleted()
7330 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007331 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007332 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor063daf62009-03-13 18:40:31 +00007333 return ExprError();
John McCall1d318332010-01-12 00:44:57 +00007334 }
Douglas Gregor063daf62009-03-13 18:40:31 +00007335
Douglas Gregor33074752009-09-30 21:46:01 +00007336 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007337 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00007338}
7339
John McCall60d7b3a2010-08-24 06:29:42 +00007340ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +00007341Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7342 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +00007343 Expr *Base, Expr *Idx) {
7344 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +00007345 DeclarationName OpName =
7346 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7347
7348 // If either side is type-dependent, create an appropriate dependent
7349 // expression.
7350 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7351
John McCallc373d482010-01-27 01:50:18 +00007352 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00007353 // CHECKME: no 'operator' keyword?
7354 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7355 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +00007356 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00007357 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00007358 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00007359 /*ADL*/ true, /*Overloaded*/ false,
7360 UnresolvedSetIterator(),
7361 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +00007362 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00007363
Sebastian Redlf322ed62009-10-29 20:17:01 +00007364 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7365 Args, 2,
7366 Context.DependentTy,
7367 RLoc));
7368 }
7369
7370 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00007371 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007372
7373 // Subscript can only be overloaded as a member function.
7374
7375 // Add operator candidates that are member functions.
7376 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7377
7378 // Add builtin operator candidates.
7379 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7380
7381 // Perform overload resolution.
7382 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007383 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00007384 case OR_Success: {
7385 // We found a built-in operator or an overloaded operator.
7386 FunctionDecl *FnDecl = Best->Function;
7387
7388 if (FnDecl) {
7389 // We matched an overloaded operator. Build a call to that
7390 // operator.
7391
John McCall9aa472c2010-03-19 07:35:19 +00007392 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007393 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +00007394
Sebastian Redlf322ed62009-10-29 20:17:01 +00007395 // Convert the arguments.
7396 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007397 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007398 Best->FoundDecl, Method))
Sebastian Redlf322ed62009-10-29 20:17:01 +00007399 return ExprError();
7400
Anders Carlsson38f88ab2010-01-29 18:37:50 +00007401 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00007402 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +00007403 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007404 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +00007405 FnDecl->getParamDecl(0)),
7406 SourceLocation(),
7407 Owned(Args[1]));
7408 if (InputInit.isInvalid())
7409 return ExprError();
7410
7411 Args[1] = InputInit.takeAs<Expr>();
7412
Sebastian Redlf322ed62009-10-29 20:17:01 +00007413 // Determine the result type
7414 QualType ResultTy
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007415 = FnDecl->getType()->getAs<FunctionType>()
7416 ->getCallResultType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007417
7418 // Build the actual expression node.
7419 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7420 LLoc);
7421 UsualUnaryConversions(FnExpr);
7422
John McCall9ae2f072010-08-23 23:25:46 +00007423 CXXOperatorCallExpr *TheCall =
7424 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7425 FnExpr, Args, 2,
7426 ResultTy, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007427
John McCall9ae2f072010-08-23 23:25:46 +00007428 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +00007429 FnDecl))
7430 return ExprError();
7431
John McCall9ae2f072010-08-23 23:25:46 +00007432 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007433 } else {
7434 // We matched a built-in operator. Convert the arguments, then
7435 // break out so that we will build the appropriate built-in
7436 // operator node.
7437 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00007438 Best->Conversions[0], AA_Passing) ||
Sebastian Redlf322ed62009-10-29 20:17:01 +00007439 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00007440 Best->Conversions[1], AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00007441 return ExprError();
7442
7443 break;
7444 }
7445 }
7446
7447 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00007448 if (CandidateSet.empty())
7449 Diag(LLoc, diag::err_ovl_no_oper)
7450 << Args[0]->getType() << /*subscript*/ 0
7451 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7452 else
7453 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7454 << Args[0]->getType()
7455 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007456 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7457 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +00007458 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00007459 }
7460
7461 case OR_Ambiguous:
7462 Diag(LLoc, diag::err_ovl_ambiguous_oper)
7463 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007464 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7465 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007466 return ExprError();
7467
7468 case OR_Deleted:
7469 Diag(LLoc, diag::err_ovl_deleted_oper)
7470 << Best->Function->isDeleted() << "[]"
7471 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007472 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7473 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007474 return ExprError();
7475 }
7476
7477 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +00007478 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007479}
7480
Douglas Gregor88a35142008-12-22 05:46:06 +00007481/// BuildCallToMemberFunction - Build a call to a member
7482/// function. MemExpr is the expression that refers to the member
7483/// function (and includes the object parameter), Args/NumArgs are the
7484/// arguments to the function call (not including the object
7485/// parameter). The caller needs to validate that the member
7486/// expression refers to a member function or an overloaded member
7487/// function.
John McCall60d7b3a2010-08-24 06:29:42 +00007488ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00007489Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7490 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +00007491 unsigned NumArgs, SourceLocation RParenLoc) {
Douglas Gregor88a35142008-12-22 05:46:06 +00007492 // Dig out the member expression. This holds both the object
7493 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00007494 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7495
John McCall129e2df2009-11-30 22:42:35 +00007496 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00007497 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +00007498 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007499 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +00007500 if (isa<MemberExpr>(NakedMemExpr)) {
7501 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00007502 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +00007503 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +00007504 Qualifier = MemExpr->getQualifier();
John McCall129e2df2009-11-30 22:42:35 +00007505 } else {
7506 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007507 Qualifier = UnresExpr->getQualifier();
7508
John McCall701c89e2009-12-03 04:06:58 +00007509 QualType ObjectType = UnresExpr->getBaseType();
John McCall129e2df2009-11-30 22:42:35 +00007510
Douglas Gregor88a35142008-12-22 05:46:06 +00007511 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +00007512 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00007513
John McCallaa81e162009-12-01 22:10:20 +00007514 // FIXME: avoid copy.
7515 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7516 if (UnresExpr->hasExplicitTemplateArgs()) {
7517 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7518 TemplateArgs = &TemplateArgsBuffer;
7519 }
7520
John McCall129e2df2009-11-30 22:42:35 +00007521 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7522 E = UnresExpr->decls_end(); I != E; ++I) {
7523
John McCall701c89e2009-12-03 04:06:58 +00007524 NamedDecl *Func = *I;
7525 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7526 if (isa<UsingShadowDecl>(Func))
7527 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7528
John McCall129e2df2009-11-30 22:42:35 +00007529 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00007530 // If explicit template arguments were provided, we can't call a
7531 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00007532 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00007533 continue;
7534
John McCall9aa472c2010-03-19 07:35:19 +00007535 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCall86820f52010-01-26 01:37:31 +00007536 Args, NumArgs,
John McCall701c89e2009-12-03 04:06:58 +00007537 CandidateSet, /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00007538 } else {
John McCall129e2df2009-11-30 22:42:35 +00007539 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +00007540 I.getPair(), ActingDC, TemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00007541 ObjectType, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00007542 CandidateSet,
7543 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00007544 }
Douglas Gregordec06662009-08-21 18:42:58 +00007545 }
Mike Stump1eb44332009-09-09 15:08:12 +00007546
John McCall129e2df2009-11-30 22:42:35 +00007547 DeclarationName DeclName = UnresExpr->getMemberName();
7548
Douglas Gregor88a35142008-12-22 05:46:06 +00007549 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007550 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
7551 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00007552 case OR_Success:
7553 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00007554 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +00007555 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007556 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +00007557 break;
7558
7559 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00007560 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00007561 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00007562 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007563 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00007564 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007565 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007566
7567 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00007568 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00007569 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007570 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00007571 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007572 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007573
7574 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00007575 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007576 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00007577 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007578 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007579 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007580 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007581 }
7582
John McCall6bb80172010-03-30 21:47:33 +00007583 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +00007584
John McCallaa81e162009-12-01 22:10:20 +00007585 // If overload resolution picked a static member, build a
7586 // non-member call based on that function.
7587 if (Method->isStatic()) {
7588 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7589 Args, NumArgs, RParenLoc);
7590 }
7591
John McCall129e2df2009-11-30 22:42:35 +00007592 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00007593 }
7594
7595 assert(Method && "Member call to something that isn't a method?");
John McCall9ae2f072010-08-23 23:25:46 +00007596 CXXMemberCallExpr *TheCall =
7597 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
7598 Method->getCallResultType(),
7599 RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +00007600
Anders Carlssoneed3e692009-10-10 00:06:20 +00007601 // Check for a valid return type.
7602 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +00007603 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +00007604 return ExprError();
Anders Carlssoneed3e692009-10-10 00:06:20 +00007605
Douglas Gregor88a35142008-12-22 05:46:06 +00007606 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +00007607 // We only need to do this if there was actually an overload; otherwise
7608 // it was done at lookup.
John McCallaa81e162009-12-01 22:10:20 +00007609 Expr *ObjectArg = MemExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00007610 if (!Method->isStatic() &&
John McCall6bb80172010-03-30 21:47:33 +00007611 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7612 FoundDecl, Method))
John McCallaa81e162009-12-01 22:10:20 +00007613 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007614 MemExpr->setBase(ObjectArg);
7615
7616 // Convert the rest of the arguments
Douglas Gregor5f970ee2010-05-04 18:18:31 +00007617 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +00007618 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00007619 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00007620 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007621
John McCall9ae2f072010-08-23 23:25:46 +00007622 if (CheckFunctionCall(Method, TheCall))
John McCallaa81e162009-12-01 22:10:20 +00007623 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00007624
John McCall9ae2f072010-08-23 23:25:46 +00007625 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +00007626}
7627
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007628/// BuildCallToObjectOfClassType - Build a call to an object of class
7629/// type (C++ [over.call.object]), which can end up invoking an
7630/// overloaded function call operator (@c operator()) or performing a
7631/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +00007632ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00007633Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00007634 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007635 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007636 SourceLocation RParenLoc) {
7637 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00007638 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00007639
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007640 // C++ [over.call.object]p1:
7641 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00007642 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007643 // candidate functions includes at least the function call
7644 // operators of T. The function call operators of T are obtained by
7645 // ordinary lookup of the name operator() in the context of
7646 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +00007647 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00007648 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00007649
7650 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007651 PDiag(diag::err_incomplete_object_call)
Douglas Gregor593564b2009-11-15 07:48:03 +00007652 << Object->getSourceRange()))
7653 return true;
7654
John McCalla24dc2e2009-11-17 02:14:36 +00007655 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7656 LookupQualifiedName(R, Record->getDecl());
7657 R.suppressDiagnostics();
7658
Douglas Gregor593564b2009-11-15 07:48:03 +00007659 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00007660 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00007661 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCall86820f52010-01-26 01:37:31 +00007662 Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00007663 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00007664 }
Douglas Gregor4a27d702009-10-21 06:18:39 +00007665
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007666 // C++ [over.call.object]p2:
7667 // In addition, for each conversion function declared in T of the
7668 // form
7669 //
7670 // operator conversion-type-id () cv-qualifier;
7671 //
7672 // where cv-qualifier is the same cv-qualification as, or a
7673 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00007674 // denotes the type "pointer to function of (P1,...,Pn) returning
7675 // R", or the type "reference to pointer to function of
7676 // (P1,...,Pn) returning R", or the type "reference to function
7677 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007678 // is also considered as a candidate function. Similarly,
7679 // surrogate call functions are added to the set of candidate
7680 // functions for each conversion function declared in an
7681 // accessible base class provided the function is not hidden
7682 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +00007683 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00007684 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00007685 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00007686 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00007687 NamedDecl *D = *I;
7688 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7689 if (isa<UsingShadowDecl>(D))
7690 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7691
Douglas Gregor4a27d702009-10-21 06:18:39 +00007692 // Skip over templated conversion functions; they aren't
7693 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00007694 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00007695 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007696
John McCall701c89e2009-12-03 04:06:58 +00007697 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCallba135432009-11-21 08:51:07 +00007698
Douglas Gregor4a27d702009-10-21 06:18:39 +00007699 // Strip the reference type (if any) and then the pointer type (if
7700 // any) to get down to what might be a function type.
7701 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7702 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7703 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007704
Douglas Gregor4a27d702009-10-21 06:18:39 +00007705 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall9aa472c2010-03-19 07:35:19 +00007706 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall701c89e2009-12-03 04:06:58 +00007707 Object->getType(), Args, NumArgs,
7708 CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007709 }
Mike Stump1eb44332009-09-09 15:08:12 +00007710
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007711 // Perform overload resolution.
7712 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007713 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
7714 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007715 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007716 // Overload resolution succeeded; we'll build the appropriate call
7717 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007718 break;
7719
7720 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00007721 if (CandidateSet.empty())
7722 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7723 << Object->getType() << /*call*/ 1
7724 << Object->getSourceRange();
7725 else
7726 Diag(Object->getSourceRange().getBegin(),
7727 diag::err_ovl_no_viable_object_call)
7728 << Object->getType() << Object->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007729 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007730 break;
7731
7732 case OR_Ambiguous:
7733 Diag(Object->getSourceRange().getBegin(),
7734 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00007735 << Object->getType() << Object->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007736 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007737 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007738
7739 case OR_Deleted:
7740 Diag(Object->getSourceRange().getBegin(),
7741 diag::err_ovl_deleted_object_call)
7742 << Best->Function->isDeleted()
7743 << Object->getType() << Object->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007744 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007745 break;
Mike Stump1eb44332009-09-09 15:08:12 +00007746 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007747
Douglas Gregorff331c12010-07-25 18:17:45 +00007748 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007749 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007750
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007751 if (Best->Function == 0) {
7752 // Since there is no function declaration, this is one of the
7753 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00007754 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007755 = cast<CXXConversionDecl>(
7756 Best->Conversions[0].UserDefined.ConversionFunction);
7757
John McCall9aa472c2010-03-19 07:35:19 +00007758 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007759 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00007760
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007761 // We selected one of the surrogate functions that converts the
7762 // object parameter to a function pointer. Perform the conversion
7763 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00007764
7765 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00007766 // and then call it.
John McCall6bb80172010-03-30 21:47:33 +00007767 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7768 Conv);
Fariborz Jahanianb7400232009-09-28 23:23:40 +00007769
John McCallf312b1e2010-08-26 23:41:50 +00007770 return ActOnCallExpr(S, CE, LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007771 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007772 }
7773
John McCall9aa472c2010-03-19 07:35:19 +00007774 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007775 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00007776
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007777 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7778 // that calls this method, using Object for the implicit object
7779 // parameter and passing along the remaining arguments.
7780 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall183700f2009-09-21 23:43:11 +00007781 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007782
7783 unsigned NumArgsInProto = Proto->getNumArgs();
7784 unsigned NumArgsToCheck = NumArgs;
7785
7786 // Build the full argument list for the method call (the
7787 // implicit object parameter is placed at the beginning of the
7788 // list).
7789 Expr **MethodArgs;
7790 if (NumArgs < NumArgsInProto) {
7791 NumArgsToCheck = NumArgsInProto;
7792 MethodArgs = new Expr*[NumArgsInProto + 1];
7793 } else {
7794 MethodArgs = new Expr*[NumArgs + 1];
7795 }
7796 MethodArgs[0] = Object;
7797 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7798 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00007799
7800 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00007801 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007802 UsualUnaryConversions(NewFn);
7803
7804 // Once we've built TheCall, all of the expressions are properly
7805 // owned.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007806 QualType ResultTy = Method->getCallResultType();
John McCall9ae2f072010-08-23 23:25:46 +00007807 CXXOperatorCallExpr *TheCall =
7808 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
7809 MethodArgs, NumArgs + 1,
7810 ResultTy, RParenLoc);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007811 delete [] MethodArgs;
7812
John McCall9ae2f072010-08-23 23:25:46 +00007813 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +00007814 Method))
7815 return true;
7816
Douglas Gregor518fda12009-01-13 05:10:00 +00007817 // We may have default arguments. If so, we need to allocate more
7818 // slots in the call for them.
7819 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00007820 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00007821 else if (NumArgs > NumArgsInProto)
7822 NumArgsToCheck = NumArgsInProto;
7823
Chris Lattner312531a2009-04-12 08:11:20 +00007824 bool IsError = false;
7825
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007826 // Initialize the implicit object parameter.
Douglas Gregor5fccd362010-03-03 23:55:11 +00007827 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007828 Best->FoundDecl, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007829 TheCall->setArg(0, Object);
7830
Chris Lattner312531a2009-04-12 08:11:20 +00007831
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007832 // Check the argument types.
7833 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007834 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00007835 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007836 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00007837
Douglas Gregor518fda12009-01-13 05:10:00 +00007838 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +00007839
John McCall60d7b3a2010-08-24 06:29:42 +00007840 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +00007841 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007842 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +00007843 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +00007844 SourceLocation(), Arg);
Anders Carlsson3faa4862010-01-29 18:43:53 +00007845
7846 IsError |= InputInit.isInvalid();
7847 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00007848 } else {
John McCall60d7b3a2010-08-24 06:29:42 +00007849 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +00007850 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7851 if (DefArg.isInvalid()) {
7852 IsError = true;
7853 break;
7854 }
7855
7856 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00007857 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007858
7859 TheCall->setArg(i + 1, Arg);
7860 }
7861
7862 // If this is a variadic call, handle args passed through "...".
7863 if (Proto->isVariadic()) {
7864 // Promote the arguments (C99 6.5.2.2p7).
7865 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7866 Expr *Arg = Args[i];
Chris Lattner40378332010-05-16 04:01:30 +00007867 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007868 TheCall->setArg(i + 1, Arg);
7869 }
7870 }
7871
Chris Lattner312531a2009-04-12 08:11:20 +00007872 if (IsError) return true;
7873
John McCall9ae2f072010-08-23 23:25:46 +00007874 if (CheckFunctionCall(Method, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00007875 return true;
7876
John McCall182f7092010-08-24 06:09:16 +00007877 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007878}
7879
Douglas Gregor8ba10742008-11-20 16:27:02 +00007880/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00007881/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00007882/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +00007883ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00007884Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00007885 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00007886
John McCall5769d612010-02-08 23:07:23 +00007887 SourceLocation Loc = Base->getExprLoc();
7888
Douglas Gregor8ba10742008-11-20 16:27:02 +00007889 // C++ [over.ref]p1:
7890 //
7891 // [...] An expression x->m is interpreted as (x.operator->())->m
7892 // for a class object x of type T if T::operator->() exists and if
7893 // the operator is selected as the best match function by the
7894 // overload resolution mechanism (13.3).
Douglas Gregor8ba10742008-11-20 16:27:02 +00007895 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +00007896 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +00007897 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007898
John McCall5769d612010-02-08 23:07:23 +00007899 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +00007900 PDiag(diag::err_typecheck_incomplete_tag)
7901 << Base->getSourceRange()))
7902 return ExprError();
7903
John McCalla24dc2e2009-11-17 02:14:36 +00007904 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7905 LookupQualifiedName(R, BaseRecord->getDecl());
7906 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00007907
7908 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00007909 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00007910 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00007911 /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00007912 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00007913
7914 // Perform overload resolution.
7915 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007916 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00007917 case OR_Success:
7918 // Overload resolution succeeded; we'll build the call below.
7919 break;
7920
7921 case OR_No_Viable_Function:
7922 if (CandidateSet.empty())
7923 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007924 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007925 else
7926 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007927 << "operator->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007928 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007929 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007930
7931 case OR_Ambiguous:
7932 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlssone30572a2009-09-10 23:18:36 +00007933 << "->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007934 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007935 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007936
7937 case OR_Deleted:
7938 Diag(OpLoc, diag::err_ovl_deleted_oper)
7939 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00007940 << "->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007941 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007942 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007943 }
7944
John McCall9aa472c2010-03-19 07:35:19 +00007945 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007946 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +00007947
Douglas Gregor8ba10742008-11-20 16:27:02 +00007948 // Convert the object parameter.
7949 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00007950 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7951 Best->FoundDecl, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007952 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00007953
Douglas Gregor8ba10742008-11-20 16:27:02 +00007954 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00007955 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7956 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00007957 UsualUnaryConversions(FnExpr);
Anders Carlsson15ea3782009-10-13 22:43:21 +00007958
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007959 QualType ResultTy = Method->getCallResultType();
John McCall9ae2f072010-08-23 23:25:46 +00007960 CXXOperatorCallExpr *TheCall =
7961 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7962 &Base, 1, ResultTy, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +00007963
John McCall9ae2f072010-08-23 23:25:46 +00007964 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00007965 Method))
7966 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00007967 return Owned(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00007968}
7969
Douglas Gregor904eed32008-11-10 20:40:00 +00007970/// FixOverloadedFunctionReference - E is an expression that refers to
7971/// a C++ overloaded function (possibly with some parentheses and
7972/// perhaps a '&' around it). We have resolved the overloaded function
7973/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00007974/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +00007975Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +00007976 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00007977 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00007978 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7979 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00007980 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00007981 return PE;
Douglas Gregor699ee522009-11-20 19:42:02 +00007982
7983 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7984 }
7985
7986 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00007987 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7988 Found, Fn);
Douglas Gregor097bfb12009-10-23 22:18:25 +00007989 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00007990 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00007991 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +00007992 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +00007993 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00007994 return ICE;
Douglas Gregor699ee522009-11-20 19:42:02 +00007995
John McCallf871d0c2010-08-07 06:22:56 +00007996 return ImplicitCastExpr::Create(Context, ICE->getType(),
7997 ICE->getCastKind(),
7998 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +00007999 ICE->getValueKind());
Douglas Gregor699ee522009-11-20 19:42:02 +00008000 }
8001
8002 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00008003 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00008004 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00008005 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8006 if (Method->isStatic()) {
8007 // Do nothing: static member functions aren't any different
8008 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00008009 } else {
John McCallf7a1a742009-11-24 19:00:30 +00008010 // Fix the sub expression, which really has to be an
8011 // UnresolvedLookupExpr holding an overloaded member function
8012 // or template.
John McCall6bb80172010-03-30 21:47:33 +00008013 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8014 Found, Fn);
John McCallba135432009-11-21 08:51:07 +00008015 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00008016 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +00008017
John McCallba135432009-11-21 08:51:07 +00008018 assert(isa<DeclRefExpr>(SubExpr)
8019 && "fixed to something other than a decl ref");
8020 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
8021 && "fixed to a member ref with no nested name qualifier");
8022
8023 // We have taken the address of a pointer to member
8024 // function. Perform the computation here so that we get the
8025 // appropriate pointer to member type.
8026 QualType ClassType
8027 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
8028 QualType MemPtrType
8029 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
8030
John McCall2de56d12010-08-25 11:45:40 +00008031 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
John McCallba135432009-11-21 08:51:07 +00008032 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00008033 }
8034 }
John McCall6bb80172010-03-30 21:47:33 +00008035 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8036 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00008037 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00008038 return UnOp;
Anders Carlsson96ad5332009-10-21 17:16:23 +00008039
John McCall2de56d12010-08-25 11:45:40 +00008040 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +00008041 Context.getPointerType(SubExpr->getType()),
8042 UnOp->getOperatorLoc());
Douglas Gregor699ee522009-11-20 19:42:02 +00008043 }
John McCallba135432009-11-21 08:51:07 +00008044
8045 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00008046 // FIXME: avoid copy.
8047 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00008048 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00008049 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
8050 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00008051 }
8052
John McCallba135432009-11-21 08:51:07 +00008053 return DeclRefExpr::Create(Context,
8054 ULE->getQualifier(),
8055 ULE->getQualifierRange(),
8056 Fn,
8057 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00008058 Fn->getType(),
8059 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00008060 }
8061
John McCall129e2df2009-11-30 22:42:35 +00008062 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00008063 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00008064 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8065 if (MemExpr->hasExplicitTemplateArgs()) {
8066 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8067 TemplateArgs = &TemplateArgsBuffer;
8068 }
John McCalld5532b62009-11-23 01:53:49 +00008069
John McCallaa81e162009-12-01 22:10:20 +00008070 Expr *Base;
8071
8072 // If we're filling in
8073 if (MemExpr->isImplicitAccess()) {
8074 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
8075 return DeclRefExpr::Create(Context,
8076 MemExpr->getQualifier(),
8077 MemExpr->getQualifierRange(),
8078 Fn,
8079 MemExpr->getMemberLoc(),
8080 Fn->getType(),
8081 TemplateArgs);
Douglas Gregor828a1972010-01-07 23:12:05 +00008082 } else {
8083 SourceLocation Loc = MemExpr->getMemberLoc();
8084 if (MemExpr->getQualifier())
8085 Loc = MemExpr->getQualifierRange().getBegin();
8086 Base = new (Context) CXXThisExpr(Loc,
8087 MemExpr->getBaseType(),
8088 /*isImplicit=*/true);
8089 }
John McCallaa81e162009-12-01 22:10:20 +00008090 } else
John McCall3fa5cae2010-10-26 07:05:15 +00008091 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +00008092
8093 return MemberExpr::Create(Context, Base,
Douglas Gregor699ee522009-11-20 19:42:02 +00008094 MemExpr->isArrow(),
8095 MemExpr->getQualifier(),
8096 MemExpr->getQualifierRange(),
8097 Fn,
John McCall6bb80172010-03-30 21:47:33 +00008098 Found,
Abramo Bagnara25777432010-08-11 22:01:17 +00008099 MemExpr->getMemberNameInfo(),
John McCallaa81e162009-12-01 22:10:20 +00008100 TemplateArgs,
Douglas Gregor699ee522009-11-20 19:42:02 +00008101 Fn->getType());
8102 }
8103
John McCall3fa5cae2010-10-26 07:05:15 +00008104 llvm_unreachable("Invalid reference to overloaded function");
8105 return E;
Douglas Gregor904eed32008-11-10 20:40:00 +00008106}
8107
John McCall60d7b3a2010-08-24 06:29:42 +00008108ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
8109 DeclAccessPair Found,
8110 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +00008111 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +00008112}
8113
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008114} // end namespace clang