blob: 80ef65e43359dc0ac0aa9d9d5df098c01e2dad38 [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"
John McCall0e800c92010-12-04 08:14:53 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor661b4932010-09-12 04:28:07 +000029#include "llvm/ADT/DenseSet.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000030#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000032#include <algorithm>
33
34namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000035using namespace sema;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000036
John McCallf89e55a2010-11-18 06:31:45 +000037/// A convenience routine for creating a decayed reference to a
38/// function.
39static Expr *
40CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn,
41 SourceLocation Loc = SourceLocation()) {
42 Expr *E = new (S.Context) DeclRefExpr(Fn, Fn->getType(), VK_LValue, Loc);
43 S.DefaultFunctionArrayConversion(E);
44 return E;
45}
46
John McCall120d63c2010-08-24 20:38:10 +000047static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
48 bool InOverloadResolution,
49 StandardConversionSequence &SCS);
50static OverloadingResult
51IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
52 UserDefinedConversionSequence& User,
53 OverloadCandidateSet& Conversions,
54 bool AllowExplicit);
55
56
57static ImplicitConversionSequence::CompareKind
58CompareStandardConversionSequences(Sema &S,
59 const StandardConversionSequence& SCS1,
60 const StandardConversionSequence& SCS2);
61
62static ImplicitConversionSequence::CompareKind
63CompareQualificationConversions(Sema &S,
64 const StandardConversionSequence& SCS1,
65 const StandardConversionSequence& SCS2);
66
67static ImplicitConversionSequence::CompareKind
68CompareDerivedToBaseConversions(Sema &S,
69 const StandardConversionSequence& SCS1,
70 const StandardConversionSequence& SCS2);
71
72
73
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000074/// GetConversionCategory - Retrieve the implicit conversion
75/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000076ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000077GetConversionCategory(ImplicitConversionKind Kind) {
78 static const ImplicitConversionCategory
79 Category[(int)ICK_Num_Conversion_Kinds] = {
80 ICC_Identity,
81 ICC_Lvalue_Transformation,
82 ICC_Lvalue_Transformation,
83 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +000084 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000085 ICC_Qualification_Adjustment,
86 ICC_Promotion,
87 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000088 ICC_Promotion,
89 ICC_Conversion,
90 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000091 ICC_Conversion,
92 ICC_Conversion,
93 ICC_Conversion,
94 ICC_Conversion,
95 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000096 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000097 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +000098 ICC_Conversion,
99 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000100 ICC_Conversion
101 };
102 return Category[(int)Kind];
103}
104
105/// GetConversionRank - Retrieve the implicit conversion rank
106/// corresponding to the given implicit conversion kind.
107ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
108 static const ImplicitConversionRank
109 Rank[(int)ICK_Num_Conversion_Kinds] = {
110 ICR_Exact_Match,
111 ICR_Exact_Match,
112 ICR_Exact_Match,
113 ICR_Exact_Match,
114 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000115 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000116 ICR_Promotion,
117 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000118 ICR_Promotion,
119 ICR_Conversion,
120 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000121 ICR_Conversion,
122 ICR_Conversion,
123 ICR_Conversion,
124 ICR_Conversion,
125 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000126 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000127 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000128 ICR_Conversion,
129 ICR_Conversion,
Chandler Carruth23a370f2010-02-25 07:20:54 +0000130 ICR_Complex_Real_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000131 };
132 return Rank[(int)Kind];
133}
134
135/// GetImplicitConversionName - Return the name of this kind of
136/// implicit conversion.
137const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +0000138 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000139 "No conversion",
140 "Lvalue-to-rvalue",
141 "Array-to-pointer",
142 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000143 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000144 "Qualification",
145 "Integral promotion",
146 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000147 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000148 "Integral conversion",
149 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000150 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000151 "Floating-integral conversion",
152 "Pointer conversion",
153 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000154 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000155 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000156 "Derived-to-base conversion",
157 "Vector conversion",
158 "Vector splat",
159 "Complex-real conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000160 };
161 return Name[Kind];
162}
163
Douglas Gregor60d62c22008-10-31 16:23:19 +0000164/// StandardConversionSequence - Set the standard conversion
165/// sequence to the identity conversion.
166void StandardConversionSequence::setAsIdentityConversion() {
167 First = ICK_Identity;
168 Second = ICK_Identity;
169 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000170 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000171 ReferenceBinding = false;
172 DirectBinding = false;
Sebastian Redl85002392009-03-29 22:46:24 +0000173 RRefBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000174 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000175}
176
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000177/// getRank - Retrieve the rank of this standard conversion sequence
178/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
179/// implicit conversions.
180ImplicitConversionRank StandardConversionSequence::getRank() const {
181 ImplicitConversionRank Rank = ICR_Exact_Match;
182 if (GetConversionRank(First) > Rank)
183 Rank = GetConversionRank(First);
184 if (GetConversionRank(Second) > Rank)
185 Rank = GetConversionRank(Second);
186 if (GetConversionRank(Third) > Rank)
187 Rank = GetConversionRank(Third);
188 return Rank;
189}
190
191/// isPointerConversionToBool - Determines whether this conversion is
192/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000193/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000194/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000195bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000196 // Note that FromType has not necessarily been transformed by the
197 // array-to-pointer or function-to-pointer implicit conversions, so
198 // check for their presence as well as checking whether FromType is
199 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000200 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000201 (getFromType()->isPointerType() ||
202 getFromType()->isObjCObjectPointerType() ||
203 getFromType()->isBlockPointerType() ||
Anders Carlssonc8df0b62010-11-05 00:12:09 +0000204 getFromType()->isNullPtrType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000205 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
206 return true;
207
208 return false;
209}
210
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000211/// isPointerConversionToVoidPointer - Determines whether this
212/// conversion is a conversion of a pointer to a void pointer. This is
213/// used as part of the ranking of standard conversion sequences (C++
214/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000215bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000216StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000217isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000218 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000219 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000220
221 // Note that FromType has not necessarily been transformed by the
222 // array-to-pointer implicit conversion, so check for its presence
223 // and redo the conversion to get a pointer.
224 if (First == ICK_Array_To_Pointer)
225 FromType = Context.getArrayDecayedType(FromType);
226
John McCall202422e2010-10-26 06:40:27 +0000227 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000228 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000229 return ToPtrType->getPointeeType()->isVoidType();
230
231 return false;
232}
233
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000234/// DebugPrint - Print this standard conversion sequence to standard
235/// error. Useful for debugging overloading issues.
236void StandardConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000237 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000238 bool PrintedSomething = false;
239 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000240 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000241 PrintedSomething = true;
242 }
243
244 if (Second != ICK_Identity) {
245 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000246 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000247 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000248 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000249
250 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000251 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000252 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000253 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000254 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000255 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000256 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000257 PrintedSomething = true;
258 }
259
260 if (Third != ICK_Identity) {
261 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000262 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000263 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000264 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000265 PrintedSomething = true;
266 }
267
268 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000269 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000270 }
271}
272
273/// DebugPrint - Print this user-defined conversion sequence to standard
274/// error. Useful for debugging overloading issues.
275void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000276 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000277 if (Before.First || Before.Second || Before.Third) {
278 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000279 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000280 }
Benjamin Kramer900fc632010-04-17 09:33:03 +0000281 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000282 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000283 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000284 After.DebugPrint();
285 }
286}
287
288/// DebugPrint - Print this implicit conversion sequence to standard
289/// error. Useful for debugging overloading issues.
290void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000291 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000292 switch (ConversionKind) {
293 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000294 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000295 Standard.DebugPrint();
296 break;
297 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000298 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000299 UserDefined.DebugPrint();
300 break;
301 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000302 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000303 break;
John McCall1d318332010-01-12 00:44:57 +0000304 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000305 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000306 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000307 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000308 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000309 break;
310 }
311
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000312 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000313}
314
John McCall1d318332010-01-12 00:44:57 +0000315void AmbiguousConversionSequence::construct() {
316 new (&conversions()) ConversionSet();
317}
318
319void AmbiguousConversionSequence::destruct() {
320 conversions().~ConversionSet();
321}
322
323void
324AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
325 FromTypePtr = O.FromTypePtr;
326 ToTypePtr = O.ToTypePtr;
327 new (&conversions()) ConversionSet(O.conversions());
328}
329
Douglas Gregora9333192010-05-08 17:41:32 +0000330namespace {
331 // Structure used by OverloadCandidate::DeductionFailureInfo to store
332 // template parameter and template argument information.
333 struct DFIParamWithArguments {
334 TemplateParameter Param;
335 TemplateArgument FirstArg;
336 TemplateArgument SecondArg;
337 };
338}
339
340/// \brief Convert from Sema's representation of template deduction information
341/// to the form used in overload-candidate information.
342OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000343static MakeDeductionFailureInfo(ASTContext &Context,
344 Sema::TemplateDeductionResult TDK,
John McCall2a7fb272010-08-25 05:32:35 +0000345 TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000346 OverloadCandidate::DeductionFailureInfo Result;
347 Result.Result = static_cast<unsigned>(TDK);
348 Result.Data = 0;
349 switch (TDK) {
350 case Sema::TDK_Success:
351 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000352 case Sema::TDK_TooManyArguments:
353 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000354 break;
355
356 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000357 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000358 Result.Data = Info.Param.getOpaqueValue();
359 break;
360
Douglas Gregora9333192010-05-08 17:41:32 +0000361 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000362 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000363 // FIXME: Should allocate from normal heap so that we can free this later.
364 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000365 Saved->Param = Info.Param;
366 Saved->FirstArg = Info.FirstArg;
367 Saved->SecondArg = Info.SecondArg;
368 Result.Data = Saved;
369 break;
370 }
371
372 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000373 Result.Data = Info.take();
374 break;
375
Douglas Gregora9333192010-05-08 17:41:32 +0000376 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000377 case Sema::TDK_FailedOverloadResolution:
378 break;
379 }
380
381 return Result;
382}
John McCall1d318332010-01-12 00:44:57 +0000383
Douglas Gregora9333192010-05-08 17:41:32 +0000384void OverloadCandidate::DeductionFailureInfo::Destroy() {
385 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
386 case Sema::TDK_Success:
387 case Sema::TDK_InstantiationDepth:
388 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000389 case Sema::TDK_TooManyArguments:
390 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000391 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000392 break;
393
Douglas Gregora9333192010-05-08 17:41:32 +0000394 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000395 case Sema::TDK_Underqualified:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000396 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000397 Data = 0;
398 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000399
400 case Sema::TDK_SubstitutionFailure:
401 // FIXME: Destroy the template arugment list?
402 Data = 0;
403 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000404
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000405 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000406 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000407 case Sema::TDK_FailedOverloadResolution:
408 break;
409 }
410}
411
412TemplateParameter
413OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
414 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
415 case Sema::TDK_Success:
416 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000417 case Sema::TDK_TooManyArguments:
418 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000419 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000420 return TemplateParameter();
421
422 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000423 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000424 return TemplateParameter::getFromOpaqueValue(Data);
425
426 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000427 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000428 return static_cast<DFIParamWithArguments*>(Data)->Param;
429
430 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000431 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000432 case Sema::TDK_FailedOverloadResolution:
433 break;
434 }
435
436 return TemplateParameter();
437}
Douglas Gregorec20f462010-05-08 20:07:26 +0000438
439TemplateArgumentList *
440OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
441 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
442 case Sema::TDK_Success:
443 case Sema::TDK_InstantiationDepth:
444 case Sema::TDK_TooManyArguments:
445 case Sema::TDK_TooFewArguments:
446 case Sema::TDK_Incomplete:
447 case Sema::TDK_InvalidExplicitArguments:
448 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000449 case Sema::TDK_Underqualified:
Douglas Gregorec20f462010-05-08 20:07:26 +0000450 return 0;
451
452 case Sema::TDK_SubstitutionFailure:
453 return static_cast<TemplateArgumentList*>(Data);
454
455 // Unhandled
456 case Sema::TDK_NonDeducedMismatch:
457 case Sema::TDK_FailedOverloadResolution:
458 break;
459 }
460
461 return 0;
462}
463
Douglas Gregora9333192010-05-08 17:41:32 +0000464const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
465 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
466 case Sema::TDK_Success:
467 case Sema::TDK_InstantiationDepth:
468 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000469 case Sema::TDK_TooManyArguments:
470 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000471 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000472 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000473 return 0;
474
Douglas Gregora9333192010-05-08 17:41:32 +0000475 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000476 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000477 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
478
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000479 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000480 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000481 case Sema::TDK_FailedOverloadResolution:
482 break;
483 }
484
485 return 0;
486}
487
488const TemplateArgument *
489OverloadCandidate::DeductionFailureInfo::getSecondArg() {
490 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
491 case Sema::TDK_Success:
492 case Sema::TDK_InstantiationDepth:
493 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000494 case Sema::TDK_TooManyArguments:
495 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000496 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000497 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000498 return 0;
499
Douglas Gregora9333192010-05-08 17:41:32 +0000500 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000501 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000502 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
503
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000504 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000505 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000506 case Sema::TDK_FailedOverloadResolution:
507 break;
508 }
509
510 return 0;
511}
512
513void OverloadCandidateSet::clear() {
Douglas Gregora9333192010-05-08 17:41:32 +0000514 inherited::clear();
515 Functions.clear();
516}
517
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000518// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000519// overload of the declarations in Old. This routine returns false if
520// New and Old cannot be overloaded, e.g., if New has the same
521// signature as some function in Old (C++ 1.3.10) or if the Old
522// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000523// it does return false, MatchedDecl will point to the decl that New
524// cannot be overloaded with. This decl may be a UsingShadowDecl on
525// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000526//
527// Example: Given the following input:
528//
529// void f(int, float); // #1
530// void f(int, int); // #2
531// int f(int, int); // #3
532//
533// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000534// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000535//
John McCall51fa86f2009-12-02 08:47:38 +0000536// When we process #2, Old contains only the FunctionDecl for #1. By
537// comparing the parameter types, we see that #1 and #2 are overloaded
538// (since they have different signatures), so this routine returns
539// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000540//
John McCall51fa86f2009-12-02 08:47:38 +0000541// When we process #3, Old is an overload set containing #1 and #2. We
542// compare the signatures of #3 to #1 (they're overloaded, so we do
543// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
544// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000545// signature), IsOverload returns false and MatchedDecl will be set to
546// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000547//
548// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
549// into a class by a using declaration. The rules for whether to hide
550// shadow declarations ignore some properties which otherwise figure
551// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000552Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000553Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
554 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000555 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000556 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000557 NamedDecl *OldD = *I;
558
559 bool OldIsUsingDecl = false;
560 if (isa<UsingShadowDecl>(OldD)) {
561 OldIsUsingDecl = true;
562
563 // We can always introduce two using declarations into the same
564 // context, even if they have identical signatures.
565 if (NewIsUsingDecl) continue;
566
567 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
568 }
569
570 // If either declaration was introduced by a using declaration,
571 // we'll need to use slightly different rules for matching.
572 // Essentially, these rules are the normal rules, except that
573 // function templates hide function templates with different
574 // return types or template parameter lists.
575 bool UseMemberUsingDeclRules =
576 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
577
John McCall51fa86f2009-12-02 08:47:38 +0000578 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000579 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
580 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
581 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
582 continue;
583 }
584
John McCall871b2e72009-12-09 03:35:25 +0000585 Match = *I;
586 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000587 }
John McCall51fa86f2009-12-02 08:47:38 +0000588 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000589 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
590 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
591 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
592 continue;
593 }
594
John McCall871b2e72009-12-09 03:35:25 +0000595 Match = *I;
596 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000597 }
John McCalld7945c62010-11-10 03:01:53 +0000598 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000599 // We can overload with these, which can show up when doing
600 // redeclaration checks for UsingDecls.
601 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000602 } else if (isa<TagDecl>(OldD)) {
603 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000604 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
605 // Optimistically assume that an unresolved using decl will
606 // overload; if it doesn't, we'll have to diagnose during
607 // template instantiation.
608 } else {
John McCall68263142009-11-18 22:49:29 +0000609 // (C++ 13p1):
610 // Only function declarations can be overloaded; object and type
611 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000612 Match = *I;
613 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000614 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000615 }
John McCall68263142009-11-18 22:49:29 +0000616
John McCall871b2e72009-12-09 03:35:25 +0000617 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000618}
619
John McCallad00b772010-06-16 08:42:20 +0000620bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
621 bool UseUsingDeclRules) {
John McCall7b492022010-08-12 07:09:11 +0000622 // If both of the functions are extern "C", then they are not
623 // overloads.
624 if (Old->isExternC() && New->isExternC())
625 return false;
626
John McCall68263142009-11-18 22:49:29 +0000627 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
628 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
629
630 // C++ [temp.fct]p2:
631 // A function template can be overloaded with other function templates
632 // and with normal (non-template) functions.
633 if ((OldTemplate == 0) != (NewTemplate == 0))
634 return true;
635
636 // Is the function New an overload of the function Old?
637 QualType OldQType = Context.getCanonicalType(Old->getType());
638 QualType NewQType = Context.getCanonicalType(New->getType());
639
640 // Compare the signatures (C++ 1.3.10) of the two functions to
641 // determine whether they are overloads. If we find any mismatch
642 // in the signature, they are overloads.
643
644 // If either of these functions is a K&R-style function (no
645 // prototype), then we consider them to have matching signatures.
646 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
647 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
648 return false;
649
650 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
651 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
652
653 // The signature of a function includes the types of its
654 // parameters (C++ 1.3.10), which includes the presence or absence
655 // of the ellipsis; see C++ DR 357).
656 if (OldQType != NewQType &&
657 (OldType->getNumArgs() != NewType->getNumArgs() ||
658 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000659 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000660 return true;
661
662 // C++ [temp.over.link]p4:
663 // The signature of a function template consists of its function
664 // signature, its return type and its template parameter list. The names
665 // of the template parameters are significant only for establishing the
666 // relationship between the template parameters and the rest of the
667 // signature.
668 //
669 // We check the return type and template parameter lists for function
670 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +0000671 //
672 // However, we don't consider either of these when deciding whether
673 // a member introduced by a shadow declaration is hidden.
674 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +0000675 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
676 OldTemplate->getTemplateParameters(),
677 false, TPL_TemplateMatch) ||
678 OldType->getResultType() != NewType->getResultType()))
679 return true;
680
681 // If the function is a class member, its signature includes the
682 // cv-qualifiers (if any) on the function itself.
683 //
684 // As part of this, also check whether one of the member functions
685 // is static, in which case they are not overloads (C++
686 // 13.1p2). While not part of the definition of the signature,
687 // this check is important to determine whether these functions
688 // can be overloaded.
689 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
690 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
691 if (OldMethod && NewMethod &&
692 !OldMethod->isStatic() && !NewMethod->isStatic() &&
693 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
694 return true;
695
696 // The signatures match; this is not an overload.
697 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000698}
699
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000700/// TryImplicitConversion - Attempt to perform an implicit conversion
701/// from the given expression (Expr) to the given type (ToType). This
702/// function returns an implicit conversion sequence that can be used
703/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000704///
705/// void f(float f);
706/// void g(int i) { f(i); }
707///
708/// this routine would produce an implicit conversion sequence to
709/// describe the initialization of f from i, which will be a standard
710/// conversion sequence containing an lvalue-to-rvalue conversion (C++
711/// 4.1) followed by a floating-integral conversion (C++ 4.9).
712//
713/// Note that this routine only determines how the conversion can be
714/// performed; it does not actually perform the conversion. As such,
715/// it will not produce any diagnostics if no conversion is available,
716/// but will instead return an implicit conversion sequence of kind
717/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000718///
719/// If @p SuppressUserConversions, then user-defined conversions are
720/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000721/// If @p AllowExplicit, then explicit user-defined conversions are
722/// permitted.
John McCall120d63c2010-08-24 20:38:10 +0000723static ImplicitConversionSequence
724TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
725 bool SuppressUserConversions,
726 bool AllowExplicit,
727 bool InOverloadResolution) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000728 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +0000729 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
730 ICS.Standard)) {
John McCall1d318332010-01-12 00:44:57 +0000731 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +0000732 return ICS;
733 }
734
John McCall120d63c2010-08-24 20:38:10 +0000735 if (!S.getLangOptions().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +0000736 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +0000737 return ICS;
738 }
739
Douglas Gregor604eb652010-08-11 02:15:33 +0000740 // C++ [over.ics.user]p4:
741 // A conversion of an expression of class type to the same class
742 // type is given Exact Match rank, and a conversion of an
743 // expression of class type to a base class of that type is
744 // given Conversion rank, in spite of the fact that a copy/move
745 // constructor (i.e., a user-defined conversion function) is
746 // called for those cases.
747 QualType FromType = From->getType();
748 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +0000749 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
750 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000751 ICS.setStandard();
752 ICS.Standard.setAsIdentityConversion();
753 ICS.Standard.setFromType(FromType);
754 ICS.Standard.setAllToTypes(ToType);
755
756 // We don't actually check at this point whether there is a valid
757 // copy/move constructor, since overloading just assumes that it
758 // exists. When we actually perform initialization, we'll find the
759 // appropriate constructor to copy the returned object, if needed.
760 ICS.Standard.CopyConstructor = 0;
Douglas Gregor604eb652010-08-11 02:15:33 +0000761
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000762 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +0000763 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000764 ICS.Standard.Second = ICK_Derived_To_Base;
Douglas Gregor604eb652010-08-11 02:15:33 +0000765
766 return ICS;
767 }
768
769 if (SuppressUserConversions) {
770 // We're not in the case above, so there is no conversion that
771 // we can perform.
772 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000773 return ICS;
774 }
775
776 // Attempt user-defined conversion.
John McCall5769d612010-02-08 23:07:23 +0000777 OverloadCandidateSet Conversions(From->getExprLoc());
778 OverloadingResult UserDefResult
John McCall120d63c2010-08-24 20:38:10 +0000779 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000780 AllowExplicit);
John McCall5769d612010-02-08 23:07:23 +0000781
782 if (UserDefResult == OR_Success) {
John McCall1d318332010-01-12 00:44:57 +0000783 ICS.setUserDefined();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000784 // C++ [over.ics.user]p4:
785 // A conversion of an expression of class type to the same class
786 // type is given Exact Match rank, and a conversion of an
787 // expression of class type to a base class of that type is
788 // given Conversion rank, in spite of the fact that a copy
789 // constructor (i.e., a user-defined conversion function) is
790 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000791 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000792 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000793 QualType FromCanon
John McCall120d63c2010-08-24 20:38:10 +0000794 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
795 QualType ToCanon
796 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor9e9199d2009-12-22 00:34:07 +0000797 if (Constructor->isCopyConstructor() &&
John McCall120d63c2010-08-24 20:38:10 +0000798 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000799 // Turn this into a "standard" conversion sequence, so that it
800 // gets ranked with standard conversion sequences.
John McCall1d318332010-01-12 00:44:57 +0000801 ICS.setStandard();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000802 ICS.Standard.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +0000803 ICS.Standard.setFromType(From->getType());
Douglas Gregorad323a82010-01-27 03:51:04 +0000804 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000805 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000806 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000807 ICS.Standard.Second = ICK_Derived_To_Base;
808 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000809 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000810
811 // C++ [over.best.ics]p4:
812 // However, when considering the argument of a user-defined
813 // conversion function that is a candidate by 13.3.1.3 when
814 // invoked for the copying of the temporary in the second step
815 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
816 // 13.3.1.6 in all cases, only standard conversion sequences and
817 // ellipsis conversion sequences are allowed.
John McCalladbb8f82010-01-13 09:16:55 +0000818 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCallb1bdc622010-02-25 01:37:24 +0000819 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCalladbb8f82010-01-13 09:16:55 +0000820 }
John McCallcefd3ad2010-01-13 22:30:33 +0000821 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall1d318332010-01-12 00:44:57 +0000822 ICS.setAmbiguous();
823 ICS.Ambiguous.setFromType(From->getType());
824 ICS.Ambiguous.setToType(ToType);
825 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
826 Cand != Conversions.end(); ++Cand)
827 if (Cand->Viable)
828 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000829 } else {
John McCallb1bdc622010-02-25 01:37:24 +0000830 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000831 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000832
833 return ICS;
834}
835
John McCall120d63c2010-08-24 20:38:10 +0000836bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
837 const InitializedEntity &Entity,
838 Expr *Initializer,
839 bool SuppressUserConversions,
840 bool AllowExplicitConversions,
841 bool InOverloadResolution) {
842 ImplicitConversionSequence ICS
843 = clang::TryImplicitConversion(*this, Initializer, Entity.getType(),
844 SuppressUserConversions,
845 AllowExplicitConversions,
846 InOverloadResolution);
847 if (ICS.isBad()) return true;
848
849 // Perform the actual conversion.
850 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
851 return false;
852}
853
Douglas Gregor575c63a2010-04-16 22:27:05 +0000854/// PerformImplicitConversion - Perform an implicit conversion of the
855/// expression From to the type ToType. Returns true if there was an
856/// error, false otherwise. The expression From is replaced with the
857/// converted expression. Flavor is the kind of conversion we're
858/// performing, used in the error message. If @p AllowExplicit,
859/// explicit user-defined conversions are permitted.
860bool
861Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
862 AssignmentAction Action, bool AllowExplicit) {
863 ImplicitConversionSequence ICS;
864 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
865}
866
867bool
868Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
869 AssignmentAction Action, bool AllowExplicit,
870 ImplicitConversionSequence& ICS) {
John McCall120d63c2010-08-24 20:38:10 +0000871 ICS = clang::TryImplicitConversion(*this, From, ToType,
872 /*SuppressUserConversions=*/false,
873 AllowExplicit,
874 /*InOverloadResolution=*/false);
Douglas Gregor575c63a2010-04-16 22:27:05 +0000875 return PerformImplicitConversion(From, ToType, ICS, Action);
876}
877
Douglas Gregor43c79c22009-12-09 00:47:37 +0000878/// \brief Determine whether the conversion from FromType to ToType is a valid
879/// conversion that strips "noreturn" off the nested function type.
880static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
881 QualType ToType, QualType &ResultTy) {
882 if (Context.hasSameUnqualifiedType(FromType, ToType))
883 return false;
884
John McCall00ccbef2010-12-21 00:44:39 +0000885 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
886 // where F adds one of the following at most once:
887 // - a pointer
888 // - a member pointer
889 // - a block pointer
890 CanQualType CanTo = Context.getCanonicalType(ToType);
891 CanQualType CanFrom = Context.getCanonicalType(FromType);
892 Type::TypeClass TyClass = CanTo->getTypeClass();
893 if (TyClass != CanFrom->getTypeClass()) return false;
894 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
895 if (TyClass == Type::Pointer) {
896 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
897 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
898 } else if (TyClass == Type::BlockPointer) {
899 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
900 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
901 } else if (TyClass == Type::MemberPointer) {
902 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
903 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
904 } else {
905 return false;
906 }
Douglas Gregor43c79c22009-12-09 00:47:37 +0000907
John McCall00ccbef2010-12-21 00:44:39 +0000908 TyClass = CanTo->getTypeClass();
909 if (TyClass != CanFrom->getTypeClass()) return false;
910 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
911 return false;
912 }
913
914 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
915 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
916 if (!EInfo.getNoReturn()) return false;
917
918 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
919 assert(QualType(FromFn, 0).isCanonical());
920 if (QualType(FromFn, 0) != CanTo) return false;
921
922 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +0000923 return true;
924}
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000925
926/// \brief Determine whether the conversion from FromType to ToType is a valid
927/// vector conversion.
928///
929/// \param ICK Will be set to the vector conversion kind, if this is a vector
930/// conversion.
931static bool IsVectorConversion(ASTContext &Context, QualType FromType,
932 QualType ToType, ImplicitConversionKind &ICK) {
933 // We need at least one of these types to be a vector type to have a vector
934 // conversion.
935 if (!ToType->isVectorType() && !FromType->isVectorType())
936 return false;
937
938 // Identical types require no conversions.
939 if (Context.hasSameUnqualifiedType(FromType, ToType))
940 return false;
941
942 // There are no conversions between extended vector types, only identity.
943 if (ToType->isExtVectorType()) {
944 // There are no conversions between extended vector types other than the
945 // identity conversion.
946 if (FromType->isExtVectorType())
947 return false;
948
949 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +0000950 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000951 ICK = ICK_Vector_Splat;
952 return true;
953 }
954 }
Douglas Gregor255210e2010-08-06 10:14:59 +0000955
956 // We can perform the conversion between vector types in the following cases:
957 // 1)vector types are equivalent AltiVec and GCC vector types
958 // 2)lax vector conversions are permitted and the vector types are of the
959 // same size
960 if (ToType->isVectorType() && FromType->isVectorType()) {
961 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruthc45eb9c2010-08-08 05:02:51 +0000962 (Context.getLangOptions().LaxVectorConversions &&
963 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +0000964 ICK = ICK_Vector_Conversion;
965 return true;
966 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000967 }
Douglas Gregor255210e2010-08-06 10:14:59 +0000968
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000969 return false;
970}
Douglas Gregor43c79c22009-12-09 00:47:37 +0000971
Douglas Gregor60d62c22008-10-31 16:23:19 +0000972/// IsStandardConversion - Determines whether there is a standard
973/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
974/// expression From to the type ToType. Standard conversion sequences
975/// only consider non-class types; for conversions that involve class
976/// types, use TryImplicitConversion. If a conversion exists, SCS will
977/// contain the standard conversion sequence required to perform this
978/// conversion and this routine will return true. Otherwise, this
979/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +0000980static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
981 bool InOverloadResolution,
982 StandardConversionSequence &SCS) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000983 QualType FromType = From->getType();
John McCall120d63c2010-08-24 20:38:10 +0000984
Douglas Gregor60d62c22008-10-31 16:23:19 +0000985 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000986 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +0000987 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000988 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +0000989 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000990 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000991
Douglas Gregorf9201e02009-02-11 23:02:49 +0000992 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +0000993 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +0000994 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall120d63c2010-08-24 20:38:10 +0000995 if (S.getLangOptions().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000996 return false;
997
Mike Stump1eb44332009-09-09 15:08:12 +0000998 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000999 }
1000
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001001 // The first conversion can be an lvalue-to-rvalue conversion,
1002 // array-to-pointer conversion, or function-to-pointer conversion
1003 // (C++ 4p1).
1004
John McCall120d63c2010-08-24 20:38:10 +00001005 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001006 DeclAccessPair AccessPair;
1007 if (FunctionDecl *Fn
John McCall120d63c2010-08-24 20:38:10 +00001008 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1009 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001010 // We were able to resolve the address of the overloaded function,
1011 // so we can convert to the type of that function.
1012 FromType = Fn->getType();
1013 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
1014 if (!Method->isStatic()) {
1015 Type *ClassType
John McCall120d63c2010-08-24 20:38:10 +00001016 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1017 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001018 }
1019 }
1020
1021 // If the "from" expression takes the address of the overloaded
1022 // function, update the type of the resulting expression accordingly.
1023 if (FromType->getAs<FunctionType>())
1024 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
John McCall2de56d12010-08-25 11:45:40 +00001025 if (UnOp->getOpcode() == UO_AddrOf)
John McCall120d63c2010-08-24 20:38:10 +00001026 FromType = S.Context.getPointerType(FromType);
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001027
1028 // Check that we've computed the proper type after overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00001029 assert(S.Context.hasSameType(FromType,
1030 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001031 } else {
1032 return false;
1033 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001034 }
Mike Stump1eb44332009-09-09 15:08:12 +00001035 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001036 // An lvalue (3.10) of a non-function, non-array type T can be
1037 // converted to an rvalue.
John McCall7eb0a9e2010-11-24 05:12:34 +00001038 bool argIsLValue = From->isLValue();
1039 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001040 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001041 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001042 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001043
1044 // If T is a non-class type, the type of the rvalue is the
1045 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001046 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1047 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001048 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001049 } else if (FromType->isArrayType()) {
1050 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001051 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001052
1053 // An lvalue or rvalue of type "array of N T" or "array of unknown
1054 // bound of T" can be converted to an rvalue of type "pointer to
1055 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001056 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001057
John McCall120d63c2010-08-24 20:38:10 +00001058 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001059 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001060 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001061
1062 // For the purpose of ranking in overload resolution
1063 // (13.3.3.1.1), this conversion is considered an
1064 // array-to-pointer conversion followed by a qualification
1065 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001066 SCS.Second = ICK_Identity;
1067 SCS.Third = ICK_Qualification;
Douglas Gregorad323a82010-01-27 03:51:04 +00001068 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001069 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001070 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001071 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001072 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001073 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001074
1075 // An lvalue of function type T can be converted to an rvalue of
1076 // type "pointer to T." The result is a pointer to the
1077 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001078 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001079 } else {
1080 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001081 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001082 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001083 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001084
1085 // The second conversion can be an integral promotion, floating
1086 // point promotion, integral conversion, floating point conversion,
1087 // floating-integral conversion, pointer conversion,
1088 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001089 // For overloading in C, this can also be a "compatible-type"
1090 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001091 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001092 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001093 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001094 // The unqualified versions of the types are the same: there's no
1095 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001096 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001097 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001098 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001099 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001100 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001101 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001102 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001103 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001104 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001105 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001106 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001107 SCS.Second = ICK_Complex_Promotion;
1108 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001109 } else if (ToType->isBooleanType() &&
1110 (FromType->isArithmeticType() ||
1111 FromType->isAnyPointerType() ||
1112 FromType->isBlockPointerType() ||
1113 FromType->isMemberPointerType() ||
1114 FromType->isNullPtrType())) {
1115 // Boolean conversions (C++ 4.12).
1116 SCS.Second = ICK_Boolean_Conversion;
1117 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001118 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001119 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001120 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001121 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001122 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001123 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001124 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001125 SCS.Second = ICK_Complex_Conversion;
1126 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001127 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1128 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001129 // Complex-real conversions (C99 6.3.1.7)
1130 SCS.Second = ICK_Complex_Real;
1131 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001132 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001133 // Floating point conversions (C++ 4.8).
1134 SCS.Second = ICK_Floating_Conversion;
1135 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001136 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001137 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001138 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001139 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001140 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001141 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001142 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001143 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1144 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001145 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001146 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001147 SCS.IncompatibleObjC = IncompatibleObjC;
John McCall120d63c2010-08-24 20:38:10 +00001148 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1149 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001150 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001151 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001152 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001153 SCS.Second = SecondICK;
1154 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001155 } else if (!S.getLangOptions().CPlusPlus &&
1156 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001157 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001158 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001159 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001160 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001161 // Treat a conversion that strips "noreturn" as an identity conversion.
1162 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001163 } else {
1164 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001165 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001166 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001167 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001168
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001169 QualType CanonFrom;
1170 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001171 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall120d63c2010-08-24 20:38:10 +00001172 if (S.IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001173 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001174 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001175 CanonFrom = S.Context.getCanonicalType(FromType);
1176 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001177 } else {
1178 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001179 SCS.Third = ICK_Identity;
1180
Mike Stump1eb44332009-09-09 15:08:12 +00001181 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001182 // [...] Any difference in top-level cv-qualification is
1183 // subsumed by the initialization itself and does not constitute
1184 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001185 CanonFrom = S.Context.getCanonicalType(FromType);
1186 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00001187 if (CanonFrom.getLocalUnqualifiedType()
1188 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001189 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1190 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001191 FromType = ToType;
1192 CanonFrom = CanonTo;
1193 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001194 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001195 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001196
1197 // If we have not converted the argument type to the parameter type,
1198 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001199 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001200 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001201
Douglas Gregor60d62c22008-10-31 16:23:19 +00001202 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001203}
1204
1205/// IsIntegralPromotion - Determines whether the conversion from the
1206/// expression From (whose potentially-adjusted type is FromType) to
1207/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1208/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001209bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001210 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001211 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001212 if (!To) {
1213 return false;
1214 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001215
1216 // An rvalue of type char, signed char, unsigned char, short int, or
1217 // unsigned short int can be converted to an rvalue of type int if
1218 // int can represent all the values of the source type; otherwise,
1219 // the source rvalue can be converted to an rvalue of type unsigned
1220 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001221 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1222 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001223 if (// We can promote any signed, promotable integer type to an int
1224 (FromType->isSignedIntegerType() ||
1225 // We can promote any unsigned integer type whose size is
1226 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001227 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001228 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001229 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001230 }
1231
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001232 return To->getKind() == BuiltinType::UInt;
1233 }
1234
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001235 // C++0x [conv.prom]p3:
1236 // A prvalue of an unscoped enumeration type whose underlying type is not
1237 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1238 // following types that can represent all the values of the enumeration
1239 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1240 // unsigned int, long int, unsigned long int, long long int, or unsigned
1241 // long long int. If none of the types in that list can represent all the
1242 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1243 // type can be converted to an rvalue a prvalue of the extended integer type
1244 // with lowest integer conversion rank (4.13) greater than the rank of long
1245 // long in which all the values of the enumeration can be represented. If
1246 // there are two such extended types, the signed one is chosen.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001247 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1248 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1249 // provided for a scoped enumeration.
1250 if (FromEnumType->getDecl()->isScoped())
1251 return false;
1252
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001253 // We have already pre-calculated the promotion type, so this is trivial.
Douglas Gregor5dde1602010-09-12 03:38:25 +00001254 if (ToType->isIntegerType() &&
1255 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall842aef82009-12-09 09:09:27 +00001256 return Context.hasSameUnqualifiedType(ToType,
1257 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001258 }
John McCall842aef82009-12-09 09:09:27 +00001259
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001260 // C++0x [conv.prom]p2:
1261 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1262 // to an rvalue a prvalue of the first of the following types that can
1263 // represent all the values of its underlying type: int, unsigned int,
1264 // long int, unsigned long int, long long int, or unsigned long long int.
1265 // If none of the types in that list can represent all the values of its
1266 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
1267 // or wchar_t can be converted to an rvalue a prvalue of its underlying
1268 // type.
1269 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1270 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001271 // Determine whether the type we're converting from is signed or
1272 // unsigned.
1273 bool FromIsSigned;
1274 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall842aef82009-12-09 09:09:27 +00001275
1276 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1277 FromIsSigned = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001278
1279 // The types we'll try to promote to, in the appropriate
1280 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001281 QualType PromoteTypes[6] = {
1282 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001283 Context.LongTy, Context.UnsignedLongTy ,
1284 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001285 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001286 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001287 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1288 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001289 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001290 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1291 // We found the type that we can promote to. If this is the
1292 // type we wanted, we have a promotion. Otherwise, no
1293 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001294 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001295 }
1296 }
1297 }
1298
1299 // An rvalue for an integral bit-field (9.6) can be converted to an
1300 // rvalue of type int if int can represent all the values of the
1301 // bit-field; otherwise, it can be converted to unsigned int if
1302 // unsigned int can represent all the values of the bit-field. If
1303 // the bit-field is larger yet, no integral promotion applies to
1304 // it. If the bit-field has an enumerated type, it is treated as any
1305 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001306 // FIXME: We should delay checking of bit-fields until we actually perform the
1307 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001308 using llvm::APSInt;
1309 if (From)
1310 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001311 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001312 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001313 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1314 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1315 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001316
Douglas Gregor86f19402008-12-20 23:49:58 +00001317 // Are we promoting to an int from a bitfield that fits in an int?
1318 if (BitWidth < ToSize ||
1319 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1320 return To->getKind() == BuiltinType::Int;
1321 }
Mike Stump1eb44332009-09-09 15:08:12 +00001322
Douglas Gregor86f19402008-12-20 23:49:58 +00001323 // Are we promoting to an unsigned int from an unsigned bitfield
1324 // that fits into an unsigned int?
1325 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1326 return To->getKind() == BuiltinType::UInt;
1327 }
Mike Stump1eb44332009-09-09 15:08:12 +00001328
Douglas Gregor86f19402008-12-20 23:49:58 +00001329 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001330 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001331 }
Mike Stump1eb44332009-09-09 15:08:12 +00001332
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001333 // An rvalue of type bool can be converted to an rvalue of type int,
1334 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001335 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001336 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001337 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001338
1339 return false;
1340}
1341
1342/// IsFloatingPointPromotion - Determines whether the conversion from
1343/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1344/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001345bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001346 /// An rvalue of type float can be converted to an rvalue of type
1347 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +00001348 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1349 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001350 if (FromBuiltin->getKind() == BuiltinType::Float &&
1351 ToBuiltin->getKind() == BuiltinType::Double)
1352 return true;
1353
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001354 // C99 6.3.1.5p1:
1355 // When a float is promoted to double or long double, or a
1356 // double is promoted to long double [...].
1357 if (!getLangOptions().CPlusPlus &&
1358 (FromBuiltin->getKind() == BuiltinType::Float ||
1359 FromBuiltin->getKind() == BuiltinType::Double) &&
1360 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1361 return true;
1362 }
1363
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001364 return false;
1365}
1366
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001367/// \brief Determine if a conversion is a complex promotion.
1368///
1369/// A complex promotion is defined as a complex -> complex conversion
1370/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001371/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001372bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001373 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001374 if (!FromComplex)
1375 return false;
1376
John McCall183700f2009-09-21 23:43:11 +00001377 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001378 if (!ToComplex)
1379 return false;
1380
1381 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001382 ToComplex->getElementType()) ||
1383 IsIntegralPromotion(0, FromComplex->getElementType(),
1384 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001385}
1386
Douglas Gregorcb7de522008-11-26 23:31:11 +00001387/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1388/// the pointer type FromPtr to a pointer to type ToPointee, with the
1389/// same type qualifiers as FromPtr has on its pointee type. ToType,
1390/// if non-empty, will be a pointer to ToType that may or may not have
1391/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +00001392static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001393BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001394 QualType ToPointee, QualType ToType,
1395 ASTContext &Context) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001396 assert((FromPtr->getTypeClass() == Type::Pointer ||
1397 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1398 "Invalid similarly-qualified pointer type");
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001399
1400 /// \brief Conversions to 'id' subsume cv-qualifier conversions.
1401 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1402 return ToType.getUnqualifiedType();
1403
Douglas Gregorda80f742010-12-01 21:43:58 +00001404 QualType CanonFromPointee
1405 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001406 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001407 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001408
1409 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001410 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001411 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001412 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001413 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001414
1415 // Build a pointer to ToPointee. It has the right qualifiers
1416 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001417 if (isa<ObjCObjectPointerType>(ToType))
1418 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001419 return Context.getPointerType(ToPointee);
1420 }
1421
1422 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001423 QualType QualifiedCanonToPointee
1424 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001425
Douglas Gregorda80f742010-12-01 21:43:58 +00001426 if (isa<ObjCObjectPointerType>(ToType))
1427 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1428 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001429}
1430
Mike Stump1eb44332009-09-09 15:08:12 +00001431static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001432 bool InOverloadResolution,
1433 ASTContext &Context) {
1434 // Handle value-dependent integral null pointer constants correctly.
1435 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1436 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001437 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001438 return !InOverloadResolution;
1439
Douglas Gregorce940492009-09-25 04:25:58 +00001440 return Expr->isNullPointerConstant(Context,
1441 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1442 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001443}
Mike Stump1eb44332009-09-09 15:08:12 +00001444
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001445/// IsPointerConversion - Determines whether the conversion of the
1446/// expression From, which has the (possibly adjusted) type FromType,
1447/// can be converted to the type ToType via a pointer conversion (C++
1448/// 4.10). If so, returns true and places the converted type (that
1449/// might differ from ToType in its cv-qualifiers at some level) into
1450/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001451///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001452/// This routine also supports conversions to and from block pointers
1453/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1454/// pointers to interfaces. FIXME: Once we've determined the
1455/// appropriate overloading rules for Objective-C, we may want to
1456/// split the Objective-C checks into a different routine; however,
1457/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001458/// conversions, so for now they live here. IncompatibleObjC will be
1459/// set if the conversion is an allowed Objective-C conversion that
1460/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001461bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001462 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001463 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001464 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001465 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00001466 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1467 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00001468 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001469
Mike Stump1eb44332009-09-09 15:08:12 +00001470 // Conversion from a null pointer constant to any Objective-C pointer type.
1471 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001472 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001473 ConvertedType = ToType;
1474 return true;
1475 }
1476
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001477 // Blocks: Block pointers can be converted to void*.
1478 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001479 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001480 ConvertedType = ToType;
1481 return true;
1482 }
1483 // Blocks: A null pointer constant can be converted to a block
1484 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001485 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001486 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001487 ConvertedType = ToType;
1488 return true;
1489 }
1490
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001491 // If the left-hand-side is nullptr_t, the right side can be a null
1492 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001493 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001494 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001495 ConvertedType = ToType;
1496 return true;
1497 }
1498
Ted Kremenek6217b802009-07-29 21:53:49 +00001499 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001500 if (!ToTypePtr)
1501 return false;
1502
1503 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001504 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001505 ConvertedType = ToType;
1506 return true;
1507 }
Sebastian Redl07779722008-10-31 14:43:28 +00001508
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001509 // Beyond this point, both types need to be pointers
1510 // , including objective-c pointers.
1511 QualType ToPointeeType = ToTypePtr->getPointeeType();
1512 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001513 ConvertedType = BuildSimilarlyQualifiedPointerType(
1514 FromType->getAs<ObjCObjectPointerType>(),
1515 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001516 ToType, Context);
1517 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001518 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001519 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001520 if (!FromTypePtr)
1521 return false;
1522
1523 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001524
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00001525 // If the unqualified pointee types are the same, this can't be a
1526 // pointer conversion, so don't do all of the work below.
1527 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1528 return false;
1529
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001530 // An rvalue of type "pointer to cv T," where T is an object type,
1531 // can be converted to an rvalue of type "pointer to cv void" (C++
1532 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00001533 if (FromPointeeType->isIncompleteOrObjectType() &&
1534 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001535 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001536 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001537 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001538 return true;
1539 }
1540
Douglas Gregorf9201e02009-02-11 23:02:49 +00001541 // When we're overloading in C, we allow a special kind of pointer
1542 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001543 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001544 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001545 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001546 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001547 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001548 return true;
1549 }
1550
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001551 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001552 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001553 // An rvalue of type "pointer to cv D," where D is a class type,
1554 // can be converted to an rvalue of type "pointer to cv B," where
1555 // B is a base class (clause 10) of D. If B is an inaccessible
1556 // (clause 11) or ambiguous (10.2) base class of D, a program that
1557 // necessitates this conversion is ill-formed. The result of the
1558 // conversion is a pointer to the base class sub-object of the
1559 // derived class object. The null pointer value is converted to
1560 // the null pointer value of the destination type.
1561 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001562 // Note that we do not check for ambiguity or inaccessibility
1563 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001564 if (getLangOptions().CPlusPlus &&
1565 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001566 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001567 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001568 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001569 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001570 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001571 ToType, Context);
1572 return true;
1573 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001574
Douglas Gregorc7887512008-12-19 19:13:09 +00001575 return false;
1576}
1577
1578/// isObjCPointerConversion - Determines whether this is an
1579/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1580/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001581bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001582 QualType& ConvertedType,
1583 bool &IncompatibleObjC) {
1584 if (!getLangOptions().ObjC1)
1585 return false;
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001586
Steve Naroff14108da2009-07-10 23:34:53 +00001587 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00001588 const ObjCObjectPointerType* ToObjCPtr =
1589 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001590 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001591 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001592
Steve Naroff14108da2009-07-10 23:34:53 +00001593 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001594 // If the pointee types are the same (ignoring qualifications),
1595 // then this is not a pointer conversion.
1596 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1597 FromObjCPtr->getPointeeType()))
1598 return false;
1599
Steve Naroffde2e22d2009-07-15 18:40:39 +00001600 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001601 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001602 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001603 ConvertedType = ToType;
1604 return true;
1605 }
1606 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001607 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001608 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001609 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001610 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001611 ConvertedType = ToType;
1612 return true;
1613 }
1614 // Objective C++: We're able to convert from a pointer to an
1615 // interface to a pointer to a different interface.
1616 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00001617 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1618 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1619 if (getLangOptions().CPlusPlus && LHS && RHS &&
1620 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1621 FromObjCPtr->getPointeeType()))
1622 return false;
Douglas Gregorda80f742010-12-01 21:43:58 +00001623 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
1624 ToObjCPtr->getPointeeType(),
1625 ToType, Context);
Steve Naroff14108da2009-07-10 23:34:53 +00001626 return true;
1627 }
1628
1629 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1630 // Okay: this is some kind of implicit downcast of Objective-C
1631 // interfaces, which is permitted. However, we're going to
1632 // complain about it.
1633 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00001634 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
1635 ToObjCPtr->getPointeeType(),
1636 ToType, Context);
Steve Naroff14108da2009-07-10 23:34:53 +00001637 return true;
1638 }
Mike Stump1eb44332009-09-09 15:08:12 +00001639 }
Steve Naroff14108da2009-07-10 23:34:53 +00001640 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001641 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001642 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001643 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001644 else if (const BlockPointerType *ToBlockPtr =
1645 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00001646 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001647 // to a block pointer type.
1648 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1649 ConvertedType = ToType;
1650 return true;
1651 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001652 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001653 }
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001654 else if (FromType->getAs<BlockPointerType>() &&
1655 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1656 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00001657 // pointer to any object.
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001658 ConvertedType = ToType;
1659 return true;
1660 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001661 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001662 return false;
1663
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001664 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001665 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001666 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00001667 else if (const BlockPointerType *FromBlockPtr =
1668 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001669 FromPointeeType = FromBlockPtr->getPointeeType();
1670 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001671 return false;
1672
Douglas Gregorc7887512008-12-19 19:13:09 +00001673 // If we have pointers to pointers, recursively check whether this
1674 // is an Objective-C conversion.
1675 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1676 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1677 IncompatibleObjC)) {
1678 // We always complain about this conversion.
1679 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00001680 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregorc7887512008-12-19 19:13:09 +00001681 return true;
1682 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001683 // Allow conversion of pointee being objective-c pointer to another one;
1684 // as in I* to id.
1685 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1686 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1687 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1688 IncompatibleObjC)) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001689 ConvertedType = Context.getPointerType(ConvertedType);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001690 return true;
1691 }
1692
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001693 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001694 // differences in the argument and result types are in Objective-C
1695 // pointer conversions. If so, we permit the conversion (but
1696 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001697 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001698 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001699 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001700 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001701 if (FromFunctionType && ToFunctionType) {
1702 // If the function types are exactly the same, this isn't an
1703 // Objective-C pointer conversion.
1704 if (Context.getCanonicalType(FromPointeeType)
1705 == Context.getCanonicalType(ToPointeeType))
1706 return false;
1707
1708 // Perform the quick checks that will tell us whether these
1709 // function types are obviously different.
1710 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1711 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1712 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1713 return false;
1714
1715 bool HasObjCConversion = false;
1716 if (Context.getCanonicalType(FromFunctionType->getResultType())
1717 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1718 // Okay, the types match exactly. Nothing to do.
1719 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1720 ToFunctionType->getResultType(),
1721 ConvertedType, IncompatibleObjC)) {
1722 // Okay, we have an Objective-C pointer conversion.
1723 HasObjCConversion = true;
1724 } else {
1725 // Function types are too different. Abort.
1726 return false;
1727 }
Mike Stump1eb44332009-09-09 15:08:12 +00001728
Douglas Gregorc7887512008-12-19 19:13:09 +00001729 // Check argument types.
1730 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1731 ArgIdx != NumArgs; ++ArgIdx) {
1732 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1733 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1734 if (Context.getCanonicalType(FromArgType)
1735 == Context.getCanonicalType(ToArgType)) {
1736 // Okay, the types match exactly. Nothing to do.
1737 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1738 ConvertedType, IncompatibleObjC)) {
1739 // Okay, we have an Objective-C pointer conversion.
1740 HasObjCConversion = true;
1741 } else {
1742 // Argument types are too different. Abort.
1743 return false;
1744 }
1745 }
1746
1747 if (HasObjCConversion) {
1748 // We had an Objective-C conversion. Allow this pointer
1749 // conversion, but complain about it.
1750 ConvertedType = ToType;
1751 IncompatibleObjC = true;
1752 return true;
1753 }
1754 }
1755
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001756 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001757}
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001758
1759/// FunctionArgTypesAreEqual - This routine checks two function proto types
1760/// for equlity of their argument types. Caller has already checked that
1761/// they have same number of arguments. This routine assumes that Objective-C
1762/// pointer types which only differ in their protocol qualifiers are equal.
1763bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1764 FunctionProtoType* NewType){
1765 if (!getLangOptions().ObjC1)
1766 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1767 NewType->arg_type_begin());
1768
1769 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1770 N = NewType->arg_type_begin(),
1771 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1772 QualType ToType = (*O);
1773 QualType FromType = (*N);
1774 if (ToType != FromType) {
1775 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1776 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00001777 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1778 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1779 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1780 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001781 continue;
1782 }
John McCallc12c5bb2010-05-15 11:32:37 +00001783 else if (const ObjCObjectPointerType *PTTo =
1784 ToType->getAs<ObjCObjectPointerType>()) {
1785 if (const ObjCObjectPointerType *PTFr =
1786 FromType->getAs<ObjCObjectPointerType>())
1787 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1788 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001789 }
1790 return false;
1791 }
1792 }
1793 return true;
1794}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001795
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001796/// CheckPointerConversion - Check the pointer conversion from the
1797/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001798/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001799/// conversions for which IsPointerConversion has already returned
1800/// true. It returns true and produces a diagnostic if there was an
1801/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001802bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00001803 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001804 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001805 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001806 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00001807 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001808
John McCalldaa8e4e2010-11-15 09:13:47 +00001809 Kind = CK_BitCast;
1810
Douglas Gregord7a95972010-06-08 17:35:15 +00001811 if (CXXBoolLiteralExpr* LitBool
1812 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00001813 if (!IsCStyleOrFunctionalCast && LitBool->getValue() == false)
Douglas Gregord7a95972010-06-08 17:35:15 +00001814 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1815 << ToType;
1816
Ted Kremenek6217b802009-07-29 21:53:49 +00001817 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1818 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001819 QualType FromPointeeType = FromPtrType->getPointeeType(),
1820 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001821
Douglas Gregor5fccd362010-03-03 23:55:11 +00001822 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1823 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001824 // We must have a derived-to-base conversion. Check an
1825 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001826 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1827 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001828 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001829 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001830 return true;
1831
1832 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00001833 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001834 }
1835 }
Mike Stump1eb44332009-09-09 15:08:12 +00001836 if (const ObjCObjectPointerType *FromPtrType =
John McCalldaa8e4e2010-11-15 09:13:47 +00001837 FromType->getAs<ObjCObjectPointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001838 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00001839 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001840 // Objective-C++ conversions are always okay.
1841 // FIXME: We should have a different class of conversions for the
1842 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001843 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001844 return false;
John McCalldaa8e4e2010-11-15 09:13:47 +00001845 }
Steve Naroff14108da2009-07-10 23:34:53 +00001846 }
John McCalldaa8e4e2010-11-15 09:13:47 +00001847
1848 // We shouldn't fall into this case unless it's valid for other
1849 // reasons.
1850 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
1851 Kind = CK_NullToPointer;
1852
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001853 return false;
1854}
1855
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001856/// IsMemberPointerConversion - Determines whether the conversion of the
1857/// expression From, which has the (possibly adjusted) type FromType, can be
1858/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1859/// If so, returns true and places the converted type (that might differ from
1860/// ToType in its cv-qualifiers at some level) into ConvertedType.
1861bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregorce940492009-09-25 04:25:58 +00001862 QualType ToType,
1863 bool InOverloadResolution,
1864 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001865 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001866 if (!ToTypePtr)
1867 return false;
1868
1869 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00001870 if (From->isNullPointerConstant(Context,
1871 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1872 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001873 ConvertedType = ToType;
1874 return true;
1875 }
1876
1877 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001878 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001879 if (!FromTypePtr)
1880 return false;
1881
1882 // A pointer to member of B can be converted to a pointer to member of D,
1883 // where D is derived from B (C++ 4.11p2).
1884 QualType FromClass(FromTypePtr->getClass(), 0);
1885 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001886
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00001887 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
1888 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
1889 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001890 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1891 ToClass.getTypePtr());
1892 return true;
1893 }
1894
1895 return false;
1896}
Douglas Gregor43c79c22009-12-09 00:47:37 +00001897
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001898/// CheckMemberPointerConversion - Check the member pointer conversion from the
1899/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00001900/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001901/// for which IsMemberPointerConversion has already returned true. It returns
1902/// true and produces a diagnostic if there was an error, or returns false
1903/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001904bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00001905 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001906 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001907 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001908 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001909 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001910 if (!FromPtrType) {
1911 // This must be a null pointer to member pointer conversion
Douglas Gregorce940492009-09-25 04:25:58 +00001912 assert(From->isNullPointerConstant(Context,
1913 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001914 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00001915 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001916 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001917 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001918
Ted Kremenek6217b802009-07-29 21:53:49 +00001919 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001920 assert(ToPtrType && "No member pointer cast has a target type "
1921 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001922
Sebastian Redl21593ac2009-01-28 18:33:18 +00001923 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1924 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001925
Sebastian Redl21593ac2009-01-28 18:33:18 +00001926 // FIXME: What about dependent types?
1927 assert(FromClass->isRecordType() && "Pointer into non-class.");
1928 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001929
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001930 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001931 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00001932 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1933 assert(DerivationOkay &&
1934 "Should not have been called if derivation isn't OK.");
1935 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001936
Sebastian Redl21593ac2009-01-28 18:33:18 +00001937 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1938 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001939 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1940 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1941 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1942 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001943 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001944
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001945 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001946 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1947 << FromClass << ToClass << QualType(VBase, 0)
1948 << From->getSourceRange();
1949 return true;
1950 }
1951
John McCall6b2accb2010-02-10 09:31:12 +00001952 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00001953 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1954 Paths.front(),
1955 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00001956
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001957 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001958 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00001959 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001960 return false;
1961}
1962
Douglas Gregor98cd5992008-10-21 23:43:52 +00001963/// IsQualificationConversion - Determines whether the conversion from
1964/// an rvalue of type FromType to ToType is a qualification conversion
1965/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001966bool
1967Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001968 FromType = Context.getCanonicalType(FromType);
1969 ToType = Context.getCanonicalType(ToType);
1970
1971 // If FromType and ToType are the same type, this is not a
1972 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00001973 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00001974 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001975
Douglas Gregor98cd5992008-10-21 23:43:52 +00001976 // (C++ 4.4p4):
1977 // A conversion can add cv-qualifiers at levels other than the first
1978 // in multi-level pointers, subject to the following rules: [...]
1979 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001980 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00001981 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001982 // Within each iteration of the loop, we check the qualifiers to
1983 // determine if this still looks like a qualification
1984 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001985 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001986 // until there are no more pointers or pointers-to-members left to
1987 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001988 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001989
1990 // -- for every j > 0, if const is in cv 1,j then const is in cv
1991 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001992 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001993 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001994
Douglas Gregor98cd5992008-10-21 23:43:52 +00001995 // -- if the cv 1,j and cv 2,j are different, then const is in
1996 // every cv for 0 < k < j.
1997 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001998 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001999 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002000
Douglas Gregor98cd5992008-10-21 23:43:52 +00002001 // Keep track of whether all prior cv-qualifiers in the "to" type
2002 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002003 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00002004 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00002005 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002006
2007 // We are left with FromType and ToType being the pointee types
2008 // after unwrapping the original FromType and ToType the same number
2009 // of types. If we unwrapped any pointers, and if FromType and
2010 // ToType have the same unqualified type (since we checked
2011 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002012 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002013}
2014
Douglas Gregor734d9862009-01-30 23:27:23 +00002015/// Determines whether there is a user-defined conversion sequence
2016/// (C++ [over.ics.user]) that converts expression From to the type
2017/// ToType. If such a conversion exists, User will contain the
2018/// user-defined conversion sequence that performs such a conversion
2019/// and this routine will return true. Otherwise, this routine returns
2020/// false and User is unspecified.
2021///
Douglas Gregor734d9862009-01-30 23:27:23 +00002022/// \param AllowExplicit true if the conversion should consider C++0x
2023/// "explicit" conversion functions as well as non-explicit conversion
2024/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00002025static OverloadingResult
2026IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2027 UserDefinedConversionSequence& User,
2028 OverloadCandidateSet& CandidateSet,
2029 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002030 // Whether we will only visit constructors.
2031 bool ConstructorsOnly = false;
2032
2033 // If the type we are conversion to is a class type, enumerate its
2034 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00002035 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002036 // C++ [over.match.ctor]p1:
2037 // When objects of class type are direct-initialized (8.5), or
2038 // copy-initialized from an expression of the same or a
2039 // derived class type (8.5), overload resolution selects the
2040 // constructor. [...] For copy-initialization, the candidate
2041 // functions are all the converting constructors (12.3.1) of
2042 // that class. The argument list is the expression-list within
2043 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00002044 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002045 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00002046 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002047 ConstructorsOnly = true;
2048
John McCall120d63c2010-08-24 20:38:10 +00002049 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag())) {
Douglas Gregor393896f2009-11-05 13:06:35 +00002050 // We're not going to find any constructors.
2051 } else if (CXXRecordDecl *ToRecordDecl
2052 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002053 DeclContext::lookup_iterator Con, ConEnd;
John McCall120d63c2010-08-24 20:38:10 +00002054 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002055 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002056 NamedDecl *D = *Con;
2057 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2058
Douglas Gregordec06662009-08-21 18:42:58 +00002059 // Find the constructor (which may be a template).
2060 CXXConstructorDecl *Constructor = 0;
2061 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00002062 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00002063 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00002064 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00002065 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2066 else
John McCall9aa472c2010-03-19 07:35:19 +00002067 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002068
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00002069 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00002070 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00002071 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00002072 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2073 /*ExplicitArgs*/ 0,
2074 &From, 1, CandidateSet,
2075 /*SuppressUserConversions=*/
2076 !ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00002077 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00002078 // Allow one user-defined conversion when user specifies a
2079 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00002080 S.AddOverloadCandidate(Constructor, FoundDecl,
2081 &From, 1, CandidateSet,
2082 /*SuppressUserConversions=*/
2083 !ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00002084 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002085 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002086 }
2087 }
2088
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002089 // Enumerate conversion functions, if we're allowed to.
2090 if (ConstructorsOnly) {
John McCall120d63c2010-08-24 20:38:10 +00002091 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2092 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00002093 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00002094 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002095 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002096 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002097 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2098 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00002099 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002100 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002101 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00002102 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00002103 DeclAccessPair FoundDecl = I.getPair();
2104 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00002105 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2106 if (isa<UsingShadowDecl>(D))
2107 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2108
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002109 CXXConversionDecl *Conv;
2110 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00002111 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2112 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002113 else
John McCall32daa422010-03-31 01:36:47 +00002114 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002115
2116 if (AllowExplicit || !Conv->isExplicit()) {
2117 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00002118 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2119 ActingContext, From, ToType,
2120 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002121 else
John McCall120d63c2010-08-24 20:38:10 +00002122 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2123 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002124 }
2125 }
2126 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002127 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002128
2129 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002130 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00002131 case OR_Success:
2132 // Record the standard conversion we used and the conversion function.
2133 if (CXXConstructorDecl *Constructor
2134 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
2135 // C++ [over.ics.user]p1:
2136 // If the user-defined conversion is specified by a
2137 // constructor (12.3.1), the initial standard conversion
2138 // sequence converts the source type to the type required by
2139 // the argument of the constructor.
2140 //
2141 QualType ThisType = Constructor->getThisType(S.Context);
2142 if (Best->Conversions[0].isEllipsis())
2143 User.EllipsisConversion = true;
2144 else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002145 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002146 User.EllipsisConversion = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002147 }
John McCall120d63c2010-08-24 20:38:10 +00002148 User.ConversionFunction = Constructor;
2149 User.After.setAsIdentityConversion();
2150 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2151 User.After.setAllToTypes(ToType);
2152 return OR_Success;
2153 } else if (CXXConversionDecl *Conversion
2154 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2155 // C++ [over.ics.user]p1:
2156 //
2157 // [...] If the user-defined conversion is specified by a
2158 // conversion function (12.3.2), the initial standard
2159 // conversion sequence converts the source type to the
2160 // implicit object parameter of the conversion function.
2161 User.Before = Best->Conversions[0].Standard;
2162 User.ConversionFunction = Conversion;
2163 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002164
John McCall120d63c2010-08-24 20:38:10 +00002165 // C++ [over.ics.user]p2:
2166 // The second standard conversion sequence converts the
2167 // result of the user-defined conversion to the target type
2168 // for the sequence. Since an implicit conversion sequence
2169 // is an initialization, the special rules for
2170 // initialization by user-defined conversion apply when
2171 // selecting the best user-defined conversion for a
2172 // user-defined conversion sequence (see 13.3.3 and
2173 // 13.3.3.1).
2174 User.After = Best->FinalConversion;
2175 return OR_Success;
2176 } else {
2177 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002178 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002179 }
2180
John McCall120d63c2010-08-24 20:38:10 +00002181 case OR_No_Viable_Function:
2182 return OR_No_Viable_Function;
2183 case OR_Deleted:
2184 // No conversion here! We're done.
2185 return OR_Deleted;
2186
2187 case OR_Ambiguous:
2188 return OR_Ambiguous;
2189 }
2190
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002191 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002192}
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002193
2194bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002195Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002196 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00002197 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002198 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00002199 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002200 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002201 if (OvResult == OR_Ambiguous)
2202 Diag(From->getSourceRange().getBegin(),
2203 diag::err_typecheck_ambiguous_condition)
2204 << From->getType() << ToType << From->getSourceRange();
2205 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2206 Diag(From->getSourceRange().getBegin(),
2207 diag::err_typecheck_nonviable_condition)
2208 << From->getType() << ToType << From->getSourceRange();
2209 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002210 return false;
John McCall120d63c2010-08-24 20:38:10 +00002211 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002212 return true;
2213}
Douglas Gregor60d62c22008-10-31 16:23:19 +00002214
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002215/// CompareImplicitConversionSequences - Compare two implicit
2216/// conversion sequences to determine whether one is better than the
2217/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00002218static ImplicitConversionSequence::CompareKind
2219CompareImplicitConversionSequences(Sema &S,
2220 const ImplicitConversionSequence& ICS1,
2221 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002222{
2223 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2224 // conversion sequences (as defined in 13.3.3.1)
2225 // -- a standard conversion sequence (13.3.3.1.1) is a better
2226 // conversion sequence than a user-defined conversion sequence or
2227 // an ellipsis conversion sequence, and
2228 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2229 // conversion sequence than an ellipsis conversion sequence
2230 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002231 //
John McCall1d318332010-01-12 00:44:57 +00002232 // C++0x [over.best.ics]p10:
2233 // For the purpose of ranking implicit conversion sequences as
2234 // described in 13.3.3.2, the ambiguous conversion sequence is
2235 // treated as a user-defined sequence that is indistinguishable
2236 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002237 if (ICS1.getKindRank() < ICS2.getKindRank())
2238 return ImplicitConversionSequence::Better;
2239 else if (ICS2.getKindRank() < ICS1.getKindRank())
2240 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002241
Benjamin Kramerb6eee072010-04-18 12:05:54 +00002242 // The following checks require both conversion sequences to be of
2243 // the same kind.
2244 if (ICS1.getKind() != ICS2.getKind())
2245 return ImplicitConversionSequence::Indistinguishable;
2246
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002247 // Two implicit conversion sequences of the same form are
2248 // indistinguishable conversion sequences unless one of the
2249 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00002250 if (ICS1.isStandard())
John McCall120d63c2010-08-24 20:38:10 +00002251 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00002252 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002253 // User-defined conversion sequence U1 is a better conversion
2254 // sequence than another user-defined conversion sequence U2 if
2255 // they contain the same user-defined conversion function or
2256 // constructor and if the second standard conversion sequence of
2257 // U1 is better than the second standard conversion sequence of
2258 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002259 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002260 ICS2.UserDefined.ConversionFunction)
John McCall120d63c2010-08-24 20:38:10 +00002261 return CompareStandardConversionSequences(S,
2262 ICS1.UserDefined.After,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002263 ICS2.UserDefined.After);
2264 }
2265
2266 return ImplicitConversionSequence::Indistinguishable;
2267}
2268
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002269static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2270 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2271 Qualifiers Quals;
2272 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2273 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2274 }
2275
2276 return Context.hasSameUnqualifiedType(T1, T2);
2277}
2278
Douglas Gregorad323a82010-01-27 03:51:04 +00002279// Per 13.3.3.2p3, compare the given standard conversion sequences to
2280// determine if one is a proper subset of the other.
2281static ImplicitConversionSequence::CompareKind
2282compareStandardConversionSubsets(ASTContext &Context,
2283 const StandardConversionSequence& SCS1,
2284 const StandardConversionSequence& SCS2) {
2285 ImplicitConversionSequence::CompareKind Result
2286 = ImplicitConversionSequence::Indistinguishable;
2287
Douglas Gregorae65f4b2010-05-23 22:10:15 +00002288 // the identity conversion sequence is considered to be a subsequence of
2289 // any non-identity conversion sequence
2290 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2291 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2292 return ImplicitConversionSequence::Better;
2293 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2294 return ImplicitConversionSequence::Worse;
2295 }
2296
Douglas Gregorad323a82010-01-27 03:51:04 +00002297 if (SCS1.Second != SCS2.Second) {
2298 if (SCS1.Second == ICK_Identity)
2299 Result = ImplicitConversionSequence::Better;
2300 else if (SCS2.Second == ICK_Identity)
2301 Result = ImplicitConversionSequence::Worse;
2302 else
2303 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002304 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00002305 return ImplicitConversionSequence::Indistinguishable;
2306
2307 if (SCS1.Third == SCS2.Third) {
2308 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2309 : ImplicitConversionSequence::Indistinguishable;
2310 }
2311
2312 if (SCS1.Third == ICK_Identity)
2313 return Result == ImplicitConversionSequence::Worse
2314 ? ImplicitConversionSequence::Indistinguishable
2315 : ImplicitConversionSequence::Better;
2316
2317 if (SCS2.Third == ICK_Identity)
2318 return Result == ImplicitConversionSequence::Better
2319 ? ImplicitConversionSequence::Indistinguishable
2320 : ImplicitConversionSequence::Worse;
2321
2322 return ImplicitConversionSequence::Indistinguishable;
2323}
2324
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002325/// CompareStandardConversionSequences - Compare two standard
2326/// conversion sequences to determine whether one is better than the
2327/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00002328static ImplicitConversionSequence::CompareKind
2329CompareStandardConversionSequences(Sema &S,
2330 const StandardConversionSequence& SCS1,
2331 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002332{
2333 // Standard conversion sequence S1 is a better conversion sequence
2334 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2335
2336 // -- S1 is a proper subsequence of S2 (comparing the conversion
2337 // sequences in the canonical form defined by 13.3.3.1.1,
2338 // excluding any Lvalue Transformation; the identity conversion
2339 // sequence is considered to be a subsequence of any
2340 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00002341 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00002342 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00002343 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002344
2345 // -- the rank of S1 is better than the rank of S2 (by the rules
2346 // defined below), or, if not that,
2347 ImplicitConversionRank Rank1 = SCS1.getRank();
2348 ImplicitConversionRank Rank2 = SCS2.getRank();
2349 if (Rank1 < Rank2)
2350 return ImplicitConversionSequence::Better;
2351 else if (Rank2 < Rank1)
2352 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002353
Douglas Gregor57373262008-10-22 14:17:15 +00002354 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2355 // are indistinguishable unless one of the following rules
2356 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00002357
Douglas Gregor57373262008-10-22 14:17:15 +00002358 // A conversion that is not a conversion of a pointer, or
2359 // pointer to member, to bool is better than another conversion
2360 // that is such a conversion.
2361 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2362 return SCS2.isPointerConversionToBool()
2363 ? ImplicitConversionSequence::Better
2364 : ImplicitConversionSequence::Worse;
2365
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002366 // C++ [over.ics.rank]p4b2:
2367 //
2368 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002369 // conversion of B* to A* is better than conversion of B* to
2370 // void*, and conversion of A* to void* is better than conversion
2371 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00002372 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00002373 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002374 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00002375 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002376 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2377 // Exactly one of the conversion sequences is a conversion to
2378 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002379 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2380 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002381 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2382 // Neither conversion sequence converts to a void pointer; compare
2383 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002384 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00002385 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002386 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002387 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2388 // Both conversion sequences are conversions to void
2389 // pointers. Compare the source types to determine if there's an
2390 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00002391 QualType FromType1 = SCS1.getFromType();
2392 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002393
2394 // Adjust the types we're converting from via the array-to-pointer
2395 // conversion, if we need to.
2396 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002397 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002398 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002399 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002400
Douglas Gregor01919692009-12-13 21:37:05 +00002401 QualType FromPointee1
2402 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2403 QualType FromPointee2
2404 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002405
John McCall120d63c2010-08-24 20:38:10 +00002406 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00002407 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002408 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00002409 return ImplicitConversionSequence::Worse;
2410
2411 // Objective-C++: If one interface is more specific than the
2412 // other, it is the better one.
John McCallc12c5bb2010-05-15 11:32:37 +00002413 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2414 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor01919692009-12-13 21:37:05 +00002415 if (FromIface1 && FromIface1) {
John McCall120d63c2010-08-24 20:38:10 +00002416 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor01919692009-12-13 21:37:05 +00002417 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002418 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor01919692009-12-13 21:37:05 +00002419 return ImplicitConversionSequence::Worse;
2420 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002421 }
Douglas Gregor57373262008-10-22 14:17:15 +00002422
2423 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2424 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00002425 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00002426 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002427 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00002428
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002429 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002430 // C++0x [over.ics.rank]p3b4:
2431 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2432 // implicit object parameter of a non-static member function declared
2433 // without a ref-qualifier, and S1 binds an rvalue reference to an
2434 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00002435 // FIXME: We don't know if we're dealing with the implicit object parameter,
2436 // or if the member function in this case has a ref qualifier.
2437 // (Of course, we don't have ref qualifiers yet.)
2438 if (SCS1.RRefBinding != SCS2.RRefBinding)
2439 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2440 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002441
2442 // C++ [over.ics.rank]p3b4:
2443 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2444 // which the references refer are the same type except for
2445 // top-level cv-qualifiers, and the type to which the reference
2446 // initialized by S2 refers is more cv-qualified than the type
2447 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00002448 QualType T1 = SCS1.getToType(2);
2449 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00002450 T1 = S.Context.getCanonicalType(T1);
2451 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002452 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00002453 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2454 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002455 if (UnqualT1 == UnqualT2) {
Chandler Carruth6df868e2010-12-12 08:17:55 +00002456 // If the type is an array type, promote the element qualifiers to the
2457 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00002458 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00002459 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002460 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00002461 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002462 if (T2.isMoreQualifiedThan(T1))
2463 return ImplicitConversionSequence::Better;
2464 else if (T1.isMoreQualifiedThan(T2))
2465 return ImplicitConversionSequence::Worse;
2466 }
2467 }
Douglas Gregor57373262008-10-22 14:17:15 +00002468
2469 return ImplicitConversionSequence::Indistinguishable;
2470}
2471
2472/// CompareQualificationConversions - Compares two standard conversion
2473/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00002474/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2475ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00002476CompareQualificationConversions(Sema &S,
2477 const StandardConversionSequence& SCS1,
2478 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00002479 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00002480 // -- S1 and S2 differ only in their qualification conversion and
2481 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2482 // cv-qualification signature of type T1 is a proper subset of
2483 // the cv-qualification signature of type T2, and S1 is not the
2484 // deprecated string literal array-to-pointer conversion (4.2).
2485 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2486 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2487 return ImplicitConversionSequence::Indistinguishable;
2488
2489 // FIXME: the example in the standard doesn't use a qualification
2490 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00002491 QualType T1 = SCS1.getToType(2);
2492 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00002493 T1 = S.Context.getCanonicalType(T1);
2494 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002495 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00002496 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2497 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00002498
2499 // If the types are the same, we won't learn anything by unwrapped
2500 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00002501 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00002502 return ImplicitConversionSequence::Indistinguishable;
2503
Chandler Carruth28e318c2009-12-29 07:16:59 +00002504 // If the type is an array type, promote the element qualifiers to the type
2505 // for comparison.
2506 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00002507 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002508 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00002509 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002510
Mike Stump1eb44332009-09-09 15:08:12 +00002511 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00002512 = ImplicitConversionSequence::Indistinguishable;
John McCall120d63c2010-08-24 20:38:10 +00002513 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00002514 // Within each iteration of the loop, we check the qualifiers to
2515 // determine if this still looks like a qualification
2516 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002517 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00002518 // until there are no more pointers or pointers-to-members left
2519 // to unwrap. This essentially mimics what
2520 // IsQualificationConversion does, but here we're checking for a
2521 // strict subset of qualifiers.
2522 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2523 // The qualifiers are the same, so this doesn't tell us anything
2524 // about how the sequences rank.
2525 ;
2526 else if (T2.isMoreQualifiedThan(T1)) {
2527 // T1 has fewer qualifiers, so it could be the better sequence.
2528 if (Result == ImplicitConversionSequence::Worse)
2529 // Neither has qualifiers that are a subset of the other's
2530 // qualifiers.
2531 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002532
Douglas Gregor57373262008-10-22 14:17:15 +00002533 Result = ImplicitConversionSequence::Better;
2534 } else if (T1.isMoreQualifiedThan(T2)) {
2535 // T2 has fewer qualifiers, so it could be the better sequence.
2536 if (Result == ImplicitConversionSequence::Better)
2537 // Neither has qualifiers that are a subset of the other's
2538 // qualifiers.
2539 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002540
Douglas Gregor57373262008-10-22 14:17:15 +00002541 Result = ImplicitConversionSequence::Worse;
2542 } else {
2543 // Qualifiers are disjoint.
2544 return ImplicitConversionSequence::Indistinguishable;
2545 }
2546
2547 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00002548 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00002549 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002550 }
2551
Douglas Gregor57373262008-10-22 14:17:15 +00002552 // Check that the winning standard conversion sequence isn't using
2553 // the deprecated string literal array to pointer conversion.
2554 switch (Result) {
2555 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00002556 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002557 Result = ImplicitConversionSequence::Indistinguishable;
2558 break;
2559
2560 case ImplicitConversionSequence::Indistinguishable:
2561 break;
2562
2563 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00002564 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002565 Result = ImplicitConversionSequence::Indistinguishable;
2566 break;
2567 }
2568
2569 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002570}
2571
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002572/// CompareDerivedToBaseConversions - Compares two standard conversion
2573/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00002574/// various kinds of derived-to-base conversions (C++
2575/// [over.ics.rank]p4b3). As part of these checks, we also look at
2576/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002577ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00002578CompareDerivedToBaseConversions(Sema &S,
2579 const StandardConversionSequence& SCS1,
2580 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00002581 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002582 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00002583 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002584 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002585
2586 // Adjust the types we're converting from via the array-to-pointer
2587 // conversion, if we need to.
2588 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002589 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002590 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002591 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002592
2593 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00002594 FromType1 = S.Context.getCanonicalType(FromType1);
2595 ToType1 = S.Context.getCanonicalType(ToType1);
2596 FromType2 = S.Context.getCanonicalType(FromType2);
2597 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002598
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002599 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002600 //
2601 // If class B is derived directly or indirectly from class A and
2602 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002603 //
2604 // For Objective-C, we let A, B, and C also be Objective-C
2605 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002606
2607 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00002608 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00002609 SCS2.Second == ICK_Pointer_Conversion &&
2610 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2611 FromType1->isPointerType() && FromType2->isPointerType() &&
2612 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002613 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002614 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002615 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002616 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002617 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002618 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002619 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002620 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002621
John McCallc12c5bb2010-05-15 11:32:37 +00002622 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2623 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2624 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2625 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002626
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002627 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002628 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002629 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002630 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002631 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002632 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00002633
2634 if (ToIface1 && ToIface2) {
John McCall120d63c2010-08-24 20:38:10 +00002635 if (S.Context.canAssignObjCInterfaces(ToIface2, ToIface1))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002636 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002637 else if (S.Context.canAssignObjCInterfaces(ToIface1, ToIface2))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002638 return ImplicitConversionSequence::Worse;
2639 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002640 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002641
2642 // -- conversion of B* to A* is better than conversion of C* to A*,
2643 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002644 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002645 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002646 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002647 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00002648
Douglas Gregorcb7de522008-11-26 23:31:11 +00002649 if (FromIface1 && FromIface2) {
John McCall120d63c2010-08-24 20:38:10 +00002650 if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002651 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002652 else if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002653 return ImplicitConversionSequence::Worse;
2654 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002655 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002656 }
2657
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002658 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002659 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2660 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2661 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2662 const MemberPointerType * FromMemPointer1 =
2663 FromType1->getAs<MemberPointerType>();
2664 const MemberPointerType * ToMemPointer1 =
2665 ToType1->getAs<MemberPointerType>();
2666 const MemberPointerType * FromMemPointer2 =
2667 FromType2->getAs<MemberPointerType>();
2668 const MemberPointerType * ToMemPointer2 =
2669 ToType2->getAs<MemberPointerType>();
2670 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2671 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2672 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2673 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2674 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2675 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2676 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2677 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002678 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002679 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002680 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002681 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00002682 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002683 return ImplicitConversionSequence::Better;
2684 }
2685 // conversion of B::* to C::* is better than conversion of A::* to C::*
2686 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002687 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002688 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002689 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002690 return ImplicitConversionSequence::Worse;
2691 }
2692 }
2693
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002694 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002695 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00002696 // -- binding of an expression of type C to a reference of type
2697 // B& is better than binding an expression of type C to a
2698 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00002699 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2700 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2701 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002702 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002703 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002704 return ImplicitConversionSequence::Worse;
2705 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002706
Douglas Gregor225c41e2008-11-03 19:09:14 +00002707 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00002708 // -- binding of an expression of type B to a reference of type
2709 // A& is better than binding an expression of type C to a
2710 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00002711 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2712 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2713 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002714 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002715 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002716 return ImplicitConversionSequence::Worse;
2717 }
2718 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002719
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002720 return ImplicitConversionSequence::Indistinguishable;
2721}
2722
Douglas Gregorabe183d2010-04-13 16:31:36 +00002723/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2724/// determine whether they are reference-related,
2725/// reference-compatible, reference-compatible with added
2726/// qualification, or incompatible, for use in C++ initialization by
2727/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2728/// type, and the first type (T1) is the pointee type of the reference
2729/// type being initialized.
2730Sema::ReferenceCompareResult
2731Sema::CompareReferenceRelationship(SourceLocation Loc,
2732 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00002733 bool &DerivedToBase,
2734 bool &ObjCConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002735 assert(!OrigT1->isReferenceType() &&
2736 "T1 must be the pointee type of the reference type");
2737 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2738
2739 QualType T1 = Context.getCanonicalType(OrigT1);
2740 QualType T2 = Context.getCanonicalType(OrigT2);
2741 Qualifiers T1Quals, T2Quals;
2742 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2743 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2744
2745 // C++ [dcl.init.ref]p4:
2746 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2747 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2748 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00002749 DerivedToBase = false;
2750 ObjCConversion = false;
2751 if (UnqualT1 == UnqualT2) {
2752 // Nothing to do.
2753 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00002754 IsDerivedFrom(UnqualT2, UnqualT1))
2755 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00002756 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2757 UnqualT2->isObjCObjectOrInterfaceType() &&
2758 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2759 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002760 else
2761 return Ref_Incompatible;
2762
2763 // At this point, we know that T1 and T2 are reference-related (at
2764 // least).
2765
2766 // If the type is an array type, promote the element qualifiers to the type
2767 // for comparison.
2768 if (isa<ArrayType>(T1) && T1Quals)
2769 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2770 if (isa<ArrayType>(T2) && T2Quals)
2771 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2772
2773 // C++ [dcl.init.ref]p4:
2774 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2775 // reference-related to T2 and cv1 is the same cv-qualification
2776 // as, or greater cv-qualification than, cv2. For purposes of
2777 // overload resolution, cases for which cv1 is greater
2778 // cv-qualification than cv2 are identified as
2779 // reference-compatible with added qualification (see 13.3.3.2).
2780 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2781 return Ref_Compatible;
2782 else if (T1.isMoreQualifiedThan(T2))
2783 return Ref_Compatible_With_Added_Qualification;
2784 else
2785 return Ref_Related;
2786}
2787
Douglas Gregor604eb652010-08-11 02:15:33 +00002788/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00002789/// with DeclType. Return true if something definite is found.
2790static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00002791FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2792 QualType DeclType, SourceLocation DeclLoc,
2793 Expr *Init, QualType T2, bool AllowRvalues,
2794 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00002795 assert(T2->isRecordType() && "Can only find conversions of record types.");
2796 CXXRecordDecl *T2RecordDecl
2797 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2798
Douglas Gregor604eb652010-08-11 02:15:33 +00002799 QualType ToType
2800 = AllowRvalues? DeclType->getAs<ReferenceType>()->getPointeeType()
2801 : DeclType;
2802
Sebastian Redl4680bf22010-06-30 18:13:39 +00002803 OverloadCandidateSet CandidateSet(DeclLoc);
2804 const UnresolvedSetImpl *Conversions
2805 = T2RecordDecl->getVisibleConversionFunctions();
2806 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2807 E = Conversions->end(); I != E; ++I) {
2808 NamedDecl *D = *I;
2809 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2810 if (isa<UsingShadowDecl>(D))
2811 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2812
2813 FunctionTemplateDecl *ConvTemplate
2814 = dyn_cast<FunctionTemplateDecl>(D);
2815 CXXConversionDecl *Conv;
2816 if (ConvTemplate)
2817 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2818 else
2819 Conv = cast<CXXConversionDecl>(D);
2820
Douglas Gregor604eb652010-08-11 02:15:33 +00002821 // If this is an explicit conversion, and we're not allowed to consider
2822 // explicit conversions, skip it.
2823 if (!AllowExplicit && Conv->isExplicit())
2824 continue;
2825
2826 if (AllowRvalues) {
2827 bool DerivedToBase = false;
2828 bool ObjCConversion = false;
2829 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00002830 S.CompareReferenceRelationship(
2831 DeclLoc,
2832 Conv->getConversionType().getNonReferenceType()
2833 .getUnqualifiedType(),
2834 DeclType.getNonReferenceType().getUnqualifiedType(),
2835 DerivedToBase, ObjCConversion) ==
2836 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00002837 continue;
2838 } else {
2839 // If the conversion function doesn't return a reference type,
2840 // it can't be considered for this conversion. An rvalue reference
2841 // is only acceptable if its referencee is a function type.
2842
2843 const ReferenceType *RefType =
2844 Conv->getConversionType()->getAs<ReferenceType>();
2845 if (!RefType ||
2846 (!RefType->isLValueReferenceType() &&
2847 !RefType->getPointeeType()->isFunctionType()))
2848 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002849 }
Douglas Gregor604eb652010-08-11 02:15:33 +00002850
2851 if (ConvTemplate)
2852 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2853 Init, ToType, CandidateSet);
2854 else
2855 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2856 ToType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002857 }
2858
2859 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002860 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00002861 case OR_Success:
2862 // C++ [over.ics.ref]p1:
2863 //
2864 // [...] If the parameter binds directly to the result of
2865 // applying a conversion function to the argument
2866 // expression, the implicit conversion sequence is a
2867 // user-defined conversion sequence (13.3.3.1.2), with the
2868 // second standard conversion sequence either an identity
2869 // conversion or, if the conversion function returns an
2870 // entity of a type that is a derived class of the parameter
2871 // type, a derived-to-base Conversion.
2872 if (!Best->FinalConversion.DirectBinding)
2873 return false;
2874
2875 ICS.setUserDefined();
2876 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2877 ICS.UserDefined.After = Best->FinalConversion;
2878 ICS.UserDefined.ConversionFunction = Best->Function;
2879 ICS.UserDefined.EllipsisConversion = false;
2880 assert(ICS.UserDefined.After.ReferenceBinding &&
2881 ICS.UserDefined.After.DirectBinding &&
2882 "Expected a direct reference binding!");
2883 return true;
2884
2885 case OR_Ambiguous:
2886 ICS.setAmbiguous();
2887 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2888 Cand != CandidateSet.end(); ++Cand)
2889 if (Cand->Viable)
2890 ICS.Ambiguous.addConversion(Cand->Function);
2891 return true;
2892
2893 case OR_No_Viable_Function:
2894 case OR_Deleted:
2895 // There was no suitable conversion, or we found a deleted
2896 // conversion; continue with other checks.
2897 return false;
2898 }
Eric Christopher1c3d5022010-06-30 18:36:32 +00002899
2900 return false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002901}
2902
Douglas Gregorabe183d2010-04-13 16:31:36 +00002903/// \brief Compute an implicit conversion sequence for reference
2904/// initialization.
2905static ImplicitConversionSequence
2906TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2907 SourceLocation DeclLoc,
2908 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00002909 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002910 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2911
2912 // Most paths end in a failed conversion.
2913 ImplicitConversionSequence ICS;
2914 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2915
2916 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2917 QualType T2 = Init->getType();
2918
2919 // If the initializer is the address of an overloaded function, try
2920 // to resolve the overloaded function. If all goes well, T2 is the
2921 // type of the resulting function.
2922 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2923 DeclAccessPair Found;
2924 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2925 false, Found))
2926 T2 = Fn->getType();
2927 }
2928
2929 // Compute some basic properties of the types and the initializer.
2930 bool isRValRef = DeclType->isRValueReferenceType();
2931 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002932 bool ObjCConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002933 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002934 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00002935 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
2936 ObjCConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002937
Douglas Gregorabe183d2010-04-13 16:31:36 +00002938
Sebastian Redl4680bf22010-06-30 18:13:39 +00002939 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00002940 // A reference to type "cv1 T1" is initialized by an expression
2941 // of type "cv2 T2" as follows:
2942
Sebastian Redl4680bf22010-06-30 18:13:39 +00002943 // -- If reference is an lvalue reference and the initializer expression
2944 // The next bullet point (T1 is a function) is pretty much equivalent to this
2945 // one, so it's handled here.
2946 if (!isRValRef || T1->isFunctionType()) {
2947 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2948 // reference-compatible with "cv2 T2," or
2949 //
2950 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2951 if (InitCategory.isLValue() &&
2952 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002953 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00002954 // When a parameter of reference type binds directly (8.5.3)
2955 // to an argument expression, the implicit conversion sequence
2956 // is the identity conversion, unless the argument expression
2957 // has a type that is a derived class of the parameter type,
2958 // in which case the implicit conversion sequence is a
2959 // derived-to-base Conversion (13.3.3.1).
2960 ICS.setStandard();
2961 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00002962 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2963 : ObjCConversion? ICK_Compatible_Conversion
2964 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002965 ICS.Standard.Third = ICK_Identity;
2966 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2967 ICS.Standard.setToType(0, T2);
2968 ICS.Standard.setToType(1, T1);
2969 ICS.Standard.setToType(2, T1);
2970 ICS.Standard.ReferenceBinding = true;
2971 ICS.Standard.DirectBinding = true;
2972 ICS.Standard.RRefBinding = isRValRef;
2973 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002974
Sebastian Redl4680bf22010-06-30 18:13:39 +00002975 // Nothing more to do: the inaccessibility/ambiguity check for
2976 // derived-to-base conversions is suppressed when we're
2977 // computing the implicit conversion sequence (C++
2978 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00002979 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002980 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00002981
Sebastian Redl4680bf22010-06-30 18:13:39 +00002982 // -- has a class type (i.e., T2 is a class type), where T1 is
2983 // not reference-related to T2, and can be implicitly
2984 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2985 // is reference-compatible with "cv3 T3" 92) (this
2986 // conversion is selected by enumerating the applicable
2987 // conversion functions (13.3.1.6) and choosing the best
2988 // one through overload resolution (13.3)),
2989 if (!SuppressUserConversions && T2->isRecordType() &&
2990 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2991 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00002992 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2993 Init, T2, /*AllowRvalues=*/false,
2994 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00002995 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002996 }
2997 }
2998
Sebastian Redl4680bf22010-06-30 18:13:39 +00002999 // -- Otherwise, the reference shall be an lvalue reference to a
3000 // non-volatile const type (i.e., cv1 shall be const), or the reference
3001 // shall be an rvalue reference and the initializer expression shall be
3002 // an rvalue or have a function type.
Douglas Gregor66821b52010-04-18 09:22:00 +00003003 //
3004 // We actually handle one oddity of C++ [over.ics.ref] at this
3005 // point, which is that, due to p2 (which short-circuits reference
3006 // binding by only attempting a simple conversion for non-direct
3007 // bindings) and p3's strange wording, we allow a const volatile
3008 // reference to bind to an rvalue. Hence the check for the presence
3009 // of "const" rather than checking for "const" being the only
3010 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00003011 // This is also the point where rvalue references and lvalue inits no longer
3012 // go together.
3013 if ((!isRValRef && !T1.isConstQualified()) ||
3014 (isRValRef && InitCategory.isLValue()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003015 return ICS;
3016
Sebastian Redl4680bf22010-06-30 18:13:39 +00003017 // -- If T1 is a function type, then
3018 // -- if T2 is the same type as T1, the reference is bound to the
3019 // initializer expression lvalue;
3020 // -- if T2 is a class type and the initializer expression can be
3021 // implicitly converted to an lvalue of type T1 [...], the
3022 // reference is bound to the function lvalue that is the result
3023 // of the conversion;
3024 // This is the same as for the lvalue case above, so it was handled there.
3025 // -- otherwise, the program is ill-formed.
3026 // This is the one difference to the lvalue case.
3027 if (T1->isFunctionType())
3028 return ICS;
3029
3030 // -- Otherwise, if T2 is a class type and
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00003031 // -- the initializer expression is an rvalue and "cv1 T1"
3032 // is reference-compatible with "cv2 T2," or
Douglas Gregorabe183d2010-04-13 16:31:36 +00003033 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00003034 // -- T1 is not reference-related to T2 and the initializer
3035 // expression can be implicitly converted to an rvalue
3036 // of type "cv3 T3" (this conversion is selected by
3037 // enumerating the applicable conversion functions
3038 // (13.3.1.6) and choosing the best one through overload
3039 // resolution (13.3)),
Douglas Gregorabe183d2010-04-13 16:31:36 +00003040 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00003041 // then the reference is bound to the initializer
3042 // expression rvalue in the first case and to the object
3043 // that is the result of the conversion in the second case
3044 // (or, in either case, to the appropriate base class
3045 // subobject of the object).
Douglas Gregor604eb652010-08-11 02:15:33 +00003046 if (T2->isRecordType()) {
3047 // First case: "cv1 T1" is reference-compatible with "cv2 T2". This is a
3048 // direct binding in C++0x but not in C++03.
3049 if (InitCategory.isRValue() &&
3050 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
3051 ICS.setStandard();
3052 ICS.Standard.First = ICK_Identity;
3053 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3054 : ObjCConversion? ICK_Compatible_Conversion
3055 : ICK_Identity;
3056 ICS.Standard.Third = ICK_Identity;
3057 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3058 ICS.Standard.setToType(0, T2);
3059 ICS.Standard.setToType(1, T1);
3060 ICS.Standard.setToType(2, T1);
3061 ICS.Standard.ReferenceBinding = true;
3062 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
3063 ICS.Standard.RRefBinding = isRValRef;
3064 ICS.Standard.CopyConstructor = 0;
3065 return ICS;
3066 }
3067
3068 // Second case: not reference-related.
3069 if (RefRelationship == Sema::Ref_Incompatible &&
3070 !S.RequireCompleteType(DeclLoc, T2, 0) &&
3071 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3072 Init, T2, /*AllowRvalues=*/true,
3073 AllowExplicit))
3074 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003075 }
Douglas Gregor604eb652010-08-11 02:15:33 +00003076
Douglas Gregorabe183d2010-04-13 16:31:36 +00003077 // -- Otherwise, a temporary of type "cv1 T1" is created and
3078 // initialized from the initializer expression using the
3079 // rules for a non-reference copy initialization (8.5). The
3080 // reference is then bound to the temporary. If T1 is
3081 // reference-related to T2, cv1 must be the same
3082 // cv-qualification as, or greater cv-qualification than,
3083 // cv2; otherwise, the program is ill-formed.
3084 if (RefRelationship == Sema::Ref_Related) {
3085 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3086 // we would be reference-compatible or reference-compatible with
3087 // added qualification. But that wasn't the case, so the reference
3088 // initialization fails.
3089 return ICS;
3090 }
3091
3092 // If at least one of the types is a class type, the types are not
3093 // related, and we aren't allowed any user conversions, the
3094 // reference binding fails. This case is important for breaking
3095 // recursion, since TryImplicitConversion below will attempt to
3096 // create a temporary through the use of a copy constructor.
3097 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3098 (T1->isRecordType() || T2->isRecordType()))
3099 return ICS;
3100
3101 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00003102 // When a parameter of reference type is not bound directly to
3103 // an argument expression, the conversion sequence is the one
3104 // required to convert the argument expression to the
3105 // underlying type of the reference according to
3106 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3107 // to copy-initializing a temporary of the underlying type with
3108 // the argument expression. Any difference in top-level
3109 // cv-qualification is subsumed by the initialization itself
3110 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00003111 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3112 /*AllowExplicit=*/false,
3113 /*InOverloadResolution=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003114
3115 // Of course, that's still a reference binding.
3116 if (ICS.isStandard()) {
3117 ICS.Standard.ReferenceBinding = true;
3118 ICS.Standard.RRefBinding = isRValRef;
3119 } else if (ICS.isUserDefined()) {
3120 ICS.UserDefined.After.ReferenceBinding = true;
3121 ICS.UserDefined.After.RRefBinding = isRValRef;
3122 }
3123 return ICS;
3124}
3125
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003126/// TryCopyInitialization - Try to copy-initialize a value of type
3127/// ToType from the expression From. Return the implicit conversion
3128/// sequence required to pass this argument, which may be a bad
3129/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00003130/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00003131/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00003132static ImplicitConversionSequence
3133TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregorb7f9e6a2010-04-16 17:53:55 +00003134 bool SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00003135 bool InOverloadResolution) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003136 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00003137 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00003138 /*FIXME:*/From->getLocStart(),
3139 SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00003140 /*AllowExplicit=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003141
John McCall120d63c2010-08-24 20:38:10 +00003142 return TryImplicitConversion(S, From, ToType,
3143 SuppressUserConversions,
3144 /*AllowExplicit=*/false,
3145 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003146}
3147
Douglas Gregor96176b32008-11-18 23:14:02 +00003148/// TryObjectArgumentInitialization - Try to initialize the object
3149/// parameter of the given member function (@c Method) from the
3150/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00003151static ImplicitConversionSequence
3152TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
3153 CXXMethodDecl *Method,
3154 CXXRecordDecl *ActingContext) {
3155 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00003156 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3157 // const volatile object.
3158 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3159 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00003160 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00003161
3162 // Set up the conversion sequence as a "bad" conversion, to allow us
3163 // to exit early.
3164 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00003165
3166 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00003167 QualType FromType = OrigFromType;
Ted Kremenek6217b802009-07-29 21:53:49 +00003168 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00003169 FromType = PT->getPointeeType();
3170
3171 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00003172
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00003173 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor96176b32008-11-18 23:14:02 +00003174 // where X is the class of which the function is a member
3175 // (C++ [over.match.funcs]p4). However, when finding an implicit
3176 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00003177 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00003178 // (C++ [over.match.funcs]p5). We perform a simplified version of
3179 // reference binding here, that allows class rvalues to bind to
3180 // non-constant references.
3181
3182 // First check the qualifiers. We don't care about lvalue-vs-rvalue
3183 // with the implicit object parameter (C++ [over.match.funcs]p5).
John McCall120d63c2010-08-24 20:38:10 +00003184 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00003185 if (ImplicitParamType.getCVRQualifiers()
3186 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00003187 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00003188 ICS.setBad(BadConversionSequence::bad_qualifiers,
3189 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003190 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003191 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003192
3193 // Check that we have either the same type or a derived type. It
3194 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00003195 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00003196 ImplicitConversionKind SecondKind;
3197 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3198 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00003199 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00003200 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00003201 else {
John McCallb1bdc622010-02-25 01:37:24 +00003202 ICS.setBad(BadConversionSequence::unrelated_class,
3203 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003204 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003205 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003206
3207 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00003208 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00003209 ICS.Standard.setAsIdentityConversion();
3210 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00003211 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003212 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003213 ICS.Standard.ReferenceBinding = true;
3214 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00003215 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003216 return ICS;
3217}
3218
3219/// PerformObjectArgumentInitialization - Perform initialization of
3220/// the implicit object parameter for the given Method with the given
3221/// expression.
3222bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00003223Sema::PerformObjectArgumentInitialization(Expr *&From,
3224 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00003225 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00003226 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003227 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00003228 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00003229 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003230
Ted Kremenek6217b802009-07-29 21:53:49 +00003231 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003232 FromRecordType = PT->getPointeeType();
3233 DestType = Method->getThisType(Context);
3234 } else {
3235 FromRecordType = From->getType();
3236 DestType = ImplicitParamRecordType;
3237 }
3238
John McCall701c89e2009-12-03 04:06:58 +00003239 // Note that we always use the true parent context when performing
3240 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003241 ImplicitConversionSequence ICS
John McCall120d63c2010-08-24 20:38:10 +00003242 = TryObjectArgumentInitialization(*this, From->getType(), Method,
John McCall701c89e2009-12-03 04:06:58 +00003243 Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00003244 if (ICS.isBad()) {
3245 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3246 Qualifiers FromQs = FromRecordType.getQualifiers();
3247 Qualifiers ToQs = DestType.getQualifiers();
3248 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3249 if (CVR) {
3250 Diag(From->getSourceRange().getBegin(),
3251 diag::err_member_function_call_bad_cvr)
3252 << Method->getDeclName() << FromRecordType << (CVR - 1)
3253 << From->getSourceRange();
3254 Diag(Method->getLocation(), diag::note_previous_decl)
3255 << Method->getDeclName();
3256 return true;
3257 }
3258 }
3259
Douglas Gregor96176b32008-11-18 23:14:02 +00003260 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003261 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00003262 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00003263 }
Mike Stump1eb44332009-09-09 15:08:12 +00003264
Douglas Gregor5fccd362010-03-03 23:55:11 +00003265 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall6bb80172010-03-30 21:47:33 +00003266 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor96176b32008-11-18 23:14:02 +00003267
Douglas Gregor5fccd362010-03-03 23:55:11 +00003268 if (!Context.hasSameType(From->getType(), DestType))
John McCall2de56d12010-08-25 11:45:40 +00003269 ImpCastExprToType(From, DestType, CK_NoOp,
John McCall5baba9d2010-08-25 10:28:54 +00003270 From->getType()->isPointerType() ? VK_RValue : VK_LValue);
Douglas Gregor96176b32008-11-18 23:14:02 +00003271 return false;
3272}
3273
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003274/// TryContextuallyConvertToBool - Attempt to contextually convert the
3275/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00003276static ImplicitConversionSequence
3277TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00003278 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00003279 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00003280 // FIXME: Are these flags correct?
3281 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00003282 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00003283 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003284}
3285
3286/// PerformContextuallyConvertToBool - Perform a contextual conversion
3287/// of the expression From to bool (C++0x [conv]p3).
3288bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
John McCall120d63c2010-08-24 20:38:10 +00003289 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00003290 if (!ICS.isBad())
3291 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003292
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003293 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003294 return Diag(From->getSourceRange().getBegin(),
3295 diag::err_typecheck_bool_condition)
3296 << From->getType() << From->getSourceRange();
3297 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003298}
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003299
3300/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3301/// expression From to 'id'.
John McCall120d63c2010-08-24 20:38:10 +00003302static ImplicitConversionSequence
3303TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3304 QualType Ty = S.Context.getObjCIdType();
3305 return TryImplicitConversion(S, From, Ty,
3306 // FIXME: Are these flags correct?
3307 /*SuppressUserConversions=*/false,
3308 /*AllowExplicit=*/true,
3309 /*InOverloadResolution=*/false);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003310}
John McCall120d63c2010-08-24 20:38:10 +00003311
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003312/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3313/// of the expression From to 'id'.
3314bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCallc12c5bb2010-05-15 11:32:37 +00003315 QualType Ty = Context.getObjCIdType();
John McCall120d63c2010-08-24 20:38:10 +00003316 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003317 if (!ICS.isBad())
3318 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3319 return true;
3320}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003321
Douglas Gregorc30614b2010-06-29 23:17:37 +00003322/// \brief Attempt to convert the given expression to an integral or
3323/// enumeration type.
3324///
3325/// This routine will attempt to convert an expression of class type to an
3326/// integral or enumeration type, if that class type only has a single
3327/// conversion to an integral or enumeration type.
3328///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003329/// \param Loc The source location of the construct that requires the
3330/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00003331///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003332/// \param FromE The expression we're converting from.
3333///
3334/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3335/// have integral or enumeration type.
3336///
3337/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3338/// incomplete class type.
3339///
3340/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3341/// explicit conversion function (because no implicit conversion functions
3342/// were available). This is a recovery mode.
3343///
3344/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3345/// showing which conversion was picked.
3346///
3347/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3348/// conversion function that could convert to integral or enumeration type.
3349///
3350/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3351/// usable conversion function.
3352///
3353/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3354/// function, which may be an extension in this case.
3355///
3356/// \returns The expression, converted to an integral or enumeration type if
3357/// successful.
John McCall60d7b3a2010-08-24 06:29:42 +00003358ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003359Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorc30614b2010-06-29 23:17:37 +00003360 const PartialDiagnostic &NotIntDiag,
3361 const PartialDiagnostic &IncompleteDiag,
3362 const PartialDiagnostic &ExplicitConvDiag,
3363 const PartialDiagnostic &ExplicitConvNote,
3364 const PartialDiagnostic &AmbigDiag,
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003365 const PartialDiagnostic &AmbigNote,
3366 const PartialDiagnostic &ConvDiag) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00003367 // We can't perform any more checking for type-dependent expressions.
3368 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00003369 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003370
3371 // If the expression already has integral or enumeration type, we're golden.
3372 QualType T = From->getType();
3373 if (T->isIntegralOrEnumerationType())
John McCall9ae2f072010-08-23 23:25:46 +00003374 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003375
3376 // FIXME: Check for missing '()' if T is a function type?
3377
3378 // If we don't have a class type in C++, there's no way we can get an
3379 // expression of integral or enumeration type.
3380 const RecordType *RecordTy = T->getAs<RecordType>();
3381 if (!RecordTy || !getLangOptions().CPlusPlus) {
3382 Diag(Loc, NotIntDiag)
3383 << T << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00003384 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003385 }
3386
3387 // We must have a complete class type.
3388 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCall9ae2f072010-08-23 23:25:46 +00003389 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003390
3391 // Look for a conversion to an integral or enumeration type.
3392 UnresolvedSet<4> ViableConversions;
3393 UnresolvedSet<4> ExplicitConversions;
3394 const UnresolvedSetImpl *Conversions
3395 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3396
3397 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3398 E = Conversions->end();
3399 I != E;
3400 ++I) {
3401 if (CXXConversionDecl *Conversion
3402 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3403 if (Conversion->getConversionType().getNonReferenceType()
3404 ->isIntegralOrEnumerationType()) {
3405 if (Conversion->isExplicit())
3406 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3407 else
3408 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3409 }
3410 }
3411
3412 switch (ViableConversions.size()) {
3413 case 0:
3414 if (ExplicitConversions.size() == 1) {
3415 DeclAccessPair Found = ExplicitConversions[0];
3416 CXXConversionDecl *Conversion
3417 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3418
3419 // The user probably meant to invoke the given explicit
3420 // conversion; use it.
3421 QualType ConvTy
3422 = Conversion->getConversionType().getNonReferenceType();
3423 std::string TypeStr;
3424 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3425
3426 Diag(Loc, ExplicitConvDiag)
3427 << T << ConvTy
3428 << FixItHint::CreateInsertion(From->getLocStart(),
3429 "static_cast<" + TypeStr + ">(")
3430 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3431 ")");
3432 Diag(Conversion->getLocation(), ExplicitConvNote)
3433 << ConvTy->isEnumeralType() << ConvTy;
3434
3435 // If we aren't in a SFINAE context, build a call to the
3436 // explicit conversion function.
3437 if (isSFINAEContext())
3438 return ExprError();
3439
3440 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
John McCall9ae2f072010-08-23 23:25:46 +00003441 From = BuildCXXMemberCallExpr(From, Found, Conversion);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003442 }
3443
3444 // We'll complain below about a non-integral condition type.
3445 break;
3446
3447 case 1: {
3448 // Apply this conversion.
3449 DeclAccessPair Found = ViableConversions[0];
3450 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003451
3452 CXXConversionDecl *Conversion
3453 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3454 QualType ConvTy
3455 = Conversion->getConversionType().getNonReferenceType();
3456 if (ConvDiag.getDiagID()) {
3457 if (isSFINAEContext())
3458 return ExprError();
3459
3460 Diag(Loc, ConvDiag)
3461 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3462 }
3463
John McCall9ae2f072010-08-23 23:25:46 +00003464 From = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorc30614b2010-06-29 23:17:37 +00003465 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregorc30614b2010-06-29 23:17:37 +00003466 break;
3467 }
3468
3469 default:
3470 Diag(Loc, AmbigDiag)
3471 << T << From->getSourceRange();
3472 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3473 CXXConversionDecl *Conv
3474 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3475 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3476 Diag(Conv->getLocation(), AmbigNote)
3477 << ConvTy->isEnumeralType() << ConvTy;
3478 }
John McCall9ae2f072010-08-23 23:25:46 +00003479 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003480 }
3481
Douglas Gregoracb0bd82010-06-29 23:25:20 +00003482 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorc30614b2010-06-29 23:17:37 +00003483 Diag(Loc, NotIntDiag)
3484 << From->getType() << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00003485
John McCall9ae2f072010-08-23 23:25:46 +00003486 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003487}
3488
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003489/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00003490/// candidate functions, using the given function call arguments. If
3491/// @p SuppressUserConversions, then don't allow user-defined
3492/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003493///
3494/// \para PartialOverloading true if we are performing "partial" overloading
3495/// based on an incomplete set of function arguments. This feature is used by
3496/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00003497void
3498Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00003499 DeclAccessPair FoundDecl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003500 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00003501 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00003502 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003503 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00003504 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003505 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003506 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00003507 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00003508 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00003509
Douglas Gregor88a35142008-12-22 05:46:06 +00003510 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003511 if (!isa<CXXConstructorDecl>(Method)) {
3512 // If we get here, it's because we're calling a member function
3513 // that is named without a member access expression (e.g.,
3514 // "this->f") that was either written explicitly or created
3515 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00003516 // function, e.g., X::f(). We use an empty type for the implied
3517 // object argument (C++ [over.call.func]p3), and the acting context
3518 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00003519 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall701c89e2009-12-03 04:06:58 +00003520 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003521 SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003522 return;
3523 }
3524 // We treat a constructor like a non-member function, since its object
3525 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00003526 }
3527
Douglas Gregorfd476482009-11-13 23:59:09 +00003528 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00003529 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00003530
Douglas Gregor7edfb692009-11-23 12:27:39 +00003531 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003532 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003533
Douglas Gregor66724ea2009-11-14 01:20:54 +00003534 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3535 // C++ [class.copy]p3:
3536 // A member function template is never instantiated to perform the copy
3537 // of a class object to an object of its class type.
3538 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3539 if (NumArgs == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00003540 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00003541 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3542 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00003543 return;
3544 }
3545
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003546 // Add this candidate
3547 CandidateSet.push_back(OverloadCandidate());
3548 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003549 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003550 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00003551 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003552 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003553 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003554
3555 unsigned NumArgsInProto = Proto->getNumArgs();
3556
3557 // (C++ 13.3.2p2): A candidate function having fewer than m
3558 // parameters is viable only if it has an ellipsis in its parameter
3559 // list (8.3.5).
Douglas Gregor5bd1a112009-09-23 14:56:09 +00003560 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3561 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003562 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003563 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003564 return;
3565 }
3566
3567 // (C++ 13.3.2p2): A candidate function having more than m parameters
3568 // is viable only if the (m+1)st parameter has a default argument
3569 // (8.3.6). For the purposes of overload resolution, the
3570 // parameter list is truncated on the right, so that there are
3571 // exactly m parameters.
3572 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003573 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003574 // Not enough arguments.
3575 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003576 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003577 return;
3578 }
3579
3580 // Determine the implicit conversion sequences for each of the
3581 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003582 Candidate.Conversions.resize(NumArgs);
3583 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3584 if (ArgIdx < NumArgsInProto) {
3585 // (C++ 13.3.2p3): for F to be a viable function, there shall
3586 // exist for each argument an implicit conversion sequence
3587 // (13.3.3.1) that converts that argument to the corresponding
3588 // parameter of F.
3589 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003590 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003591 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003592 SuppressUserConversions,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003593 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003594 if (Candidate.Conversions[ArgIdx].isBad()) {
3595 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003596 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00003597 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00003598 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003599 } else {
3600 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3601 // argument for which there is no corresponding parameter is
3602 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003603 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003604 }
3605 }
3606}
3607
Douglas Gregor063daf62009-03-13 18:40:31 +00003608/// \brief Add all of the function declarations in the given function set to
3609/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00003610void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00003611 Expr **Args, unsigned NumArgs,
3612 OverloadCandidateSet& CandidateSet,
3613 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00003614 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00003615 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3616 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003617 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003618 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003619 cast<CXXMethodDecl>(FD)->getParent(),
3620 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003621 CandidateSet, SuppressUserConversions);
3622 else
John McCall9aa472c2010-03-19 07:35:19 +00003623 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00003624 SuppressUserConversions);
3625 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003626 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00003627 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3628 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003629 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003630 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00003631 /*FIXME: explicit args */ 0,
John McCall701c89e2009-12-03 04:06:58 +00003632 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003633 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00003634 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00003635 else
John McCall9aa472c2010-03-19 07:35:19 +00003636 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCalld5532b62009-11-23 01:53:49 +00003637 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00003638 Args, NumArgs, CandidateSet,
3639 SuppressUserConversions);
3640 }
Douglas Gregor364e0212009-06-27 21:05:07 +00003641 }
Douglas Gregor063daf62009-03-13 18:40:31 +00003642}
3643
John McCall314be4e2009-11-17 07:50:12 +00003644/// AddMethodCandidate - Adds a named decl (which is some kind of
3645/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00003646void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003647 QualType ObjectType,
John McCall314be4e2009-11-17 07:50:12 +00003648 Expr **Args, unsigned NumArgs,
3649 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003650 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00003651 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003652 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00003653
3654 if (isa<UsingShadowDecl>(Decl))
3655 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3656
3657 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3658 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3659 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00003660 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3661 /*ExplicitArgs*/ 0,
John McCall701c89e2009-12-03 04:06:58 +00003662 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00003663 CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003664 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003665 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003666 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall701c89e2009-12-03 04:06:58 +00003667 ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003668 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003669 }
3670}
3671
Douglas Gregor96176b32008-11-18 23:14:02 +00003672/// AddMethodCandidate - Adds the given C++ member function to the set
3673/// of candidate functions, using the given function call arguments
3674/// and the object argument (@c Object). For example, in a call
3675/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3676/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3677/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00003678/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00003679void
John McCall9aa472c2010-03-19 07:35:19 +00003680Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003681 CXXRecordDecl *ActingContext, QualType ObjectType,
3682 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00003683 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003684 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00003685 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003686 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00003687 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003688 assert(!isa<CXXConstructorDecl>(Method) &&
3689 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00003690
Douglas Gregor3f396022009-09-28 04:47:19 +00003691 if (!CandidateSet.isNewCandidate(Method))
3692 return;
3693
Douglas Gregor7edfb692009-11-23 12:27:39 +00003694 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003695 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003696
Douglas Gregor96176b32008-11-18 23:14:02 +00003697 // Add this candidate
3698 CandidateSet.push_back(OverloadCandidate());
3699 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003700 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00003701 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003702 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003703 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003704
3705 unsigned NumArgsInProto = Proto->getNumArgs();
3706
3707 // (C++ 13.3.2p2): A candidate function having fewer than m
3708 // parameters is viable only if it has an ellipsis in its parameter
3709 // list (8.3.5).
3710 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3711 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003712 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003713 return;
3714 }
3715
3716 // (C++ 13.3.2p2): A candidate function having more than m parameters
3717 // is viable only if the (m+1)st parameter has a default argument
3718 // (8.3.6). For the purposes of overload resolution, the
3719 // parameter list is truncated on the right, so that there are
3720 // exactly m parameters.
3721 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3722 if (NumArgs < MinRequiredArgs) {
3723 // Not enough arguments.
3724 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003725 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003726 return;
3727 }
3728
3729 Candidate.Viable = true;
3730 Candidate.Conversions.resize(NumArgs + 1);
3731
John McCall701c89e2009-12-03 04:06:58 +00003732 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00003733 // The implicit object argument is ignored.
3734 Candidate.IgnoreObjectArgument = true;
3735 else {
3736 // Determine the implicit conversion sequence for the object
3737 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00003738 Candidate.Conversions[0]
John McCall120d63c2010-08-24 20:38:10 +00003739 = TryObjectArgumentInitialization(*this, ObjectType, Method,
3740 ActingContext);
John McCall1d318332010-01-12 00:44:57 +00003741 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003742 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003743 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00003744 return;
3745 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003746 }
3747
3748 // Determine the implicit conversion sequences for each of the
3749 // arguments.
3750 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3751 if (ArgIdx < NumArgsInProto) {
3752 // (C++ 13.3.2p3): for F to be a viable function, there shall
3753 // exist for each argument an implicit conversion sequence
3754 // (13.3.3.1) that converts that argument to the corresponding
3755 // parameter of F.
3756 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003757 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003758 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003759 SuppressUserConversions,
Anders Carlsson08972922009-08-28 15:33:32 +00003760 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003761 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00003762 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003763 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00003764 break;
3765 }
3766 } else {
3767 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3768 // argument for which there is no corresponding parameter is
3769 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003770 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00003771 }
3772 }
3773}
Douglas Gregora9333192010-05-08 17:41:32 +00003774
Douglas Gregor6b906862009-08-21 00:16:32 +00003775/// \brief Add a C++ member function template as a candidate to the candidate
3776/// set, using template argument deduction to produce an appropriate member
3777/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003778void
Douglas Gregor6b906862009-08-21 00:16:32 +00003779Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00003780 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003781 CXXRecordDecl *ActingContext,
John McCalld5532b62009-11-23 01:53:49 +00003782 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00003783 QualType ObjectType,
3784 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003785 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003786 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003787 if (!CandidateSet.isNewCandidate(MethodTmpl))
3788 return;
3789
Douglas Gregor6b906862009-08-21 00:16:32 +00003790 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003791 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00003792 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003793 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00003794 // candidate functions in the usual way.113) A given name can refer to one
3795 // or more function templates and also to a set of overloaded non-template
3796 // functions. In such a case, the candidate functions generated from each
3797 // function template are combined with the set of non-template candidate
3798 // functions.
John McCall5769d612010-02-08 23:07:23 +00003799 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00003800 FunctionDecl *Specialization = 0;
3801 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003802 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003803 Args, NumArgs, Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003804 CandidateSet.push_back(OverloadCandidate());
3805 OverloadCandidate &Candidate = CandidateSet.back();
3806 Candidate.FoundDecl = FoundDecl;
3807 Candidate.Function = MethodTmpl->getTemplatedDecl();
3808 Candidate.Viable = false;
3809 Candidate.FailureKind = ovl_fail_bad_deduction;
3810 Candidate.IsSurrogate = false;
3811 Candidate.IgnoreObjectArgument = false;
3812 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3813 Info);
3814 return;
3815 }
Mike Stump1eb44332009-09-09 15:08:12 +00003816
Douglas Gregor6b906862009-08-21 00:16:32 +00003817 // Add the function template specialization produced by template argument
3818 // deduction as a candidate.
3819 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00003820 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00003821 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00003822 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003823 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003824 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00003825}
3826
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003827/// \brief Add a C++ function template specialization as a candidate
3828/// in the candidate set, using template argument deduction to produce
3829/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003830void
Douglas Gregore53060f2009-06-25 22:08:12 +00003831Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003832 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00003833 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00003834 Expr **Args, unsigned NumArgs,
3835 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003836 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003837 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3838 return;
3839
Douglas Gregore53060f2009-06-25 22:08:12 +00003840 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003841 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00003842 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003843 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00003844 // candidate functions in the usual way.113) A given name can refer to one
3845 // or more function templates and also to a set of overloaded non-template
3846 // functions. In such a case, the candidate functions generated from each
3847 // function template are combined with the set of non-template candidate
3848 // functions.
John McCall5769d612010-02-08 23:07:23 +00003849 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00003850 FunctionDecl *Specialization = 0;
3851 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003852 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003853 Args, NumArgs, Specialization, Info)) {
John McCall578b69b2009-12-16 08:11:27 +00003854 CandidateSet.push_back(OverloadCandidate());
3855 OverloadCandidate &Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003856 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00003857 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3858 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003859 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00003860 Candidate.IsSurrogate = false;
3861 Candidate.IgnoreObjectArgument = false;
Douglas Gregorff5adac2010-05-08 20:18:54 +00003862 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3863 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00003864 return;
3865 }
Mike Stump1eb44332009-09-09 15:08:12 +00003866
Douglas Gregore53060f2009-06-25 22:08:12 +00003867 // Add the function template specialization produced by template argument
3868 // deduction as a candidate.
3869 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003870 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003871 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00003872}
Mike Stump1eb44332009-09-09 15:08:12 +00003873
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003874/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00003875/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003876/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00003877/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003878/// (which may or may not be the same type as the type that the
3879/// conversion function produces).
3880void
3881Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003882 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003883 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003884 Expr *From, QualType ToType,
3885 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003886 assert(!Conversion->getDescribedFunctionTemplate() &&
3887 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003888 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00003889 if (!CandidateSet.isNewCandidate(Conversion))
3890 return;
3891
Douglas Gregor7edfb692009-11-23 12:27:39 +00003892 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003893 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003894
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003895 // Add this candidate
3896 CandidateSet.push_back(OverloadCandidate());
3897 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003898 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003899 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003900 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003901 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003902 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003903 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003904 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003905 Candidate.Viable = true;
3906 Candidate.Conversions.resize(1);
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003907
Douglas Gregorbca39322010-08-19 15:37:02 +00003908 // C++ [over.match.funcs]p4:
3909 // For conversion functions, the function is considered to be a member of
3910 // the class of the implicit implied object argument for the purpose of
3911 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003912 //
3913 // Determine the implicit conversion sequence for the implicit
3914 // object parameter.
3915 QualType ImplicitParamType = From->getType();
3916 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
3917 ImplicitParamType = FromPtrType->getPointeeType();
3918 CXXRecordDecl *ConversionContext
3919 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
3920
3921 Candidate.Conversions[0]
John McCall120d63c2010-08-24 20:38:10 +00003922 = TryObjectArgumentInitialization(*this, From->getType(), Conversion,
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003923 ConversionContext);
3924
John McCall1d318332010-01-12 00:44:57 +00003925 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003926 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003927 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003928 return;
3929 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003930
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003931 // We won't go through a user-define type conversion function to convert a
3932 // derived to base as such conversions are given Conversion Rank. They only
3933 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3934 QualType FromCanon
3935 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3936 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3937 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3938 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003939 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003940 return;
3941 }
3942
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003943 // To determine what the conversion from the result of calling the
3944 // conversion function to the type we're eventually trying to
3945 // convert to (ToType), we need to synthesize a call to the
3946 // conversion function and attempt copy initialization from it. This
3947 // makes sure that we get the right semantics with respect to
3948 // lvalues/rvalues and the type. Fortunately, we can allocate this
3949 // call on the stack and we don't need its arguments to be
3950 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00003951 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00003952 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00003953 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
3954 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00003955 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00003956 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00003957
Douglas Gregor7d14d382010-11-13 19:36:57 +00003958 QualType CallResultType
3959 = Conversion->getConversionType().getNonLValueExprType(Context);
3960 if (RequireCompleteType(From->getLocStart(), CallResultType, 0)) {
3961 Candidate.Viable = false;
3962 Candidate.FailureKind = ovl_fail_bad_final_conversion;
3963 return;
3964 }
3965
John McCallf89e55a2010-11-18 06:31:45 +00003966 ExprValueKind VK = Expr::getValueKindForType(Conversion->getConversionType());
3967
Mike Stump1eb44332009-09-09 15:08:12 +00003968 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00003969 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3970 // allocator).
John McCallf89e55a2010-11-18 06:31:45 +00003971 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003972 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00003973 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00003974 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00003975 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003976 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00003977
John McCall1d318332010-01-12 00:44:57 +00003978 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003979 case ImplicitConversionSequence::StandardConversion:
3980 Candidate.FinalConversion = ICS.Standard;
Douglas Gregorc520c842010-04-12 23:42:09 +00003981
3982 // C++ [over.ics.user]p3:
3983 // If the user-defined conversion is specified by a specialization of a
3984 // conversion function template, the second standard conversion sequence
3985 // shall have exact match rank.
3986 if (Conversion->getPrimaryTemplate() &&
3987 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3988 Candidate.Viable = false;
3989 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3990 }
3991
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003992 break;
3993
3994 case ImplicitConversionSequence::BadConversion:
3995 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003996 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003997 break;
3998
3999 default:
Mike Stump1eb44332009-09-09 15:08:12 +00004000 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004001 "Can only end up with a standard conversion sequence or failure");
4002 }
4003}
4004
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004005/// \brief Adds a conversion function template specialization
4006/// candidate to the overload set, using template argument deduction
4007/// to deduce the template arguments of the conversion function
4008/// template from the type that we are converting to (C++
4009/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00004010void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004011Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00004012 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004013 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004014 Expr *From, QualType ToType,
4015 OverloadCandidateSet &CandidateSet) {
4016 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4017 "Only conversion function templates permitted here");
4018
Douglas Gregor3f396022009-09-28 04:47:19 +00004019 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4020 return;
4021
John McCall5769d612010-02-08 23:07:23 +00004022 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004023 CXXConversionDecl *Specialization = 0;
4024 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00004025 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004026 Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00004027 CandidateSet.push_back(OverloadCandidate());
4028 OverloadCandidate &Candidate = CandidateSet.back();
4029 Candidate.FoundDecl = FoundDecl;
4030 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4031 Candidate.Viable = false;
4032 Candidate.FailureKind = ovl_fail_bad_deduction;
4033 Candidate.IsSurrogate = false;
4034 Candidate.IgnoreObjectArgument = false;
4035 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
4036 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004037 return;
4038 }
Mike Stump1eb44332009-09-09 15:08:12 +00004039
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004040 // Add the conversion function template specialization produced by
4041 // template argument deduction as a candidate.
4042 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00004043 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00004044 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004045}
4046
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004047/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4048/// converts the given @c Object to a function pointer via the
4049/// conversion function @c Conversion, and then attempts to call it
4050/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4051/// the type of function that we'll eventually be calling.
4052void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00004053 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004054 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00004055 const FunctionProtoType *Proto,
John McCall701c89e2009-12-03 04:06:58 +00004056 QualType ObjectType,
4057 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004058 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00004059 if (!CandidateSet.isNewCandidate(Conversion))
4060 return;
4061
Douglas Gregor7edfb692009-11-23 12:27:39 +00004062 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004063 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004064
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004065 CandidateSet.push_back(OverloadCandidate());
4066 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004067 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004068 Candidate.Function = 0;
4069 Candidate.Surrogate = Conversion;
4070 Candidate.Viable = true;
4071 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00004072 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004073 Candidate.Conversions.resize(NumArgs + 1);
4074
4075 // Determine the implicit conversion sequence for the implicit
4076 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00004077 ImplicitConversionSequence ObjectInit
John McCall120d63c2010-08-24 20:38:10 +00004078 = TryObjectArgumentInitialization(*this, ObjectType, Conversion,
4079 ActingContext);
John McCall1d318332010-01-12 00:44:57 +00004080 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004081 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004082 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00004083 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004084 return;
4085 }
4086
4087 // The first conversion is actually a user-defined conversion whose
4088 // first conversion is ObjectInit's standard conversion (which is
4089 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00004090 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004091 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00004092 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004093 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00004094 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004095 = Candidate.Conversions[0].UserDefined.Before;
4096 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4097
Mike Stump1eb44332009-09-09 15:08:12 +00004098 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004099 unsigned NumArgsInProto = Proto->getNumArgs();
4100
4101 // (C++ 13.3.2p2): A candidate function having fewer than m
4102 // parameters is viable only if it has an ellipsis in its parameter
4103 // list (8.3.5).
4104 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4105 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004106 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004107 return;
4108 }
4109
4110 // Function types don't have any default arguments, so just check if
4111 // we have enough arguments.
4112 if (NumArgs < NumArgsInProto) {
4113 // Not enough arguments.
4114 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004115 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004116 return;
4117 }
4118
4119 // Determine the implicit conversion sequences for each of the
4120 // arguments.
4121 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4122 if (ArgIdx < NumArgsInProto) {
4123 // (C++ 13.3.2p3): for F to be a viable function, there shall
4124 // exist for each argument an implicit conversion sequence
4125 // (13.3.3.1) that converts that argument to the corresponding
4126 // parameter of F.
4127 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00004128 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004129 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00004130 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00004131 /*InOverloadResolution=*/false);
John McCall1d318332010-01-12 00:44:57 +00004132 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004133 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004134 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004135 break;
4136 }
4137 } else {
4138 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4139 // argument for which there is no corresponding parameter is
4140 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00004141 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004142 }
4143 }
4144}
4145
Douglas Gregor063daf62009-03-13 18:40:31 +00004146/// \brief Add overload candidates for overloaded operators that are
4147/// member functions.
4148///
4149/// Add the overloaded operator candidates that are member functions
4150/// for the operator Op that was used in an operator expression such
4151/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4152/// CandidateSet will store the added overload candidates. (C++
4153/// [over.match.oper]).
4154void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4155 SourceLocation OpLoc,
4156 Expr **Args, unsigned NumArgs,
4157 OverloadCandidateSet& CandidateSet,
4158 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00004159 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4160
4161 // C++ [over.match.oper]p3:
4162 // For a unary operator @ with an operand of a type whose
4163 // cv-unqualified version is T1, and for a binary operator @ with
4164 // a left operand of a type whose cv-unqualified version is T1 and
4165 // a right operand of a type whose cv-unqualified version is T2,
4166 // three sets of candidate functions, designated member
4167 // candidates, non-member candidates and built-in candidates, are
4168 // constructed as follows:
4169 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00004170
4171 // -- If T1 is a class type, the set of member candidates is the
4172 // result of the qualified lookup of T1::operator@
4173 // (13.3.1.1.1); otherwise, the set of member candidates is
4174 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00004175 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004176 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004177 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004178 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004179
John McCalla24dc2e2009-11-17 02:14:36 +00004180 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4181 LookupQualifiedName(Operators, T1Rec->getDecl());
4182 Operators.suppressDiagnostics();
4183
Mike Stump1eb44332009-09-09 15:08:12 +00004184 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004185 OperEnd = Operators.end();
4186 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00004187 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00004188 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall701c89e2009-12-03 04:06:58 +00004189 Args + 1, NumArgs - 1, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00004190 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00004191 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004192}
4193
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004194/// AddBuiltinCandidate - Add a candidate for a built-in
4195/// operator. ResultTy and ParamTys are the result and parameter types
4196/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004197/// arguments being passed to the candidate. IsAssignmentOperator
4198/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004199/// operator. NumContextualBoolArguments is the number of arguments
4200/// (at the beginning of the argument list) that will be contextually
4201/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00004202void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004203 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004204 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004205 bool IsAssignmentOperator,
4206 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00004207 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004208 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004209
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004210 // Add this candidate
4211 CandidateSet.push_back(OverloadCandidate());
4212 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004213 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004214 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00004215 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004216 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004217 Candidate.BuiltinTypes.ResultTy = ResultTy;
4218 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4219 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4220
4221 // Determine the implicit conversion sequences for each of the
4222 // arguments.
4223 Candidate.Viable = true;
4224 Candidate.Conversions.resize(NumArgs);
4225 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004226 // C++ [over.match.oper]p4:
4227 // For the built-in assignment operators, conversions of the
4228 // left operand are restricted as follows:
4229 // -- no temporaries are introduced to hold the left operand, and
4230 // -- no user-defined conversions are applied to the left
4231 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00004232 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004233 //
4234 // We block these conversions by turning off user-defined
4235 // conversions, since that is the only way that initialization of
4236 // a reference to a non-class type can occur from something that
4237 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004238 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00004239 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004240 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00004241 Candidate.Conversions[ArgIdx]
4242 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004243 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00004244 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004245 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00004246 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00004247 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004248 }
John McCall1d318332010-01-12 00:44:57 +00004249 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004250 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004251 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00004252 break;
4253 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004254 }
4255}
4256
4257/// BuiltinCandidateTypeSet - A set of types that will be used for the
4258/// candidate operator functions for built-in operators (C++
4259/// [over.built]). The types are separated into pointer types and
4260/// enumeration types.
4261class BuiltinCandidateTypeSet {
4262 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004263 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004264
4265 /// PointerTypes - The set of pointer types that will be used in the
4266 /// built-in candidates.
4267 TypeSet PointerTypes;
4268
Sebastian Redl78eb8742009-04-19 21:53:20 +00004269 /// MemberPointerTypes - The set of member pointer types that will be
4270 /// used in the built-in candidates.
4271 TypeSet MemberPointerTypes;
4272
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004273 /// EnumerationTypes - The set of enumeration types that will be
4274 /// used in the built-in candidates.
4275 TypeSet EnumerationTypes;
4276
Douglas Gregor26bcf672010-05-19 03:21:00 +00004277 /// \brief The set of vector types that will be used in the built-in
4278 /// candidates.
4279 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00004280
4281 /// \brief A flag indicating non-record types are viable candidates
4282 bool HasNonRecordTypes;
4283
4284 /// \brief A flag indicating whether either arithmetic or enumeration types
4285 /// were present in the candidate set.
4286 bool HasArithmeticOrEnumeralTypes;
4287
Douglas Gregor5842ba92009-08-24 15:23:48 +00004288 /// Sema - The semantic analysis instance where we are building the
4289 /// candidate type set.
4290 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00004291
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004292 /// Context - The AST context in which we will build the type sets.
4293 ASTContext &Context;
4294
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004295 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4296 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00004297 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004298
4299public:
4300 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004301 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004302
Mike Stump1eb44332009-09-09 15:08:12 +00004303 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00004304 : HasNonRecordTypes(false),
4305 HasArithmeticOrEnumeralTypes(false),
4306 SemaRef(SemaRef),
4307 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004308
Douglas Gregor573d9c32009-10-21 23:19:44 +00004309 void AddTypesConvertedFrom(QualType Ty,
4310 SourceLocation Loc,
4311 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004312 bool AllowExplicitConversions,
4313 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004314
4315 /// pointer_begin - First pointer type found;
4316 iterator pointer_begin() { return PointerTypes.begin(); }
4317
Sebastian Redl78eb8742009-04-19 21:53:20 +00004318 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004319 iterator pointer_end() { return PointerTypes.end(); }
4320
Sebastian Redl78eb8742009-04-19 21:53:20 +00004321 /// member_pointer_begin - First member pointer type found;
4322 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4323
4324 /// member_pointer_end - Past the last member pointer type found;
4325 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4326
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004327 /// enumeration_begin - First enumeration type found;
4328 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4329
Sebastian Redl78eb8742009-04-19 21:53:20 +00004330 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004331 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004332
4333 iterator vector_begin() { return VectorTypes.begin(); }
4334 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00004335
4336 bool hasNonRecordTypes() { return HasNonRecordTypes; }
4337 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004338};
4339
Sebastian Redl78eb8742009-04-19 21:53:20 +00004340/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004341/// the set of pointer types along with any more-qualified variants of
4342/// that type. For example, if @p Ty is "int const *", this routine
4343/// will add "int const *", "int const volatile *", "int const
4344/// restrict *", and "int const volatile restrict *" to the set of
4345/// pointer types. Returns true if the add of @p Ty itself succeeded,
4346/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00004347///
4348/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004349bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00004350BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4351 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00004352
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004353 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004354 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004355 return false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004356
4357 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00004358 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004359 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004360 if (!PointerTy) {
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004361 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004362 PointeeTy = PTy->getPointeeType();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004363 buildObjCPtr = true;
4364 }
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004365 else
4366 assert(false && "type was not a pointer type!");
4367 }
4368 else
4369 PointeeTy = PointerTy->getPointeeType();
4370
Sebastian Redla9efada2009-11-18 20:39:26 +00004371 // Don't add qualified variants of arrays. For one, they're not allowed
4372 // (the qualifier would sink to the element type), and for another, the
4373 // only overload situation where it matters is subscript or pointer +- int,
4374 // and those shouldn't have qualifier variants anyway.
4375 if (PointeeTy->isArrayType())
4376 return true;
John McCall0953e762009-09-24 19:53:00 +00004377 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00004378 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00004379 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004380 bool hasVolatile = VisibleQuals.hasVolatile();
4381 bool hasRestrict = VisibleQuals.hasRestrict();
4382
John McCall0953e762009-09-24 19:53:00 +00004383 // Iterate through all strict supersets of BaseCVR.
4384 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4385 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004386 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4387 // in the types.
4388 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4389 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00004390 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004391 if (!buildObjCPtr)
4392 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4393 else
4394 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004395 }
4396
4397 return true;
4398}
4399
Sebastian Redl78eb8742009-04-19 21:53:20 +00004400/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4401/// to the set of pointer types along with any more-qualified variants of
4402/// that type. For example, if @p Ty is "int const *", this routine
4403/// will add "int const *", "int const volatile *", "int const
4404/// restrict *", and "int const volatile restrict *" to the set of
4405/// pointer types. Returns true if the add of @p Ty itself succeeded,
4406/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00004407///
4408/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004409bool
4410BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4411 QualType Ty) {
4412 // Insert this type.
4413 if (!MemberPointerTypes.insert(Ty))
4414 return false;
4415
John McCall0953e762009-09-24 19:53:00 +00004416 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4417 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00004418
John McCall0953e762009-09-24 19:53:00 +00004419 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00004420 // Don't add qualified variants of arrays. For one, they're not allowed
4421 // (the qualifier would sink to the element type), and for another, the
4422 // only overload situation where it matters is subscript or pointer +- int,
4423 // and those shouldn't have qualifier variants anyway.
4424 if (PointeeTy->isArrayType())
4425 return true;
John McCall0953e762009-09-24 19:53:00 +00004426 const Type *ClassTy = PointerTy->getClass();
4427
4428 // Iterate through all strict supersets of the pointee type's CVR
4429 // qualifiers.
4430 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4431 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4432 if ((CVR | BaseCVR) != CVR) continue;
4433
4434 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00004435 MemberPointerTypes.insert(
4436 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00004437 }
4438
4439 return true;
4440}
4441
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004442/// AddTypesConvertedFrom - Add each of the types to which the type @p
4443/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00004444/// primarily interested in pointer types and enumeration types. We also
4445/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004446/// AllowUserConversions is true if we should look at the conversion
4447/// functions of a class type, and AllowExplicitConversions if we
4448/// should also include the explicit conversion functions of a class
4449/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00004450void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004451BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004452 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004453 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004454 bool AllowExplicitConversions,
4455 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004456 // Only deal with canonical types.
4457 Ty = Context.getCanonicalType(Ty);
4458
4459 // Look through reference types; they aren't part of the type of an
4460 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00004461 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004462 Ty = RefTy->getPointeeType();
4463
4464 // We don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004465 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004466
Chandler Carruth6a577462010-12-13 01:44:01 +00004467 // Flag if we ever add a non-record type.
4468 const RecordType *TyRec = Ty->getAs<RecordType>();
4469 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
4470
Sebastian Redla65b5512009-11-05 16:36:20 +00004471 // If we're dealing with an array type, decay to the pointer.
4472 if (Ty->isArrayType())
4473 Ty = SemaRef.Context.getArrayDecayedType(Ty);
Chandler Carruth6a577462010-12-13 01:44:01 +00004474
4475 // Flag if we encounter an arithmetic type.
4476 HasArithmeticOrEnumeralTypes =
4477 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
4478
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004479 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4480 PointerTypes.insert(Ty);
4481 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004482 // Insert our type, and its more-qualified variants, into the set
4483 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004484 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004485 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00004486 } else if (Ty->isMemberPointerType()) {
4487 // Member pointers are far easier, since the pointee can't be converted.
4488 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4489 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004490 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00004491 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00004492 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004493 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00004494 // We treat vector types as arithmetic types in many contexts as an
4495 // extension.
4496 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00004497 VectorTypes.insert(Ty);
Chandler Carruth6a577462010-12-13 01:44:01 +00004498 } else if (AllowUserConversions && TyRec) {
4499 // No conversion functions in incomplete types.
4500 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
4501 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004502
Chandler Carruth6a577462010-12-13 01:44:01 +00004503 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
4504 const UnresolvedSetImpl *Conversions
4505 = ClassDecl->getVisibleConversionFunctions();
4506 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
4507 E = Conversions->end(); I != E; ++I) {
4508 NamedDecl *D = I.getDecl();
4509 if (isa<UsingShadowDecl>(D))
4510 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004511
Chandler Carruth6a577462010-12-13 01:44:01 +00004512 // Skip conversion function templates; they don't tell us anything
4513 // about which builtin types we can convert to.
4514 if (isa<FunctionTemplateDecl>(D))
4515 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004516
Chandler Carruth6a577462010-12-13 01:44:01 +00004517 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
4518 if (AllowExplicitConversions || !Conv->isExplicit()) {
4519 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
4520 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004521 }
4522 }
4523 }
4524}
4525
Douglas Gregor19b7b152009-08-24 13:43:27 +00004526/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4527/// the volatile- and non-volatile-qualified assignment operators for the
4528/// given type to the candidate set.
4529static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4530 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00004531 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004532 unsigned NumArgs,
4533 OverloadCandidateSet &CandidateSet) {
4534 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00004535
Douglas Gregor19b7b152009-08-24 13:43:27 +00004536 // T& operator=(T&, T)
4537 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4538 ParamTypes[1] = T;
4539 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4540 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004541
Douglas Gregor19b7b152009-08-24 13:43:27 +00004542 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4543 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00004544 ParamTypes[0]
4545 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00004546 ParamTypes[1] = T;
4547 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00004548 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00004549 }
4550}
Mike Stump1eb44332009-09-09 15:08:12 +00004551
Sebastian Redl9994a342009-10-25 17:03:50 +00004552/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4553/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004554static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4555 Qualifiers VRQuals;
4556 const RecordType *TyRec;
4557 if (const MemberPointerType *RHSMPType =
4558 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004559 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004560 else
4561 TyRec = ArgExpr->getType()->getAs<RecordType>();
4562 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004563 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004564 VRQuals.addVolatile();
4565 VRQuals.addRestrict();
4566 return VRQuals;
4567 }
4568
4569 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00004570 if (!ClassDecl->hasDefinition())
4571 return VRQuals;
4572
John McCalleec51cf2010-01-20 00:46:10 +00004573 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00004574 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004575
John McCalleec51cf2010-01-20 00:46:10 +00004576 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004577 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00004578 NamedDecl *D = I.getDecl();
4579 if (isa<UsingShadowDecl>(D))
4580 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4581 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004582 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4583 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4584 CanTy = ResTypeRef->getPointeeType();
4585 // Need to go down the pointer/mempointer chain and add qualifiers
4586 // as see them.
4587 bool done = false;
4588 while (!done) {
4589 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4590 CanTy = ResTypePtr->getPointeeType();
4591 else if (const MemberPointerType *ResTypeMPtr =
4592 CanTy->getAs<MemberPointerType>())
4593 CanTy = ResTypeMPtr->getPointeeType();
4594 else
4595 done = true;
4596 if (CanTy.isVolatileQualified())
4597 VRQuals.addVolatile();
4598 if (CanTy.isRestrictQualified())
4599 VRQuals.addRestrict();
4600 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4601 return VRQuals;
4602 }
4603 }
4604 }
4605 return VRQuals;
4606}
John McCall00071ec2010-11-13 05:51:15 +00004607
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004608namespace {
John McCall00071ec2010-11-13 05:51:15 +00004609
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004610/// \brief Helper class to manage the addition of builtin operator overload
4611/// candidates. It provides shared state and utility methods used throughout
4612/// the process, as well as a helper method to add each group of builtin
4613/// operator overloads from the standard to a candidate set.
4614class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00004615 // Common instance state available to all overload candidate addition methods.
4616 Sema &S;
4617 Expr **Args;
4618 unsigned NumArgs;
4619 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00004620 bool HasArithmeticOrEnumeralCandidateType;
Chandler Carruth6d695582010-12-12 10:35:00 +00004621 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
4622 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004623
Chandler Carruth6d695582010-12-12 10:35:00 +00004624 // Define some constants used to index and iterate over the arithemetic types
4625 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00004626 // The "promoted arithmetic types" are the arithmetic
4627 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00004628 static const unsigned FirstIntegralType = 3;
4629 static const unsigned LastIntegralType = 18;
4630 static const unsigned FirstPromotedIntegralType = 3,
4631 LastPromotedIntegralType = 9;
4632 static const unsigned FirstPromotedArithmeticType = 0,
4633 LastPromotedArithmeticType = 9;
4634 static const unsigned NumArithmeticTypes = 18;
4635
Chandler Carruth6d695582010-12-12 10:35:00 +00004636 /// \brief Get the canonical type for a given arithmetic type index.
4637 CanQualType getArithmeticType(unsigned index) {
4638 assert(index < NumArithmeticTypes);
4639 static CanQualType ASTContext::* const
4640 ArithmeticTypes[NumArithmeticTypes] = {
4641 // Start of promoted types.
4642 &ASTContext::FloatTy,
4643 &ASTContext::DoubleTy,
4644 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00004645
Chandler Carruth6d695582010-12-12 10:35:00 +00004646 // Start of integral types.
4647 &ASTContext::IntTy,
4648 &ASTContext::LongTy,
4649 &ASTContext::LongLongTy,
4650 &ASTContext::UnsignedIntTy,
4651 &ASTContext::UnsignedLongTy,
4652 &ASTContext::UnsignedLongLongTy,
4653 // End of promoted types.
4654
4655 &ASTContext::BoolTy,
4656 &ASTContext::CharTy,
4657 &ASTContext::WCharTy,
4658 &ASTContext::Char16Ty,
4659 &ASTContext::Char32Ty,
4660 &ASTContext::SignedCharTy,
4661 &ASTContext::ShortTy,
4662 &ASTContext::UnsignedCharTy,
4663 &ASTContext::UnsignedShortTy,
4664 // End of integral types.
4665 // FIXME: What about complex?
4666 };
4667 return S.Context.*ArithmeticTypes[index];
4668 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004669
Chandler Carruth38ca8d12010-12-12 09:59:53 +00004670 /// \brief Gets the canonical type resulting from the usual arithemetic
4671 /// converions for the given arithmetic types.
4672 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
4673 // Accelerator table for performing the usual arithmetic conversions.
4674 // The rules are basically:
4675 // - if either is floating-point, use the wider floating-point
4676 // - if same signedness, use the higher rank
4677 // - if same size, use unsigned of the higher rank
4678 // - use the larger type
4679 // These rules, together with the axiom that higher ranks are
4680 // never smaller, are sufficient to precompute all of these results
4681 // *except* when dealing with signed types of higher rank.
4682 // (we could precompute SLL x UI for all known platforms, but it's
4683 // better not to make any assumptions).
4684 enum PromotedType {
4685 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
4686 };
4687 static PromotedType ConversionsTable[LastPromotedArithmeticType]
4688 [LastPromotedArithmeticType] = {
4689 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
4690 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
4691 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
4692 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
4693 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
4694 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
4695 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
4696 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
4697 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
4698 };
4699
4700 assert(L < LastPromotedArithmeticType);
4701 assert(R < LastPromotedArithmeticType);
4702 int Idx = ConversionsTable[L][R];
4703
4704 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00004705 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00004706
4707 // Slow path: we need to compare widths.
4708 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00004709 CanQualType LT = getArithmeticType(L),
4710 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00004711 unsigned LW = S.Context.getIntWidth(LT),
4712 RW = S.Context.getIntWidth(RT);
4713
4714 // If they're different widths, use the signed type.
4715 if (LW > RW) return LT;
4716 else if (LW < RW) return RT;
4717
4718 // Otherwise, use the unsigned type of the signed type's rank.
4719 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
4720 assert(L == SLL || R == SLL);
4721 return S.Context.UnsignedLongLongTy;
4722 }
4723
Chandler Carruth3c69dc42010-12-12 09:22:45 +00004724 /// \brief Helper method to factor out the common pattern of adding overloads
4725 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004726 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
4727 bool HasVolatile) {
4728 QualType ParamTypes[2] = {
4729 S.Context.getLValueReferenceType(CandidateTy),
4730 S.Context.IntTy
4731 };
4732
4733 // Non-volatile version.
4734 if (NumArgs == 1)
4735 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4736 else
4737 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
4738
4739 // Use a heuristic to reduce number of builtin candidates in the set:
4740 // add volatile version only if there are conversions to a volatile type.
4741 if (HasVolatile) {
4742 ParamTypes[0] =
4743 S.Context.getLValueReferenceType(
4744 S.Context.getVolatileType(CandidateTy));
4745 if (NumArgs == 1)
4746 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4747 else
4748 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
4749 }
4750 }
4751
4752public:
4753 BuiltinOperatorOverloadBuilder(
4754 Sema &S, Expr **Args, unsigned NumArgs,
4755 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00004756 bool HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004757 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
4758 OverloadCandidateSet &CandidateSet)
4759 : S(S), Args(Args), NumArgs(NumArgs),
4760 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00004761 HasArithmeticOrEnumeralCandidateType(
4762 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004763 CandidateTypes(CandidateTypes),
4764 CandidateSet(CandidateSet) {
4765 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00004766 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004767 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00004768 assert(getArithmeticType(LastPromotedIntegralType - 1)
4769 == S.Context.UnsignedLongLongTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004770 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00004771 assert(getArithmeticType(FirstPromotedArithmeticType)
4772 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004773 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00004774 assert(getArithmeticType(LastPromotedArithmeticType - 1)
4775 == S.Context.UnsignedLongLongTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004776 "Invalid last promoted arithmetic type");
4777 }
4778
4779 // C++ [over.built]p3:
4780 //
4781 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4782 // is either volatile or empty, there exist candidate operator
4783 // functions of the form
4784 //
4785 // VQ T& operator++(VQ T&);
4786 // T operator++(VQ T&, int);
4787 //
4788 // C++ [over.built]p4:
4789 //
4790 // For every pair (T, VQ), where T is an arithmetic type other
4791 // than bool, and VQ is either volatile or empty, there exist
4792 // candidate operator functions of the form
4793 //
4794 // VQ T& operator--(VQ T&);
4795 // T operator--(VQ T&, int);
4796 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00004797 if (!HasArithmeticOrEnumeralCandidateType)
4798 return;
4799
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004800 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
4801 Arith < NumArithmeticTypes; ++Arith) {
4802 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00004803 getArithmeticType(Arith),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004804 VisibleTypeConversionsQuals.hasVolatile());
4805 }
4806 }
4807
4808 // C++ [over.built]p5:
4809 //
4810 // For every pair (T, VQ), where T is a cv-qualified or
4811 // cv-unqualified object type, and VQ is either volatile or
4812 // empty, there exist candidate operator functions of the form
4813 //
4814 // T*VQ& operator++(T*VQ&);
4815 // T*VQ& operator--(T*VQ&);
4816 // T* operator++(T*VQ&, int);
4817 // T* operator--(T*VQ&, int);
4818 void addPlusPlusMinusMinusPointerOverloads() {
4819 for (BuiltinCandidateTypeSet::iterator
4820 Ptr = CandidateTypes[0].pointer_begin(),
4821 PtrEnd = CandidateTypes[0].pointer_end();
4822 Ptr != PtrEnd; ++Ptr) {
4823 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00004824 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004825 continue;
4826
4827 addPlusPlusMinusMinusStyleOverloads(*Ptr,
4828 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4829 VisibleTypeConversionsQuals.hasVolatile()));
4830 }
4831 }
4832
4833 // C++ [over.built]p6:
4834 // For every cv-qualified or cv-unqualified object type T, there
4835 // exist candidate operator functions of the form
4836 //
4837 // T& operator*(T*);
4838 //
4839 // C++ [over.built]p7:
4840 // For every function type T, there exist candidate operator
4841 // functions of the form
4842 // T& operator*(T*);
4843 void addUnaryStarPointerOverloads() {
4844 for (BuiltinCandidateTypeSet::iterator
4845 Ptr = CandidateTypes[0].pointer_begin(),
4846 PtrEnd = CandidateTypes[0].pointer_end();
4847 Ptr != PtrEnd; ++Ptr) {
4848 QualType ParamTy = *Ptr;
4849 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00004850 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
4851 continue;
4852
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004853 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
4854 &ParamTy, Args, 1, CandidateSet);
4855 }
4856 }
4857
4858 // C++ [over.built]p9:
4859 // For every promoted arithmetic type T, there exist candidate
4860 // operator functions of the form
4861 //
4862 // T operator+(T);
4863 // T operator-(T);
4864 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00004865 if (!HasArithmeticOrEnumeralCandidateType)
4866 return;
4867
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004868 for (unsigned Arith = FirstPromotedArithmeticType;
4869 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00004870 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004871 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4872 }
4873
4874 // Extension: We also add these operators for vector types.
4875 for (BuiltinCandidateTypeSet::iterator
4876 Vec = CandidateTypes[0].vector_begin(),
4877 VecEnd = CandidateTypes[0].vector_end();
4878 Vec != VecEnd; ++Vec) {
4879 QualType VecTy = *Vec;
4880 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4881 }
4882 }
4883
4884 // C++ [over.built]p8:
4885 // For every type T, there exist candidate operator functions of
4886 // the form
4887 //
4888 // T* operator+(T*);
4889 void addUnaryPlusPointerOverloads() {
4890 for (BuiltinCandidateTypeSet::iterator
4891 Ptr = CandidateTypes[0].pointer_begin(),
4892 PtrEnd = CandidateTypes[0].pointer_end();
4893 Ptr != PtrEnd; ++Ptr) {
4894 QualType ParamTy = *Ptr;
4895 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4896 }
4897 }
4898
4899 // C++ [over.built]p10:
4900 // For every promoted integral type T, there exist candidate
4901 // operator functions of the form
4902 //
4903 // T operator~(T);
4904 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00004905 if (!HasArithmeticOrEnumeralCandidateType)
4906 return;
4907
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004908 for (unsigned Int = FirstPromotedIntegralType;
4909 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00004910 QualType IntTy = getArithmeticType(Int);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004911 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4912 }
4913
4914 // Extension: We also add this operator for vector types.
4915 for (BuiltinCandidateTypeSet::iterator
4916 Vec = CandidateTypes[0].vector_begin(),
4917 VecEnd = CandidateTypes[0].vector_end();
4918 Vec != VecEnd; ++Vec) {
4919 QualType VecTy = *Vec;
4920 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4921 }
4922 }
4923
4924 // C++ [over.match.oper]p16:
4925 // For every pointer to member type T, there exist candidate operator
4926 // functions of the form
4927 //
4928 // bool operator==(T,T);
4929 // bool operator!=(T,T);
4930 void addEqualEqualOrNotEqualMemberPointerOverloads() {
4931 /// Set of (canonical) types that we've already handled.
4932 llvm::SmallPtrSet<QualType, 8> AddedTypes;
4933
4934 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4935 for (BuiltinCandidateTypeSet::iterator
4936 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
4937 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
4938 MemPtr != MemPtrEnd;
4939 ++MemPtr) {
4940 // Don't add the same builtin candidate twice.
4941 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
4942 continue;
4943
4944 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4945 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
4946 CandidateSet);
4947 }
4948 }
4949 }
4950
4951 // C++ [over.built]p15:
4952 //
4953 // For every pointer or enumeration type T, there exist
4954 // candidate operator functions of the form
4955 //
4956 // bool operator<(T, T);
4957 // bool operator>(T, T);
4958 // bool operator<=(T, T);
4959 // bool operator>=(T, T);
4960 // bool operator==(T, T);
4961 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00004962 void addRelationalPointerOrEnumeralOverloads() {
4963 // C++ [over.built]p1:
4964 // If there is a user-written candidate with the same name and parameter
4965 // types as a built-in candidate operator function, the built-in operator
4966 // function is hidden and is not included in the set of candidate
4967 // functions.
4968 //
4969 // The text is actually in a note, but if we don't implement it then we end
4970 // up with ambiguities when the user provides an overloaded operator for
4971 // an enumeration type. Note that only enumeration types have this problem,
4972 // so we track which enumeration types we've seen operators for. Also, the
4973 // only other overloaded operator with enumeration argumenst, operator=,
4974 // cannot be overloaded for enumeration types, so this is the only place
4975 // where we must suppress candidates like this.
4976 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
4977 UserDefinedBinaryOperators;
4978
4979 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4980 if (CandidateTypes[ArgIdx].enumeration_begin() !=
4981 CandidateTypes[ArgIdx].enumeration_end()) {
4982 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
4983 CEnd = CandidateSet.end();
4984 C != CEnd; ++C) {
4985 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
4986 continue;
4987
4988 QualType FirstParamType =
4989 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
4990 QualType SecondParamType =
4991 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
4992
4993 // Skip if either parameter isn't of enumeral type.
4994 if (!FirstParamType->isEnumeralType() ||
4995 !SecondParamType->isEnumeralType())
4996 continue;
4997
4998 // Add this operator to the set of known user-defined operators.
4999 UserDefinedBinaryOperators.insert(
5000 std::make_pair(S.Context.getCanonicalType(FirstParamType),
5001 S.Context.getCanonicalType(SecondParamType)));
5002 }
5003 }
5004 }
5005
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005006 /// Set of (canonical) types that we've already handled.
5007 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5008
5009 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5010 for (BuiltinCandidateTypeSet::iterator
5011 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5012 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5013 Ptr != PtrEnd; ++Ptr) {
5014 // Don't add the same builtin candidate twice.
5015 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5016 continue;
5017
5018 QualType ParamTypes[2] = { *Ptr, *Ptr };
5019 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5020 CandidateSet);
5021 }
5022 for (BuiltinCandidateTypeSet::iterator
5023 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5024 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5025 Enum != EnumEnd; ++Enum) {
5026 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5027
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00005028 // Don't add the same builtin candidate twice, or if a user defined
5029 // candidate exists.
5030 if (!AddedTypes.insert(CanonType) ||
5031 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5032 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005033 continue;
5034
5035 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00005036 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5037 CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005038 }
5039 }
5040 }
5041
5042 // C++ [over.built]p13:
5043 //
5044 // For every cv-qualified or cv-unqualified object type T
5045 // there exist candidate operator functions of the form
5046 //
5047 // T* operator+(T*, ptrdiff_t);
5048 // T& operator[](T*, ptrdiff_t); [BELOW]
5049 // T* operator-(T*, ptrdiff_t);
5050 // T* operator+(ptrdiff_t, T*);
5051 // T& operator[](ptrdiff_t, T*); [BELOW]
5052 //
5053 // C++ [over.built]p14:
5054 //
5055 // For every T, where T is a pointer to object type, there
5056 // exist candidate operator functions of the form
5057 //
5058 // ptrdiff_t operator-(T, T);
5059 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5060 /// Set of (canonical) types that we've already handled.
5061 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5062
5063 for (int Arg = 0; Arg < 2; ++Arg) {
5064 QualType AsymetricParamTypes[2] = {
5065 S.Context.getPointerDiffType(),
5066 S.Context.getPointerDiffType(),
5067 };
5068 for (BuiltinCandidateTypeSet::iterator
5069 Ptr = CandidateTypes[Arg].pointer_begin(),
5070 PtrEnd = CandidateTypes[Arg].pointer_end();
5071 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00005072 QualType PointeeTy = (*Ptr)->getPointeeType();
5073 if (!PointeeTy->isObjectType())
5074 continue;
5075
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005076 AsymetricParamTypes[Arg] = *Ptr;
5077 if (Arg == 0 || Op == OO_Plus) {
5078 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5079 // T* operator+(ptrdiff_t, T*);
5080 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5081 CandidateSet);
5082 }
5083 if (Op == OO_Minus) {
5084 // ptrdiff_t operator-(T, T);
5085 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5086 continue;
5087
5088 QualType ParamTypes[2] = { *Ptr, *Ptr };
5089 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5090 Args, 2, CandidateSet);
5091 }
5092 }
5093 }
5094 }
5095
5096 // C++ [over.built]p12:
5097 //
5098 // For every pair of promoted arithmetic types L and R, there
5099 // exist candidate operator functions of the form
5100 //
5101 // LR operator*(L, R);
5102 // LR operator/(L, R);
5103 // LR operator+(L, R);
5104 // LR operator-(L, R);
5105 // bool operator<(L, R);
5106 // bool operator>(L, R);
5107 // bool operator<=(L, R);
5108 // bool operator>=(L, R);
5109 // bool operator==(L, R);
5110 // bool operator!=(L, R);
5111 //
5112 // where LR is the result of the usual arithmetic conversions
5113 // between types L and R.
5114 //
5115 // C++ [over.built]p24:
5116 //
5117 // For every pair of promoted arithmetic types L and R, there exist
5118 // candidate operator functions of the form
5119 //
5120 // LR operator?(bool, L, R);
5121 //
5122 // where LR is the result of the usual arithmetic conversions
5123 // between types L and R.
5124 // Our candidates ignore the first parameter.
5125 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005126 if (!HasArithmeticOrEnumeralCandidateType)
5127 return;
5128
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005129 for (unsigned Left = FirstPromotedArithmeticType;
5130 Left < LastPromotedArithmeticType; ++Left) {
5131 for (unsigned Right = FirstPromotedArithmeticType;
5132 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00005133 QualType LandR[2] = { getArithmeticType(Left),
5134 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005135 QualType Result =
5136 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005137 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005138 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5139 }
5140 }
5141
5142 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5143 // conditional operator for vector types.
5144 for (BuiltinCandidateTypeSet::iterator
5145 Vec1 = CandidateTypes[0].vector_begin(),
5146 Vec1End = CandidateTypes[0].vector_end();
5147 Vec1 != Vec1End; ++Vec1) {
5148 for (BuiltinCandidateTypeSet::iterator
5149 Vec2 = CandidateTypes[1].vector_begin(),
5150 Vec2End = CandidateTypes[1].vector_end();
5151 Vec2 != Vec2End; ++Vec2) {
5152 QualType LandR[2] = { *Vec1, *Vec2 };
5153 QualType Result = S.Context.BoolTy;
5154 if (!isComparison) {
5155 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5156 Result = *Vec1;
5157 else
5158 Result = *Vec2;
5159 }
5160
5161 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5162 }
5163 }
5164 }
5165
5166 // C++ [over.built]p17:
5167 //
5168 // For every pair of promoted integral types L and R, there
5169 // exist candidate operator functions of the form
5170 //
5171 // LR operator%(L, R);
5172 // LR operator&(L, R);
5173 // LR operator^(L, R);
5174 // LR operator|(L, R);
5175 // L operator<<(L, R);
5176 // L operator>>(L, R);
5177 //
5178 // where LR is the result of the usual arithmetic conversions
5179 // between types L and R.
5180 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005181 if (!HasArithmeticOrEnumeralCandidateType)
5182 return;
5183
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005184 for (unsigned Left = FirstPromotedIntegralType;
5185 Left < LastPromotedIntegralType; ++Left) {
5186 for (unsigned Right = FirstPromotedIntegralType;
5187 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00005188 QualType LandR[2] = { getArithmeticType(Left),
5189 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005190 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5191 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005192 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005193 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5194 }
5195 }
5196 }
5197
5198 // C++ [over.built]p20:
5199 //
5200 // For every pair (T, VQ), where T is an enumeration or
5201 // pointer to member type and VQ is either volatile or
5202 // empty, there exist candidate operator functions of the form
5203 //
5204 // VQ T& operator=(VQ T&, T);
5205 void addAssignmentMemberPointerOrEnumeralOverloads() {
5206 /// Set of (canonical) types that we've already handled.
5207 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5208
5209 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5210 for (BuiltinCandidateTypeSet::iterator
5211 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5212 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5213 Enum != EnumEnd; ++Enum) {
5214 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5215 continue;
5216
5217 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5218 CandidateSet);
5219 }
5220
5221 for (BuiltinCandidateTypeSet::iterator
5222 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5223 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5224 MemPtr != MemPtrEnd; ++MemPtr) {
5225 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5226 continue;
5227
5228 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5229 CandidateSet);
5230 }
5231 }
5232 }
5233
5234 // C++ [over.built]p19:
5235 //
5236 // For every pair (T, VQ), where T is any type and VQ is either
5237 // volatile or empty, there exist candidate operator functions
5238 // of the form
5239 //
5240 // T*VQ& operator=(T*VQ&, T*);
5241 //
5242 // C++ [over.built]p21:
5243 //
5244 // For every pair (T, VQ), where T is a cv-qualified or
5245 // cv-unqualified object type and VQ is either volatile or
5246 // empty, there exist candidate operator functions of the form
5247 //
5248 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5249 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5250 void addAssignmentPointerOverloads(bool isEqualOp) {
5251 /// Set of (canonical) types that we've already handled.
5252 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5253
5254 for (BuiltinCandidateTypeSet::iterator
5255 Ptr = CandidateTypes[0].pointer_begin(),
5256 PtrEnd = CandidateTypes[0].pointer_end();
5257 Ptr != PtrEnd; ++Ptr) {
5258 // If this is operator=, keep track of the builtin candidates we added.
5259 if (isEqualOp)
5260 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00005261 else if (!(*Ptr)->getPointeeType()->isObjectType())
5262 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005263
5264 // non-volatile version
5265 QualType ParamTypes[2] = {
5266 S.Context.getLValueReferenceType(*Ptr),
5267 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
5268 };
5269 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5270 /*IsAssigmentOperator=*/ isEqualOp);
5271
5272 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5273 VisibleTypeConversionsQuals.hasVolatile()) {
5274 // volatile version
5275 ParamTypes[0] =
5276 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5277 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5278 /*IsAssigmentOperator=*/isEqualOp);
5279 }
5280 }
5281
5282 if (isEqualOp) {
5283 for (BuiltinCandidateTypeSet::iterator
5284 Ptr = CandidateTypes[1].pointer_begin(),
5285 PtrEnd = CandidateTypes[1].pointer_end();
5286 Ptr != PtrEnd; ++Ptr) {
5287 // Make sure we don't add the same candidate twice.
5288 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5289 continue;
5290
Chandler Carruth6df868e2010-12-12 08:17:55 +00005291 QualType ParamTypes[2] = {
5292 S.Context.getLValueReferenceType(*Ptr),
5293 *Ptr,
5294 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005295
5296 // non-volatile version
5297 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5298 /*IsAssigmentOperator=*/true);
5299
5300 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5301 VisibleTypeConversionsQuals.hasVolatile()) {
5302 // volatile version
5303 ParamTypes[0] =
5304 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth6df868e2010-12-12 08:17:55 +00005305 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5306 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005307 }
5308 }
5309 }
5310 }
5311
5312 // C++ [over.built]p18:
5313 //
5314 // For every triple (L, VQ, R), where L is an arithmetic type,
5315 // VQ is either volatile or empty, and R is a promoted
5316 // arithmetic type, there exist candidate operator functions of
5317 // the form
5318 //
5319 // VQ L& operator=(VQ L&, R);
5320 // VQ L& operator*=(VQ L&, R);
5321 // VQ L& operator/=(VQ L&, R);
5322 // VQ L& operator+=(VQ L&, R);
5323 // VQ L& operator-=(VQ L&, R);
5324 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005325 if (!HasArithmeticOrEnumeralCandidateType)
5326 return;
5327
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005328 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
5329 for (unsigned Right = FirstPromotedArithmeticType;
5330 Right < LastPromotedArithmeticType; ++Right) {
5331 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00005332 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005333
5334 // Add this built-in operator as a candidate (VQ is empty).
5335 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00005336 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005337 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5338 /*IsAssigmentOperator=*/isEqualOp);
5339
5340 // Add this built-in operator as a candidate (VQ is 'volatile').
5341 if (VisibleTypeConversionsQuals.hasVolatile()) {
5342 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00005343 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005344 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00005345 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5346 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005347 /*IsAssigmentOperator=*/isEqualOp);
5348 }
5349 }
5350 }
5351
5352 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5353 for (BuiltinCandidateTypeSet::iterator
5354 Vec1 = CandidateTypes[0].vector_begin(),
5355 Vec1End = CandidateTypes[0].vector_end();
5356 Vec1 != Vec1End; ++Vec1) {
5357 for (BuiltinCandidateTypeSet::iterator
5358 Vec2 = CandidateTypes[1].vector_begin(),
5359 Vec2End = CandidateTypes[1].vector_end();
5360 Vec2 != Vec2End; ++Vec2) {
5361 QualType ParamTypes[2];
5362 ParamTypes[1] = *Vec2;
5363 // Add this built-in operator as a candidate (VQ is empty).
5364 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
5365 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5366 /*IsAssigmentOperator=*/isEqualOp);
5367
5368 // Add this built-in operator as a candidate (VQ is 'volatile').
5369 if (VisibleTypeConversionsQuals.hasVolatile()) {
5370 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
5371 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00005372 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5373 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005374 /*IsAssigmentOperator=*/isEqualOp);
5375 }
5376 }
5377 }
5378 }
5379
5380 // C++ [over.built]p22:
5381 //
5382 // For every triple (L, VQ, R), where L is an integral type, VQ
5383 // is either volatile or empty, and R is a promoted integral
5384 // type, there exist candidate operator functions of the form
5385 //
5386 // VQ L& operator%=(VQ L&, R);
5387 // VQ L& operator<<=(VQ L&, R);
5388 // VQ L& operator>>=(VQ L&, R);
5389 // VQ L& operator&=(VQ L&, R);
5390 // VQ L& operator^=(VQ L&, R);
5391 // VQ L& operator|=(VQ L&, R);
5392 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00005393 if (!HasArithmeticOrEnumeralCandidateType)
5394 return;
5395
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005396 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
5397 for (unsigned Right = FirstPromotedIntegralType;
5398 Right < LastPromotedIntegralType; ++Right) {
5399 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00005400 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005401
5402 // Add this built-in operator as a candidate (VQ is empty).
5403 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00005404 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005405 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5406 if (VisibleTypeConversionsQuals.hasVolatile()) {
5407 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00005408 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005409 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
5410 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
5411 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5412 CandidateSet);
5413 }
5414 }
5415 }
5416 }
5417
5418 // C++ [over.operator]p23:
5419 //
5420 // There also exist candidate operator functions of the form
5421 //
5422 // bool operator!(bool);
5423 // bool operator&&(bool, bool);
5424 // bool operator||(bool, bool);
5425 void addExclaimOverload() {
5426 QualType ParamTy = S.Context.BoolTy;
5427 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5428 /*IsAssignmentOperator=*/false,
5429 /*NumContextualBoolArguments=*/1);
5430 }
5431 void addAmpAmpOrPipePipeOverload() {
5432 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
5433 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5434 /*IsAssignmentOperator=*/false,
5435 /*NumContextualBoolArguments=*/2);
5436 }
5437
5438 // C++ [over.built]p13:
5439 //
5440 // For every cv-qualified or cv-unqualified object type T there
5441 // exist candidate operator functions of the form
5442 //
5443 // T* operator+(T*, ptrdiff_t); [ABOVE]
5444 // T& operator[](T*, ptrdiff_t);
5445 // T* operator-(T*, ptrdiff_t); [ABOVE]
5446 // T* operator+(ptrdiff_t, T*); [ABOVE]
5447 // T& operator[](ptrdiff_t, T*);
5448 void addSubscriptOverloads() {
5449 for (BuiltinCandidateTypeSet::iterator
5450 Ptr = CandidateTypes[0].pointer_begin(),
5451 PtrEnd = CandidateTypes[0].pointer_end();
5452 Ptr != PtrEnd; ++Ptr) {
5453 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
5454 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00005455 if (!PointeeType->isObjectType())
5456 continue;
5457
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005458 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5459
5460 // T& operator[](T*, ptrdiff_t)
5461 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5462 }
5463
5464 for (BuiltinCandidateTypeSet::iterator
5465 Ptr = CandidateTypes[1].pointer_begin(),
5466 PtrEnd = CandidateTypes[1].pointer_end();
5467 Ptr != PtrEnd; ++Ptr) {
5468 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
5469 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00005470 if (!PointeeType->isObjectType())
5471 continue;
5472
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005473 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5474
5475 // T& operator[](ptrdiff_t, T*)
5476 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5477 }
5478 }
5479
5480 // C++ [over.built]p11:
5481 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5482 // C1 is the same type as C2 or is a derived class of C2, T is an object
5483 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5484 // there exist candidate operator functions of the form
5485 //
5486 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5487 //
5488 // where CV12 is the union of CV1 and CV2.
5489 void addArrowStarOverloads() {
5490 for (BuiltinCandidateTypeSet::iterator
5491 Ptr = CandidateTypes[0].pointer_begin(),
5492 PtrEnd = CandidateTypes[0].pointer_end();
5493 Ptr != PtrEnd; ++Ptr) {
5494 QualType C1Ty = (*Ptr);
5495 QualType C1;
5496 QualifierCollector Q1;
5497 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5498 if (!isa<RecordType>(C1))
5499 continue;
5500 // heuristic to reduce number of builtin candidates in the set.
5501 // Add volatile/restrict version only if there are conversions to a
5502 // volatile/restrict type.
5503 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5504 continue;
5505 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5506 continue;
5507 for (BuiltinCandidateTypeSet::iterator
5508 MemPtr = CandidateTypes[1].member_pointer_begin(),
5509 MemPtrEnd = CandidateTypes[1].member_pointer_end();
5510 MemPtr != MemPtrEnd; ++MemPtr) {
5511 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5512 QualType C2 = QualType(mptr->getClass(), 0);
5513 C2 = C2.getUnqualifiedType();
5514 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
5515 break;
5516 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5517 // build CV12 T&
5518 QualType T = mptr->getPointeeType();
5519 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5520 T.isVolatileQualified())
5521 continue;
5522 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5523 T.isRestrictQualified())
5524 continue;
5525 T = Q1.apply(S.Context, T);
5526 QualType ResultTy = S.Context.getLValueReferenceType(T);
5527 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5528 }
5529 }
5530 }
5531
5532 // Note that we don't consider the first argument, since it has been
5533 // contextually converted to bool long ago. The candidates below are
5534 // therefore added as binary.
5535 //
5536 // C++ [over.built]p25:
5537 // For every type T, where T is a pointer, pointer-to-member, or scoped
5538 // enumeration type, there exist candidate operator functions of the form
5539 //
5540 // T operator?(bool, T, T);
5541 //
5542 void addConditionalOperatorOverloads() {
5543 /// Set of (canonical) types that we've already handled.
5544 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5545
5546 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5547 for (BuiltinCandidateTypeSet::iterator
5548 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5549 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5550 Ptr != PtrEnd; ++Ptr) {
5551 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5552 continue;
5553
5554 QualType ParamTypes[2] = { *Ptr, *Ptr };
5555 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5556 }
5557
5558 for (BuiltinCandidateTypeSet::iterator
5559 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5560 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5561 MemPtr != MemPtrEnd; ++MemPtr) {
5562 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5563 continue;
5564
5565 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5566 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
5567 }
5568
5569 if (S.getLangOptions().CPlusPlus0x) {
5570 for (BuiltinCandidateTypeSet::iterator
5571 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5572 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5573 Enum != EnumEnd; ++Enum) {
5574 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
5575 continue;
5576
5577 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5578 continue;
5579
5580 QualType ParamTypes[2] = { *Enum, *Enum };
5581 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
5582 }
5583 }
5584 }
5585 }
5586};
5587
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005588} // end anonymous namespace
5589
5590/// AddBuiltinOperatorCandidates - Add the appropriate built-in
5591/// operator overloads to the candidate set (C++ [over.built]), based
5592/// on the operator @p Op and the arguments given. For example, if the
5593/// operator is a binary '+', this routine might add "int
5594/// operator+(int, int)" to cover integer addition.
5595void
5596Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
5597 SourceLocation OpLoc,
5598 Expr **Args, unsigned NumArgs,
5599 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005600 // Find all of the types that the arguments can convert to, but only
5601 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00005602 // that make use of these types. Also record whether we encounter non-record
5603 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005604 Qualifiers VisibleTypeConversionsQuals;
5605 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00005606 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5607 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00005608
5609 bool HasNonRecordCandidateType = false;
5610 bool HasArithmeticOrEnumeralCandidateType = false;
Douglas Gregorfec56e72010-11-03 17:00:07 +00005611 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
5612 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5613 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
5614 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
5615 OpLoc,
5616 true,
5617 (Op == OO_Exclaim ||
5618 Op == OO_AmpAmp ||
5619 Op == OO_PipePipe),
5620 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00005621 HasNonRecordCandidateType = HasNonRecordCandidateType ||
5622 CandidateTypes[ArgIdx].hasNonRecordTypes();
5623 HasArithmeticOrEnumeralCandidateType =
5624 HasArithmeticOrEnumeralCandidateType ||
5625 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00005626 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005627
Chandler Carruth6a577462010-12-13 01:44:01 +00005628 // Exit early when no non-record types have been added to the candidate set
5629 // for any of the arguments to the operator.
5630 if (!HasNonRecordCandidateType)
5631 return;
5632
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005633 // Setup an object to manage the common state for building overloads.
5634 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
5635 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00005636 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005637 CandidateTypes, CandidateSet);
5638
5639 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005640 switch (Op) {
5641 case OO_None:
5642 case NUM_OVERLOADED_OPERATORS:
5643 assert(false && "Expected an overloaded operator");
5644 break;
5645
Chandler Carruthabb71842010-12-12 08:51:33 +00005646 case OO_New:
5647 case OO_Delete:
5648 case OO_Array_New:
5649 case OO_Array_Delete:
5650 case OO_Call:
5651 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
5652 break;
5653
5654 case OO_Comma:
5655 case OO_Arrow:
5656 // C++ [over.match.oper]p3:
5657 // -- For the operator ',', the unary operator '&', or the
5658 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00005659 break;
5660
5661 case OO_Plus: // '+' is either unary or binary
Chandler Carruth32fe0d02010-12-12 08:41:34 +00005662 if (NumArgs == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005663 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00005664 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00005665
5666 case OO_Minus: // '-' is either unary or binary
Chandler Carruthfe622742010-12-12 08:39:38 +00005667 if (NumArgs == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005668 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00005669 } else {
5670 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
5671 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5672 }
Douglas Gregor74253732008-11-19 15:42:04 +00005673 break;
5674
Chandler Carruthabb71842010-12-12 08:51:33 +00005675 case OO_Star: // '*' is either unary or binary
Douglas Gregor74253732008-11-19 15:42:04 +00005676 if (NumArgs == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00005677 OpBuilder.addUnaryStarPointerOverloads();
5678 else
5679 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5680 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005681
Chandler Carruthabb71842010-12-12 08:51:33 +00005682 case OO_Slash:
5683 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00005684 break;
Douglas Gregor74253732008-11-19 15:42:04 +00005685
5686 case OO_PlusPlus:
5687 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005688 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
5689 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00005690 break;
5691
Douglas Gregor19b7b152009-08-24 13:43:27 +00005692 case OO_EqualEqual:
5693 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005694 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00005695 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00005696
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005697 case OO_Less:
5698 case OO_Greater:
5699 case OO_LessEqual:
5700 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00005701 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00005702 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
5703 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005704
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005705 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005706 case OO_Caret:
5707 case OO_Pipe:
5708 case OO_LessLess:
5709 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005710 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005711 break;
5712
Chandler Carruthabb71842010-12-12 08:51:33 +00005713 case OO_Amp: // '&' is either unary or binary
5714 if (NumArgs == 1)
5715 // C++ [over.match.oper]p3:
5716 // -- For the operator ',', the unary operator '&', or the
5717 // operator '->', the built-in candidates set is empty.
5718 break;
5719
5720 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
5721 break;
5722
5723 case OO_Tilde:
5724 OpBuilder.addUnaryTildePromotedIntegralOverloads();
5725 break;
5726
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005727 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005728 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00005729 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005730
5731 case OO_PlusEqual:
5732 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005733 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005734 // Fall through.
5735
5736 case OO_StarEqual:
5737 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005738 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005739 break;
5740
5741 case OO_PercentEqual:
5742 case OO_LessLessEqual:
5743 case OO_GreaterGreaterEqual:
5744 case OO_AmpEqual:
5745 case OO_CaretEqual:
5746 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005747 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005748 break;
5749
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005750 case OO_Exclaim:
5751 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00005752 break;
Douglas Gregor74253732008-11-19 15:42:04 +00005753
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005754 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005755 case OO_PipePipe:
5756 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005757 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005758
5759 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005760 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005761 break;
5762
5763 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005764 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005765 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005766
5767 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005768 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00005769 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5770 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005771 }
5772}
5773
Douglas Gregorfa047642009-02-04 00:32:51 +00005774/// \brief Add function candidates found via argument-dependent lookup
5775/// to the set of overloading candidates.
5776///
5777/// This routine performs argument-dependent name lookup based on the
5778/// given function name (which may also be an operator name) and adds
5779/// all of the overload candidates found by ADL to the overload
5780/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00005781void
Douglas Gregorfa047642009-02-04 00:32:51 +00005782Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00005783 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00005784 Expr **Args, unsigned NumArgs,
John McCalld5532b62009-11-23 01:53:49 +00005785 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005786 OverloadCandidateSet& CandidateSet,
5787 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00005788 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00005789
John McCalla113e722010-01-26 06:04:06 +00005790 // FIXME: This approach for uniquing ADL results (and removing
5791 // redundant candidates from the set) relies on pointer-equality,
5792 // which means we need to key off the canonical decl. However,
5793 // always going back to the canonical decl might not get us the
5794 // right set of default arguments. What default arguments are
5795 // we supposed to consider on ADL candidates, anyway?
5796
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005797 // FIXME: Pass in the explicit template arguments?
John McCall7edb5fd2010-01-26 07:16:45 +00005798 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00005799
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005800 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005801 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5802 CandEnd = CandidateSet.end();
5803 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00005804 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00005805 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00005806 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00005807 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00005808 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005809
5810 // For each of the ADL candidates we found, add it to the overload
5811 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00005812 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00005813 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00005814 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00005815 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005816 continue;
5817
John McCall9aa472c2010-03-19 07:35:19 +00005818 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00005819 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005820 } else
John McCall6e266892010-01-26 03:27:55 +00005821 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00005822 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00005823 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00005824 }
Douglas Gregorfa047642009-02-04 00:32:51 +00005825}
5826
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005827/// isBetterOverloadCandidate - Determines whether the first overload
5828/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00005829bool
John McCall120d63c2010-08-24 20:38:10 +00005830isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00005831 const OverloadCandidate &Cand1,
5832 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005833 SourceLocation Loc,
5834 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005835 // Define viable functions to be better candidates than non-viable
5836 // functions.
5837 if (!Cand2.Viable)
5838 return Cand1.Viable;
5839 else if (!Cand1.Viable)
5840 return false;
5841
Douglas Gregor88a35142008-12-22 05:46:06 +00005842 // C++ [over.match.best]p1:
5843 //
5844 // -- if F is a static member function, ICS1(F) is defined such
5845 // that ICS1(F) is neither better nor worse than ICS1(G) for
5846 // any function G, and, symmetrically, ICS1(G) is neither
5847 // better nor worse than ICS1(F).
5848 unsigned StartArg = 0;
5849 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5850 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005851
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005852 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00005853 // A viable function F1 is defined to be a better function than another
5854 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005855 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005856 unsigned NumArgs = Cand1.Conversions.size();
5857 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5858 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005859 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00005860 switch (CompareImplicitConversionSequences(S,
5861 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005862 Cand2.Conversions[ArgIdx])) {
5863 case ImplicitConversionSequence::Better:
5864 // Cand1 has a better conversion sequence.
5865 HasBetterConversion = true;
5866 break;
5867
5868 case ImplicitConversionSequence::Worse:
5869 // Cand1 can't be better than Cand2.
5870 return false;
5871
5872 case ImplicitConversionSequence::Indistinguishable:
5873 // Do nothing.
5874 break;
5875 }
5876 }
5877
Mike Stump1eb44332009-09-09 15:08:12 +00005878 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005879 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005880 if (HasBetterConversion)
5881 return true;
5882
Mike Stump1eb44332009-09-09 15:08:12 +00005883 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005884 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00005885 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005886 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5887 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005888
5889 // -- F1 and F2 are function template specializations, and the function
5890 // template for F1 is more specialized than the template for F2
5891 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005892 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00005893 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5894 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005895 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00005896 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5897 Cand2.Function->getPrimaryTemplate(),
5898 Loc,
Douglas Gregor5d7d3752009-09-14 23:02:14 +00005899 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00005900 : TPOC_Call,
5901 NumArgs))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005902 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005903
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005904 // -- the context is an initialization by user-defined conversion
5905 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5906 // from the return type of F1 to the destination type (i.e.,
5907 // the type of the entity being initialized) is a better
5908 // conversion sequence than the standard conversion sequence
5909 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005910 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00005911 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005912 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall120d63c2010-08-24 20:38:10 +00005913 switch (CompareStandardConversionSequences(S,
5914 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005915 Cand2.FinalConversion)) {
5916 case ImplicitConversionSequence::Better:
5917 // Cand1 has a better conversion sequence.
5918 return true;
5919
5920 case ImplicitConversionSequence::Worse:
5921 // Cand1 can't be better than Cand2.
5922 return false;
5923
5924 case ImplicitConversionSequence::Indistinguishable:
5925 // Do nothing
5926 break;
5927 }
5928 }
5929
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005930 return false;
5931}
5932
Mike Stump1eb44332009-09-09 15:08:12 +00005933/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00005934/// within an overload candidate set.
5935///
5936/// \param CandidateSet the set of candidate functions.
5937///
5938/// \param Loc the location of the function name (or operator symbol) for
5939/// which overload resolution occurs.
5940///
Mike Stump1eb44332009-09-09 15:08:12 +00005941/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00005942/// function, Best points to the candidate function found.
5943///
5944/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00005945OverloadingResult
5946OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00005947 iterator &Best,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005948 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005949 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00005950 Best = end();
5951 for (iterator Cand = begin(); Cand != end(); ++Cand) {
5952 if (Cand->Viable)
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005953 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
5954 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005955 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005956 }
5957
5958 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00005959 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005960 return OR_No_Viable_Function;
5961
5962 // Make sure that this function is better than every other viable
5963 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00005964 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00005965 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005966 Cand != Best &&
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005967 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
5968 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00005969 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005970 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005971 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005972 }
Mike Stump1eb44332009-09-09 15:08:12 +00005973
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005974 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005975 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00005976 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005977 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005978 return OR_Deleted;
5979
Douglas Gregore0762c92009-06-19 23:52:42 +00005980 // C++ [basic.def.odr]p2:
5981 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00005982 // when referred to from a potentially-evaluated expression. [Note: this
5983 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00005984 // (clause 13), user-defined conversions (12.3.2), allocation function for
5985 // placement new (5.3.4), as well as non-default initialization (8.5).
5986 if (Best->Function)
John McCall120d63c2010-08-24 20:38:10 +00005987 S.MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor9b623632010-10-12 23:32:35 +00005988
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005989 return OR_Success;
5990}
5991
John McCall3c80f572010-01-12 02:15:36 +00005992namespace {
5993
5994enum OverloadCandidateKind {
5995 oc_function,
5996 oc_method,
5997 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00005998 oc_function_template,
5999 oc_method_template,
6000 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00006001 oc_implicit_default_constructor,
6002 oc_implicit_copy_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00006003 oc_implicit_copy_assignment
John McCall3c80f572010-01-12 02:15:36 +00006004};
6005
John McCall220ccbf2010-01-13 00:25:19 +00006006OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6007 FunctionDecl *Fn,
6008 std::string &Description) {
6009 bool isTemplate = false;
6010
6011 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6012 isTemplate = true;
6013 Description = S.getTemplateArgumentBindingsText(
6014 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6015 }
John McCallb1622a12010-01-06 09:43:14 +00006016
6017 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00006018 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00006019 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00006020
John McCall3c80f572010-01-12 02:15:36 +00006021 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
6022 : oc_implicit_default_constructor;
John McCallb1622a12010-01-06 09:43:14 +00006023 }
6024
6025 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6026 // This actually gets spelled 'candidate function' for now, but
6027 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00006028 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00006029 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00006030
Douglas Gregor3e9438b2010-09-27 22:37:28 +00006031 assert(Meth->isCopyAssignmentOperator()
John McCallb1622a12010-01-06 09:43:14 +00006032 && "implicit method is not copy assignment operator?");
John McCall3c80f572010-01-12 02:15:36 +00006033 return oc_implicit_copy_assignment;
6034 }
6035
John McCall220ccbf2010-01-13 00:25:19 +00006036 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00006037}
6038
6039} // end anonymous namespace
6040
6041// Notes the location of an overload candidate.
6042void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCall220ccbf2010-01-13 00:25:19 +00006043 std::string FnDesc;
6044 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6045 Diag(Fn->getLocation(), diag::note_ovl_candidate)
6046 << (unsigned) K << FnDesc;
John McCallb1622a12010-01-06 09:43:14 +00006047}
6048
John McCall1d318332010-01-12 00:44:57 +00006049/// Diagnoses an ambiguous conversion. The partial diagnostic is the
6050/// "lead" diagnostic; it will be given two arguments, the source and
6051/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00006052void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6053 Sema &S,
6054 SourceLocation CaretLoc,
6055 const PartialDiagnostic &PDiag) const {
6056 S.Diag(CaretLoc, PDiag)
6057 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall1d318332010-01-12 00:44:57 +00006058 for (AmbiguousConversionSequence::const_iterator
John McCall120d63c2010-08-24 20:38:10 +00006059 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6060 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00006061 }
John McCall81201622010-01-08 04:41:39 +00006062}
6063
John McCall1d318332010-01-12 00:44:57 +00006064namespace {
6065
John McCalladbb8f82010-01-13 09:16:55 +00006066void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6067 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6068 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00006069 assert(Cand->Function && "for now, candidate must be a function");
6070 FunctionDecl *Fn = Cand->Function;
6071
6072 // There's a conversion slot for the object argument if this is a
6073 // non-constructor method. Note that 'I' corresponds the
6074 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00006075 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00006076 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00006077 if (I == 0)
6078 isObjectArgument = true;
6079 else
6080 I--;
John McCall220ccbf2010-01-13 00:25:19 +00006081 }
6082
John McCall220ccbf2010-01-13 00:25:19 +00006083 std::string FnDesc;
6084 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6085
John McCalladbb8f82010-01-13 09:16:55 +00006086 Expr *FromExpr = Conv.Bad.FromExpr;
6087 QualType FromTy = Conv.Bad.getFromType();
6088 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00006089
John McCall5920dbb2010-02-02 02:42:52 +00006090 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00006091 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00006092 Expr *E = FromExpr->IgnoreParens();
6093 if (isa<UnaryOperator>(E))
6094 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00006095 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00006096
6097 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6098 << (unsigned) FnKind << FnDesc
6099 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6100 << ToTy << Name << I+1;
6101 return;
6102 }
6103
John McCall258b2032010-01-23 08:10:49 +00006104 // Do some hand-waving analysis to see if the non-viability is due
6105 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00006106 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6107 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6108 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6109 CToTy = RT->getPointeeType();
6110 else {
6111 // TODO: detect and diagnose the full richness of const mismatches.
6112 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6113 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6114 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6115 }
6116
6117 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6118 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6119 // It is dumb that we have to do this here.
6120 while (isa<ArrayType>(CFromTy))
6121 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6122 while (isa<ArrayType>(CToTy))
6123 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6124
6125 Qualifiers FromQs = CFromTy.getQualifiers();
6126 Qualifiers ToQs = CToTy.getQualifiers();
6127
6128 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6129 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6130 << (unsigned) FnKind << FnDesc
6131 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6132 << FromTy
6133 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6134 << (unsigned) isObjectArgument << I+1;
6135 return;
6136 }
6137
6138 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6139 assert(CVR && "unexpected qualifiers mismatch");
6140
6141 if (isObjectArgument) {
6142 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6143 << (unsigned) FnKind << FnDesc
6144 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6145 << FromTy << (CVR - 1);
6146 } else {
6147 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6148 << (unsigned) FnKind << FnDesc
6149 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6150 << FromTy << (CVR - 1) << I+1;
6151 }
6152 return;
6153 }
6154
John McCall258b2032010-01-23 08:10:49 +00006155 // Diagnose references or pointers to incomplete types differently,
6156 // since it's far from impossible that the incompleteness triggered
6157 // the failure.
6158 QualType TempFromTy = FromTy.getNonReferenceType();
6159 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6160 TempFromTy = PTy->getPointeeType();
6161 if (TempFromTy->isIncompleteType()) {
6162 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6163 << (unsigned) FnKind << FnDesc
6164 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6165 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
6166 return;
6167 }
6168
Douglas Gregor85789812010-06-30 23:01:39 +00006169 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006170 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00006171 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
6172 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
6173 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6174 FromPtrTy->getPointeeType()) &&
6175 !FromPtrTy->getPointeeType()->isIncompleteType() &&
6176 !ToPtrTy->getPointeeType()->isIncompleteType() &&
6177 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
6178 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006179 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00006180 }
6181 } else if (const ObjCObjectPointerType *FromPtrTy
6182 = FromTy->getAs<ObjCObjectPointerType>()) {
6183 if (const ObjCObjectPointerType *ToPtrTy
6184 = ToTy->getAs<ObjCObjectPointerType>())
6185 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
6186 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
6187 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6188 FromPtrTy->getPointeeType()) &&
6189 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006190 BaseToDerivedConversion = 2;
6191 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
6192 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
6193 !FromTy->isIncompleteType() &&
6194 !ToRefTy->getPointeeType()->isIncompleteType() &&
6195 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
6196 BaseToDerivedConversion = 3;
6197 }
6198
6199 if (BaseToDerivedConversion) {
Douglas Gregor85789812010-06-30 23:01:39 +00006200 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006201 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00006202 << (unsigned) FnKind << FnDesc
6203 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006204 << (BaseToDerivedConversion - 1)
Douglas Gregor85789812010-06-30 23:01:39 +00006205 << FromTy << ToTy << I+1;
6206 return;
6207 }
6208
John McCall651f3ee2010-01-14 03:28:57 +00006209 // TODO: specialize more based on the kind of mismatch
John McCall220ccbf2010-01-13 00:25:19 +00006210 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
6211 << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00006212 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalle81e15e2010-01-14 00:56:20 +00006213 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCalladbb8f82010-01-13 09:16:55 +00006214}
6215
6216void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
6217 unsigned NumFormalArgs) {
6218 // TODO: treat calls to a missing default constructor as a special case
6219
6220 FunctionDecl *Fn = Cand->Function;
6221 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
6222
6223 unsigned MinParams = Fn->getMinRequiredArguments();
6224
6225 // at least / at most / exactly
6226 unsigned mode, modeCount;
6227 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00006228 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
6229 (Cand->FailureKind == ovl_fail_bad_deduction &&
6230 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00006231 if (MinParams != FnTy->getNumArgs() ||
6232 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00006233 mode = 0; // "at least"
6234 else
6235 mode = 2; // "exactly"
6236 modeCount = MinParams;
6237 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00006238 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
6239 (Cand->FailureKind == ovl_fail_bad_deduction &&
6240 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00006241 if (MinParams != FnTy->getNumArgs())
6242 mode = 1; // "at most"
6243 else
6244 mode = 2; // "exactly"
6245 modeCount = FnTy->getNumArgs();
6246 }
6247
6248 std::string Description;
6249 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6250
6251 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregora18592e2010-05-08 18:13:28 +00006252 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
6253 << modeCount << NumFormalArgs;
John McCall220ccbf2010-01-13 00:25:19 +00006254}
6255
John McCall342fec42010-02-01 18:53:26 +00006256/// Diagnose a failed template-argument deduction.
6257void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6258 Expr **Args, unsigned NumArgs) {
6259 FunctionDecl *Fn = Cand->Function; // pattern
6260
Douglas Gregora9333192010-05-08 17:41:32 +00006261 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00006262 NamedDecl *ParamD;
6263 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
6264 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
6265 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00006266 switch (Cand->DeductionFailure.Result) {
6267 case Sema::TDK_Success:
6268 llvm_unreachable("TDK_success while diagnosing bad deduction");
6269
6270 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00006271 assert(ParamD && "no parameter found for incomplete deduction result");
6272 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
6273 << ParamD->getDeclName();
6274 return;
6275 }
6276
John McCall57e97782010-08-05 09:05:08 +00006277 case Sema::TDK_Underqualified: {
6278 assert(ParamD && "no parameter found for bad qualifiers deduction result");
6279 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
6280
6281 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
6282
6283 // Param will have been canonicalized, but it should just be a
6284 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00006285 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00006286 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00006287 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00006288 assert(S.Context.hasSameType(Param, NonCanonParam));
6289
6290 // Arg has also been canonicalized, but there's nothing we can do
6291 // about that. It also doesn't matter as much, because it won't
6292 // have any template parameters in it (because deduction isn't
6293 // done on dependent types).
6294 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
6295
6296 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
6297 << ParamD->getDeclName() << Arg << NonCanonParam;
6298 return;
6299 }
6300
6301 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00006302 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00006303 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00006304 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00006305 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00006306 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00006307 which = 1;
6308 else {
Douglas Gregora9333192010-05-08 17:41:32 +00006309 which = 2;
6310 }
6311
6312 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
6313 << which << ParamD->getDeclName()
6314 << *Cand->DeductionFailure.getFirstArg()
6315 << *Cand->DeductionFailure.getSecondArg();
6316 return;
6317 }
Douglas Gregora18592e2010-05-08 18:13:28 +00006318
Douglas Gregorf1a84452010-05-08 19:15:54 +00006319 case Sema::TDK_InvalidExplicitArguments:
6320 assert(ParamD && "no parameter found for invalid explicit arguments");
6321 if (ParamD->getDeclName())
6322 S.Diag(Fn->getLocation(),
6323 diag::note_ovl_candidate_explicit_arg_mismatch_named)
6324 << ParamD->getDeclName();
6325 else {
6326 int index = 0;
6327 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
6328 index = TTP->getIndex();
6329 else if (NonTypeTemplateParmDecl *NTTP
6330 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
6331 index = NTTP->getIndex();
6332 else
6333 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
6334 S.Diag(Fn->getLocation(),
6335 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
6336 << (index + 1);
6337 }
6338 return;
6339
Douglas Gregora18592e2010-05-08 18:13:28 +00006340 case Sema::TDK_TooManyArguments:
6341 case Sema::TDK_TooFewArguments:
6342 DiagnoseArityMismatch(S, Cand, NumArgs);
6343 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00006344
6345 case Sema::TDK_InstantiationDepth:
6346 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
6347 return;
6348
6349 case Sema::TDK_SubstitutionFailure: {
6350 std::string ArgString;
6351 if (TemplateArgumentList *Args
6352 = Cand->DeductionFailure.getTemplateArgumentList())
6353 ArgString = S.getTemplateArgumentBindingsText(
6354 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
6355 *Args);
6356 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
6357 << ArgString;
6358 return;
6359 }
Douglas Gregora9333192010-05-08 17:41:32 +00006360
John McCall342fec42010-02-01 18:53:26 +00006361 // TODO: diagnose these individually, then kill off
6362 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00006363 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00006364 case Sema::TDK_FailedOverloadResolution:
6365 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
6366 return;
6367 }
6368}
6369
6370/// Generates a 'note' diagnostic for an overload candidate. We've
6371/// already generated a primary error at the call site.
6372///
6373/// It really does need to be a single diagnostic with its caret
6374/// pointed at the candidate declaration. Yes, this creates some
6375/// major challenges of technical writing. Yes, this makes pointing
6376/// out problems with specific arguments quite awkward. It's still
6377/// better than generating twenty screens of text for every failed
6378/// overload.
6379///
6380/// It would be great to be able to express per-candidate problems
6381/// more richly for those diagnostic clients that cared, but we'd
6382/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00006383void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
6384 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00006385 FunctionDecl *Fn = Cand->Function;
6386
John McCall81201622010-01-08 04:41:39 +00006387 // Note deleted candidates, but only if they're viable.
John McCall3c80f572010-01-12 02:15:36 +00006388 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCall220ccbf2010-01-13 00:25:19 +00006389 std::string FnDesc;
6390 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00006391
6392 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00006393 << FnKind << FnDesc << Fn->isDeleted();
John McCalla1d7d622010-01-08 00:58:21 +00006394 return;
John McCall81201622010-01-08 04:41:39 +00006395 }
6396
John McCall220ccbf2010-01-13 00:25:19 +00006397 // We don't really have anything else to say about viable candidates.
6398 if (Cand->Viable) {
6399 S.NoteOverloadCandidate(Fn);
6400 return;
6401 }
John McCall1d318332010-01-12 00:44:57 +00006402
John McCalladbb8f82010-01-13 09:16:55 +00006403 switch (Cand->FailureKind) {
6404 case ovl_fail_too_many_arguments:
6405 case ovl_fail_too_few_arguments:
6406 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00006407
John McCalladbb8f82010-01-13 09:16:55 +00006408 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00006409 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
6410
John McCall717e8912010-01-23 05:17:32 +00006411 case ovl_fail_trivial_conversion:
6412 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00006413 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00006414 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00006415
John McCallb1bdc622010-02-25 01:37:24 +00006416 case ovl_fail_bad_conversion: {
6417 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
6418 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00006419 if (Cand->Conversions[I].isBad())
6420 return DiagnoseBadConversion(S, Cand, I);
6421
6422 // FIXME: this currently happens when we're called from SemaInit
6423 // when user-conversion overload fails. Figure out how to handle
6424 // those conditions and diagnose them well.
6425 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00006426 }
John McCallb1bdc622010-02-25 01:37:24 +00006427 }
John McCalla1d7d622010-01-08 00:58:21 +00006428}
6429
6430void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
6431 // Desugar the type of the surrogate down to a function type,
6432 // retaining as many typedefs as possible while still showing
6433 // the function type (and, therefore, its parameter types).
6434 QualType FnType = Cand->Surrogate->getConversionType();
6435 bool isLValueReference = false;
6436 bool isRValueReference = false;
6437 bool isPointer = false;
6438 if (const LValueReferenceType *FnTypeRef =
6439 FnType->getAs<LValueReferenceType>()) {
6440 FnType = FnTypeRef->getPointeeType();
6441 isLValueReference = true;
6442 } else if (const RValueReferenceType *FnTypeRef =
6443 FnType->getAs<RValueReferenceType>()) {
6444 FnType = FnTypeRef->getPointeeType();
6445 isRValueReference = true;
6446 }
6447 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
6448 FnType = FnTypePtr->getPointeeType();
6449 isPointer = true;
6450 }
6451 // Desugar down to a function type.
6452 FnType = QualType(FnType->getAs<FunctionType>(), 0);
6453 // Reconstruct the pointer/reference as appropriate.
6454 if (isPointer) FnType = S.Context.getPointerType(FnType);
6455 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
6456 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
6457
6458 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
6459 << FnType;
6460}
6461
6462void NoteBuiltinOperatorCandidate(Sema &S,
6463 const char *Opc,
6464 SourceLocation OpLoc,
6465 OverloadCandidate *Cand) {
6466 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
6467 std::string TypeStr("operator");
6468 TypeStr += Opc;
6469 TypeStr += "(";
6470 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6471 if (Cand->Conversions.size() == 1) {
6472 TypeStr += ")";
6473 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6474 } else {
6475 TypeStr += ", ";
6476 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6477 TypeStr += ")";
6478 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
6479 }
6480}
6481
6482void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
6483 OverloadCandidate *Cand) {
6484 unsigned NoOperands = Cand->Conversions.size();
6485 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
6486 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00006487 if (ICS.isBad()) break; // all meaningless after first invalid
6488 if (!ICS.isAmbiguous()) continue;
6489
John McCall120d63c2010-08-24 20:38:10 +00006490 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006491 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00006492 }
6493}
6494
John McCall1b77e732010-01-15 23:32:50 +00006495SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
6496 if (Cand->Function)
6497 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00006498 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00006499 return Cand->Surrogate->getLocation();
6500 return SourceLocation();
6501}
6502
John McCallbf65c0b2010-01-12 00:48:53 +00006503struct CompareOverloadCandidatesForDisplay {
6504 Sema &S;
6505 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00006506
6507 bool operator()(const OverloadCandidate *L,
6508 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00006509 // Fast-path this check.
6510 if (L == R) return false;
6511
John McCall81201622010-01-08 04:41:39 +00006512 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00006513 if (L->Viable) {
6514 if (!R->Viable) return true;
6515
6516 // TODO: introduce a tri-valued comparison for overload
6517 // candidates. Would be more worthwhile if we had a sort
6518 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00006519 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6520 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00006521 } else if (R->Viable)
6522 return false;
John McCall81201622010-01-08 04:41:39 +00006523
John McCall1b77e732010-01-15 23:32:50 +00006524 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00006525
John McCall1b77e732010-01-15 23:32:50 +00006526 // Criteria by which we can sort non-viable candidates:
6527 if (!L->Viable) {
6528 // 1. Arity mismatches come after other candidates.
6529 if (L->FailureKind == ovl_fail_too_many_arguments ||
6530 L->FailureKind == ovl_fail_too_few_arguments)
6531 return false;
6532 if (R->FailureKind == ovl_fail_too_many_arguments ||
6533 R->FailureKind == ovl_fail_too_few_arguments)
6534 return true;
John McCall81201622010-01-08 04:41:39 +00006535
John McCall717e8912010-01-23 05:17:32 +00006536 // 2. Bad conversions come first and are ordered by the number
6537 // of bad conversions and quality of good conversions.
6538 if (L->FailureKind == ovl_fail_bad_conversion) {
6539 if (R->FailureKind != ovl_fail_bad_conversion)
6540 return true;
6541
6542 // If there's any ordering between the defined conversions...
6543 // FIXME: this might not be transitive.
6544 assert(L->Conversions.size() == R->Conversions.size());
6545
6546 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00006547 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6548 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00006549 switch (CompareImplicitConversionSequences(S,
6550 L->Conversions[I],
6551 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00006552 case ImplicitConversionSequence::Better:
6553 leftBetter++;
6554 break;
6555
6556 case ImplicitConversionSequence::Worse:
6557 leftBetter--;
6558 break;
6559
6560 case ImplicitConversionSequence::Indistinguishable:
6561 break;
6562 }
6563 }
6564 if (leftBetter > 0) return true;
6565 if (leftBetter < 0) return false;
6566
6567 } else if (R->FailureKind == ovl_fail_bad_conversion)
6568 return false;
6569
John McCall1b77e732010-01-15 23:32:50 +00006570 // TODO: others?
6571 }
6572
6573 // Sort everything else by location.
6574 SourceLocation LLoc = GetLocationForCandidate(L);
6575 SourceLocation RLoc = GetLocationForCandidate(R);
6576
6577 // Put candidates without locations (e.g. builtins) at the end.
6578 if (LLoc.isInvalid()) return false;
6579 if (RLoc.isInvalid()) return true;
6580
6581 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00006582 }
6583};
6584
John McCall717e8912010-01-23 05:17:32 +00006585/// CompleteNonViableCandidate - Normally, overload resolution only
6586/// computes up to the first
6587void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6588 Expr **Args, unsigned NumArgs) {
6589 assert(!Cand->Viable);
6590
6591 // Don't do anything on failures other than bad conversion.
6592 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6593
6594 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00006595 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCall717e8912010-01-23 05:17:32 +00006596 unsigned ConvCount = Cand->Conversions.size();
6597 while (true) {
6598 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6599 ConvIdx++;
6600 if (Cand->Conversions[ConvIdx - 1].isBad())
6601 break;
6602 }
6603
6604 if (ConvIdx == ConvCount)
6605 return;
6606
John McCallb1bdc622010-02-25 01:37:24 +00006607 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6608 "remaining conversion is initialized?");
6609
Douglas Gregor23ef6c02010-04-16 17:45:54 +00006610 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00006611 // operation somehow.
6612 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00006613
6614 const FunctionProtoType* Proto;
6615 unsigned ArgIdx = ConvIdx;
6616
6617 if (Cand->IsSurrogate) {
6618 QualType ConvType
6619 = Cand->Surrogate->getConversionType().getNonReferenceType();
6620 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6621 ConvType = ConvPtrType->getPointeeType();
6622 Proto = ConvType->getAs<FunctionProtoType>();
6623 ArgIdx--;
6624 } else if (Cand->Function) {
6625 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6626 if (isa<CXXMethodDecl>(Cand->Function) &&
6627 !isa<CXXConstructorDecl>(Cand->Function))
6628 ArgIdx--;
6629 } else {
6630 // Builtin binary operator with a bad first conversion.
6631 assert(ConvCount <= 3);
6632 for (; ConvIdx != ConvCount; ++ConvIdx)
6633 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006634 = TryCopyInitialization(S, Args[ConvIdx],
6635 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6636 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00006637 /*InOverloadResolution*/ true);
John McCall717e8912010-01-23 05:17:32 +00006638 return;
6639 }
6640
6641 // Fill in the rest of the conversions.
6642 unsigned NumArgsInProto = Proto->getNumArgs();
6643 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6644 if (ArgIdx < NumArgsInProto)
6645 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006646 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6647 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00006648 /*InOverloadResolution=*/true);
John McCall717e8912010-01-23 05:17:32 +00006649 else
6650 Cand->Conversions[ConvIdx].setEllipsis();
6651 }
6652}
6653
John McCalla1d7d622010-01-08 00:58:21 +00006654} // end anonymous namespace
6655
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006656/// PrintOverloadCandidates - When overload resolution fails, prints
6657/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00006658/// set.
John McCall120d63c2010-08-24 20:38:10 +00006659void OverloadCandidateSet::NoteCandidates(Sema &S,
6660 OverloadCandidateDisplayKind OCD,
6661 Expr **Args, unsigned NumArgs,
6662 const char *Opc,
6663 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00006664 // Sort the candidates by viability and position. Sorting directly would
6665 // be prohibitive, so we make a set of pointers and sort those.
6666 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00006667 if (OCD == OCD_AllCandidates) Cands.reserve(size());
6668 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00006669 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00006670 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00006671 else if (OCD == OCD_AllCandidates) {
John McCall120d63c2010-08-24 20:38:10 +00006672 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006673 if (Cand->Function || Cand->IsSurrogate)
6674 Cands.push_back(Cand);
6675 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6676 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00006677 }
6678 }
6679
John McCallbf65c0b2010-01-12 00:48:53 +00006680 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00006681 CompareOverloadCandidatesForDisplay(S));
John McCall81201622010-01-08 04:41:39 +00006682
John McCall1d318332010-01-12 00:44:57 +00006683 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00006684
John McCall81201622010-01-08 04:41:39 +00006685 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall120d63c2010-08-24 20:38:10 +00006686 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006687 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00006688 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6689 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00006690
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006691 // Set an arbitrary limit on the number of candidate functions we'll spam
6692 // the user with. FIXME: This limit should depend on details of the
6693 // candidate list.
6694 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6695 break;
6696 }
6697 ++CandsShown;
6698
John McCalla1d7d622010-01-08 00:58:21 +00006699 if (Cand->Function)
John McCall120d63c2010-08-24 20:38:10 +00006700 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00006701 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00006702 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006703 else {
6704 assert(Cand->Viable &&
6705 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00006706 // Generally we only see ambiguities including viable builtin
6707 // operators if overload resolution got screwed up by an
6708 // ambiguous user-defined conversion.
6709 //
6710 // FIXME: It's quite possible for different conversions to see
6711 // different ambiguities, though.
6712 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00006713 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00006714 ReportedAmbiguousConversions = true;
6715 }
John McCalla1d7d622010-01-08 00:58:21 +00006716
John McCall1d318332010-01-12 00:44:57 +00006717 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00006718 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006719 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006720 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006721
6722 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00006723 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006724}
6725
John McCall9aa472c2010-03-19 07:35:19 +00006726static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCallc373d482010-01-27 01:50:18 +00006727 if (isa<UnresolvedLookupExpr>(E))
John McCall9aa472c2010-03-19 07:35:19 +00006728 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00006729
John McCall9aa472c2010-03-19 07:35:19 +00006730 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00006731}
6732
Douglas Gregor904eed32008-11-10 20:40:00 +00006733/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6734/// an overloaded function (C++ [over.over]), where @p From is an
6735/// expression with overloaded function type and @p ToType is the type
6736/// we're trying to resolve to. For example:
6737///
6738/// @code
6739/// int f(double);
6740/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00006741///
Douglas Gregor904eed32008-11-10 20:40:00 +00006742/// int (*pfd)(double) = f; // selects f(double)
6743/// @endcode
6744///
6745/// This routine returns the resulting FunctionDecl if it could be
6746/// resolved, and NULL otherwise. When @p Complain is true, this
6747/// routine will emit diagnostics if there is an error.
6748FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00006749Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall6bb80172010-03-30 21:47:33 +00006750 bool Complain,
6751 DeclAccessPair &FoundResult) {
Douglas Gregor904eed32008-11-10 20:40:00 +00006752 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00006753 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00006754 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00006755 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00006756 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00006757 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00006758 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00006759 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00006760 FunctionType = MemTypePtr->getPointeeType();
6761 IsMember = true;
6762 }
Douglas Gregor904eed32008-11-10 20:40:00 +00006763
Douglas Gregor904eed32008-11-10 20:40:00 +00006764 // C++ [over.over]p1:
6765 // [...] [Note: any redundant set of parentheses surrounding the
6766 // overloaded function name is ignored (5.1). ]
Douglas Gregor904eed32008-11-10 20:40:00 +00006767 // C++ [over.over]p1:
6768 // [...] The overloaded function name can be preceded by the &
6769 // operator.
John McCallc988fab2010-08-24 23:26:21 +00006770 // However, remember whether the expression has member-pointer form:
6771 // C++ [expr.unary.op]p4:
6772 // A pointer to member is only formed when an explicit & is used
6773 // and its operand is a qualified-id not enclosed in
6774 // parentheses.
John McCall9c72c602010-08-27 09:08:28 +00006775 OverloadExpr::FindResult Ovl = OverloadExpr::find(From);
6776 OverloadExpr *OvlExpr = Ovl.Expression;
John McCallc988fab2010-08-24 23:26:21 +00006777
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006778 // We expect a pointer or reference to function, or a function pointer.
6779 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6780 if (!FunctionType->isFunctionType()) {
6781 if (Complain)
6782 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6783 << OvlExpr->getName() << ToType;
6784
6785 return 0;
6786 }
6787
John McCallfb97e752010-08-24 22:52:39 +00006788 // If the overload expression doesn't have the form of a pointer to
John McCallc988fab2010-08-24 23:26:21 +00006789 // member, don't try to convert it to a pointer-to-member type.
John McCall9c72c602010-08-27 09:08:28 +00006790 if (IsMember && !Ovl.HasFormOfMemberPointer) {
John McCallfb97e752010-08-24 22:52:39 +00006791 if (!Complain) return 0;
6792
6793 // TODO: Should we condition this on whether any functions might
6794 // have matched, or is it more appropriate to do that in callers?
6795 // TODO: a fixit wouldn't hurt.
6796 Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
6797 << ToType << OvlExpr->getSourceRange();
6798 return 0;
6799 }
6800
6801 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6802 if (OvlExpr->hasExplicitTemplateArgs()) {
6803 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6804 ExplicitTemplateArgs = &ETABuffer;
6805 }
6806
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006807 assert(From->getType() == Context.OverloadTy);
Douglas Gregor904eed32008-11-10 20:40:00 +00006808
Douglas Gregor904eed32008-11-10 20:40:00 +00006809 // Look through all of the overloaded functions, searching for one
6810 // whose type matches exactly.
John McCall9aa472c2010-03-19 07:35:19 +00006811 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb7a09262010-04-01 18:32:35 +00006812 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
Douglas Gregor9b623632010-10-12 23:32:35 +00006813
Douglas Gregor00aeb522009-07-08 23:33:52 +00006814 bool FoundNonTemplateFunction = false;
John McCall7bb12da2010-02-02 06:20:04 +00006815 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6816 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00006817 // Look through any using declarations to find the underlying function.
6818 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6819
Douglas Gregor904eed32008-11-10 20:40:00 +00006820 // C++ [over.over]p3:
6821 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00006822 // targets of type "pointer-to-function" or "reference-to-function."
6823 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00006824 // type "pointer-to-member-function."
6825 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00006826
Mike Stump1eb44332009-09-09 15:08:12 +00006827 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthbd647292009-12-29 06:17:27 +00006828 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006829 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00006830 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00006831 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00006832 // static when converting to member pointer.
6833 if (Method->isStatic() == IsMember)
6834 continue;
6835 } else if (IsMember)
6836 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00006837
Douglas Gregor00aeb522009-07-08 23:33:52 +00006838 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00006839 // If the name is a function template, template argument deduction is
6840 // done (14.8.2.2), and if the argument deduction succeeds, the
6841 // resulting template argument list is used to generate a single
6842 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00006843 // overloaded functions considered.
Douglas Gregor83314aa2009-07-08 20:55:45 +00006844 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00006845 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor83314aa2009-07-08 20:55:45 +00006846 if (TemplateDeductionResult Result
John McCall7bb12da2010-02-02 06:20:04 +00006847 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00006848 FunctionType, Specialization, Info)) {
6849 // FIXME: make a note of the failed deduction for diagnostics.
6850 (void)Result;
6851 } else {
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00006852 // Template argument deduction ensures that we have an exact match.
6853 // This function template specicalization works.
Douglas Gregor9b623632010-10-12 23:32:35 +00006854 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006855 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00006856 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor9b623632010-10-12 23:32:35 +00006857 Matches.push_back(std::make_pair(I.getPair(), Specialization));
Douglas Gregor83314aa2009-07-08 20:55:45 +00006858 }
John McCallba135432009-11-21 08:51:07 +00006859
6860 continue;
Douglas Gregor83314aa2009-07-08 20:55:45 +00006861 }
Mike Stump1eb44332009-09-09 15:08:12 +00006862
Chandler Carruthbd647292009-12-29 06:17:27 +00006863 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00006864 // Skip non-static functions when converting to pointer, and static
6865 // when converting to member pointer.
6866 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00006867 continue;
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006868
6869 // If we have explicit template arguments, skip non-templates.
John McCall7bb12da2010-02-02 06:20:04 +00006870 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006871 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00006872 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00006873 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00006874
Chandler Carruthbd647292009-12-29 06:17:27 +00006875 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00006876 QualType ResultTy;
6877 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6878 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6879 ResultTy)) {
John McCall9aa472c2010-03-19 07:35:19 +00006880 Matches.push_back(std::make_pair(I.getPair(),
6881 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00006882 FoundNonTemplateFunction = true;
6883 }
Mike Stump1eb44332009-09-09 15:08:12 +00006884 }
Douglas Gregor904eed32008-11-10 20:40:00 +00006885 }
6886
Douglas Gregor00aeb522009-07-08 23:33:52 +00006887 // If there were 0 or 1 matches, we're done.
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006888 if (Matches.empty()) {
6889 if (Complain) {
6890 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6891 << OvlExpr->getName() << FunctionType;
6892 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6893 E = OvlExpr->decls_end();
6894 I != E; ++I)
6895 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6896 NoteOverloadCandidate(F);
6897 }
6898
Douglas Gregor00aeb522009-07-08 23:33:52 +00006899 return 0;
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006900 } else if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00006901 FunctionDecl *Result = Matches[0].second;
Douglas Gregor9b623632010-10-12 23:32:35 +00006902 FoundResult = Matches[0].first;
Sebastian Redl07ab2022009-10-17 21:12:09 +00006903 MarkDeclarationReferenced(From->getLocStart(), Result);
Douglas Gregor9b623632010-10-12 23:32:35 +00006904 if (Complain) {
John McCall6bb80172010-03-30 21:47:33 +00006905 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Douglas Gregor9b623632010-10-12 23:32:35 +00006906 }
Sebastian Redl07ab2022009-10-17 21:12:09 +00006907 return Result;
6908 }
Douglas Gregor00aeb522009-07-08 23:33:52 +00006909
6910 // C++ [over.over]p4:
6911 // If more than one function is selected, [...]
Douglas Gregor312a2022009-09-26 03:56:17 +00006912 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006913 // [...] and any given function template specialization F1 is
6914 // eliminated if the set contains a second function template
6915 // specialization whose function template is more specialized
6916 // than the function template of F1 according to the partial
6917 // ordering rules of 14.5.5.2.
6918
6919 // The algorithm specified above is quadratic. We instead use a
6920 // two-pass algorithm (similar to the one used to identify the
6921 // best viable function in an overload set) that identifies the
6922 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00006923
6924 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6925 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6926 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCallc373d482010-01-27 01:50:18 +00006927
6928 UnresolvedSetIterator Result =
John McCall9aa472c2010-03-19 07:35:19 +00006929 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Douglas Gregor5c7bf422011-01-11 17:34:58 +00006930 TPOC_Other, 0, From->getLocStart(),
Sebastian Redl07ab2022009-10-17 21:12:09 +00006931 PDiag(),
6932 PDiag(diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00006933 << Matches[0].second->getDeclName(),
John McCall220ccbf2010-01-13 00:25:19 +00006934 PDiag(diag::note_ovl_candidate)
6935 << (unsigned) oc_function_template);
Douglas Gregor78c057e2010-09-12 08:16:09 +00006936 if (Result == MatchesCopy.end())
6937 return 0;
6938
John McCallc373d482010-01-27 01:50:18 +00006939 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall6bb80172010-03-30 21:47:33 +00006940 FoundResult = Matches[Result - MatchesCopy.begin()].first;
Douglas Gregor9b623632010-10-12 23:32:35 +00006941 if (Complain)
John McCall6bb80172010-03-30 21:47:33 +00006942 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCallc373d482010-01-27 01:50:18 +00006943 return cast<FunctionDecl>(*Result);
Douglas Gregor00aeb522009-07-08 23:33:52 +00006944 }
Mike Stump1eb44332009-09-09 15:08:12 +00006945
Douglas Gregor312a2022009-09-26 03:56:17 +00006946 // [...] any function template specializations in the set are
6947 // eliminated if the set also contains a non-template function, [...]
John McCallc373d482010-01-27 01:50:18 +00006948 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCall9aa472c2010-03-19 07:35:19 +00006949 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCallc373d482010-01-27 01:50:18 +00006950 ++I;
6951 else {
John McCall9aa472c2010-03-19 07:35:19 +00006952 Matches[I] = Matches[--N];
6953 Matches.set_size(N);
John McCallc373d482010-01-27 01:50:18 +00006954 }
6955 }
Douglas Gregor312a2022009-09-26 03:56:17 +00006956
Mike Stump1eb44332009-09-09 15:08:12 +00006957 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00006958 // selected function.
John McCallc373d482010-01-27 01:50:18 +00006959 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00006960 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall6bb80172010-03-30 21:47:33 +00006961 FoundResult = Matches[0].first;
Douglas Gregor9b623632010-10-12 23:32:35 +00006962 if (Complain)
John McCall9aa472c2010-03-19 07:35:19 +00006963 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
6964 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redl07ab2022009-10-17 21:12:09 +00006965 }
Mike Stump1eb44332009-09-09 15:08:12 +00006966
Douglas Gregor00aeb522009-07-08 23:33:52 +00006967 // FIXME: We should probably return the same thing that BestViableFunction
6968 // returns (even if we issue the diagnostics here).
Douglas Gregor8e960432010-11-08 03:40:48 +00006969 if (Complain) {
6970 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
6971 << Matches[0].second->getDeclName();
6972 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6973 NoteOverloadCandidate(Matches[I].second);
6974 }
6975
Douglas Gregor904eed32008-11-10 20:40:00 +00006976 return 0;
6977}
6978
Douglas Gregor4b52e252009-12-21 23:17:24 +00006979/// \brief Given an expression that refers to an overloaded function, try to
6980/// resolve that overloaded function expression down to a single function.
6981///
6982/// This routine can only resolve template-ids that refer to a single function
6983/// template, where that template-id refers to a single template whose template
6984/// arguments are either provided by the template-id or have defaults,
6985/// as described in C++0x [temp.arg.explicit]p3.
6986FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6987 // C++ [over.over]p1:
6988 // [...] [Note: any redundant set of parentheses surrounding the
6989 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00006990 // C++ [over.over]p1:
6991 // [...] The overloaded function name can be preceded by the &
6992 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00006993
6994 if (From->getType() != Context.OverloadTy)
6995 return 0;
6996
John McCall9c72c602010-08-27 09:08:28 +00006997 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
Douglas Gregor4b52e252009-12-21 23:17:24 +00006998
6999 // If we didn't actually find any template-ids, we're done.
John McCall7bb12da2010-02-02 06:20:04 +00007000 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00007001 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00007002
7003 TemplateArgumentListInfo ExplicitTemplateArgs;
7004 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor4b52e252009-12-21 23:17:24 +00007005
7006 // Look through all of the overloaded functions, searching for one
7007 // whose type matches exactly.
7008 FunctionDecl *Matched = 0;
John McCall7bb12da2010-02-02 06:20:04 +00007009 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7010 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00007011 // C++0x [temp.arg.explicit]p3:
7012 // [...] In contexts where deduction is done and fails, or in contexts
7013 // where deduction is not done, if a template argument list is
7014 // specified and it, along with any default template arguments,
7015 // identifies a single function template specialization, then the
7016 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00007017 FunctionTemplateDecl *FunctionTemplate
7018 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor4b52e252009-12-21 23:17:24 +00007019
7020 // C++ [over.over]p2:
7021 // If the name is a function template, template argument deduction is
7022 // done (14.8.2.2), and if the argument deduction succeeds, the
7023 // resulting template argument list is used to generate a single
7024 // function template specialization, which is added to the set of
7025 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00007026 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00007027 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00007028 if (TemplateDeductionResult Result
7029 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
7030 Specialization, Info)) {
7031 // FIXME: make a note of the failed deduction for diagnostics.
7032 (void)Result;
7033 continue;
7034 }
7035
7036 // Multiple matches; we can't resolve to a single declaration.
7037 if (Matched)
7038 return 0;
7039
7040 Matched = Specialization;
7041 }
Douglas Gregor9b623632010-10-12 23:32:35 +00007042
Douglas Gregor4b52e252009-12-21 23:17:24 +00007043 return Matched;
7044}
7045
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007046/// \brief Add a single candidate to the overload set.
7047static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00007048 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00007049 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007050 Expr **Args, unsigned NumArgs,
7051 OverloadCandidateSet &CandidateSet,
7052 bool PartialOverloading) {
John McCall9aa472c2010-03-19 07:35:19 +00007053 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00007054 if (isa<UsingShadowDecl>(Callee))
7055 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
7056
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007057 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00007058 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCall9aa472c2010-03-19 07:35:19 +00007059 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00007060 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007061 return;
John McCallba135432009-11-21 08:51:07 +00007062 }
7063
7064 if (FunctionTemplateDecl *FuncTemplate
7065 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00007066 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
7067 ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00007068 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00007069 return;
7070 }
7071
7072 assert(false && "unhandled case in overloaded call candidate");
7073
7074 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007075}
7076
7077/// \brief Add the overload candidates named by callee and/or found by argument
7078/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00007079void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007080 Expr **Args, unsigned NumArgs,
7081 OverloadCandidateSet &CandidateSet,
7082 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00007083
7084#ifndef NDEBUG
7085 // Verify that ArgumentDependentLookup is consistent with the rules
7086 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007087 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007088 // Let X be the lookup set produced by unqualified lookup (3.4.1)
7089 // and let Y be the lookup set produced by argument dependent
7090 // lookup (defined as follows). If X contains
7091 //
7092 // -- a declaration of a class member, or
7093 //
7094 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00007095 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007096 //
7097 // -- a declaration that is neither a function or a function
7098 // template
7099 //
7100 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00007101
John McCall3b4294e2009-12-16 12:17:52 +00007102 if (ULE->requiresADL()) {
7103 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7104 E = ULE->decls_end(); I != E; ++I) {
7105 assert(!(*I)->getDeclContext()->isRecord());
7106 assert(isa<UsingShadowDecl>(*I) ||
7107 !(*I)->getDeclContext()->isFunctionOrMethod());
7108 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00007109 }
7110 }
7111#endif
7112
John McCall3b4294e2009-12-16 12:17:52 +00007113 // It would be nice to avoid this copy.
7114 TemplateArgumentListInfo TABuffer;
7115 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7116 if (ULE->hasExplicitTemplateArgs()) {
7117 ULE->copyTemplateArgumentsInto(TABuffer);
7118 ExplicitTemplateArgs = &TABuffer;
7119 }
7120
7121 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7122 E = ULE->decls_end(); I != E; ++I)
John McCall9aa472c2010-03-19 07:35:19 +00007123 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00007124 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007125 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00007126
John McCall3b4294e2009-12-16 12:17:52 +00007127 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00007128 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
7129 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007130 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007131 CandidateSet,
7132 PartialOverloading);
7133}
John McCall578b69b2009-12-16 08:11:27 +00007134
7135/// Attempts to recover from a call where no functions were found.
7136///
7137/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00007138static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00007139BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00007140 UnresolvedLookupExpr *ULE,
7141 SourceLocation LParenLoc,
7142 Expr **Args, unsigned NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00007143 SourceLocation RParenLoc) {
John McCall578b69b2009-12-16 08:11:27 +00007144
7145 CXXScopeSpec SS;
7146 if (ULE->getQualifier()) {
7147 SS.setScopeRep(ULE->getQualifier());
7148 SS.setRange(ULE->getQualifierRange());
7149 }
7150
John McCall3b4294e2009-12-16 12:17:52 +00007151 TemplateArgumentListInfo TABuffer;
7152 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7153 if (ULE->hasExplicitTemplateArgs()) {
7154 ULE->copyTemplateArgumentsInto(TABuffer);
7155 ExplicitTemplateArgs = &TABuffer;
7156 }
7157
John McCall578b69b2009-12-16 08:11:27 +00007158 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
7159 Sema::LookupOrdinaryName);
Douglas Gregor91f7ac72010-05-18 16:14:23 +00007160 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCallf312b1e2010-08-26 23:41:50 +00007161 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00007162
John McCall3b4294e2009-12-16 12:17:52 +00007163 assert(!R.empty() && "lookup results empty despite recovery");
7164
7165 // Build an implicit member call if appropriate. Just drop the
7166 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00007167 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00007168 if ((*R.begin())->isCXXClassMember())
Chandler Carruth6df868e2010-12-12 08:17:55 +00007169 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
7170 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00007171 else if (ExplicitTemplateArgs)
7172 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
7173 else
7174 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
7175
7176 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007177 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00007178
7179 // This shouldn't cause an infinite loop because we're giving it
7180 // an expression with non-empty lookup results, which should never
7181 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00007182 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +00007183 MultiExprArg(Args, NumArgs), RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00007184}
Douglas Gregord7a95972010-06-08 17:35:15 +00007185
Douglas Gregorf6b89692008-11-26 05:54:23 +00007186/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00007187/// (which eventually refers to the declaration Func) and the call
7188/// arguments Args/NumArgs, attempt to resolve the function call down
7189/// to a specific function. If overload resolution succeeds, returns
7190/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00007191/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00007192/// arguments and Fn, and returns NULL.
John McCall60d7b3a2010-08-24 06:29:42 +00007193ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00007194Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00007195 SourceLocation LParenLoc,
7196 Expr **Args, unsigned NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00007197 SourceLocation RParenLoc) {
7198#ifndef NDEBUG
7199 if (ULE->requiresADL()) {
7200 // To do ADL, we must have found an unqualified name.
7201 assert(!ULE->getQualifier() && "qualified name with ADL");
7202
7203 // We don't perform ADL for implicit declarations of builtins.
7204 // Verify that this was correctly set up.
7205 FunctionDecl *F;
7206 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
7207 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
7208 F->getBuiltinID() && F->isImplicit())
7209 assert(0 && "performing ADL for builtin");
7210
7211 // We don't perform ADL in C.
7212 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
7213 }
7214#endif
7215
John McCall5769d612010-02-08 23:07:23 +00007216 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00007217
John McCall3b4294e2009-12-16 12:17:52 +00007218 // Add the functions denoted by the callee to the set of candidate
7219 // functions, including those from argument-dependent lookup.
7220 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00007221
7222 // If we found nothing, try to recover.
7223 // AddRecoveryCallCandidates diagnoses the error itself, so we just
7224 // bailout out if it fails.
John McCall3b4294e2009-12-16 12:17:52 +00007225 if (CandidateSet.empty())
Douglas Gregor1aae80b2010-04-14 20:27:54 +00007226 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00007227 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00007228
Douglas Gregorf6b89692008-11-26 05:54:23 +00007229 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007230 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00007231 case OR_Success: {
7232 FunctionDecl *FDecl = Best->Function;
John McCall9aa472c2010-03-19 07:35:19 +00007233 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007234 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
7235 ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00007236 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007237 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
7238 RParenLoc);
John McCall3b4294e2009-12-16 12:17:52 +00007239 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00007240
7241 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00007242 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00007243 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00007244 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007245 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00007246 break;
7247
7248 case OR_Ambiguous:
7249 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00007250 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007251 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00007252 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007253
7254 case OR_Deleted:
7255 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
7256 << Best->Function->isDeleted()
John McCall3b4294e2009-12-16 12:17:52 +00007257 << ULE->getName()
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007258 << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007259 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007260 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00007261 }
7262
Douglas Gregorff331c12010-07-25 18:17:45 +00007263 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00007264 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00007265}
7266
John McCall6e266892010-01-26 03:27:55 +00007267static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00007268 return Functions.size() > 1 ||
7269 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
7270}
7271
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007272/// \brief Create a unary operation that may resolve to an overloaded
7273/// operator.
7274///
7275/// \param OpLoc The location of the operator itself (e.g., '*').
7276///
7277/// \param OpcIn The UnaryOperator::Opcode that describes this
7278/// operator.
7279///
7280/// \param Functions The set of non-member functions that will be
7281/// considered by overload resolution. The caller needs to build this
7282/// set based on the context using, e.g.,
7283/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7284/// set should not contain any member functions; those will be added
7285/// by CreateOverloadedUnaryOp().
7286///
7287/// \param input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +00007288ExprResult
John McCall6e266892010-01-26 03:27:55 +00007289Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
7290 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +00007291 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007292 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007293
7294 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
7295 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
7296 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00007297 // TODO: provide better source location info.
7298 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007299
John McCall0e800c92010-12-04 08:14:53 +00007300 if (Input->getObjectKind() == OK_ObjCProperty)
7301 ConvertPropertyForRValue(Input);
7302
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007303 Expr *Args[2] = { Input, 0 };
7304 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00007305
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007306 // For post-increment and post-decrement, add the implicit '0' as
7307 // the second argument, so that we know this is a post-increment or
7308 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +00007309 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007310 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007311 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
7312 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007313 NumArgs = 2;
7314 }
7315
7316 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00007317 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +00007318 return Owned(new (Context) UnaryOperator(Input,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00007319 Opc,
7320 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00007321 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00007322 OpLoc));
7323
John McCallc373d482010-01-27 01:50:18 +00007324 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00007325 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00007326 = UnresolvedLookupExpr::Create(Context, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00007327 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00007328 /*ADL*/ true, IsOverloaded(Fns),
7329 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007330 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
7331 &Args[0], NumArgs,
7332 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00007333 VK_RValue,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007334 OpLoc));
7335 }
7336
7337 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00007338 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007339
7340 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00007341 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007342
7343 // Add operator candidates that are member functions.
7344 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
7345
John McCall6e266892010-01-26 03:27:55 +00007346 // Add candidates from ADL.
7347 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregordc81c882010-02-05 05:15:43 +00007348 Args, NumArgs,
John McCall6e266892010-01-26 03:27:55 +00007349 /*ExplicitTemplateArgs*/ 0,
7350 CandidateSet);
7351
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007352 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00007353 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007354
7355 // Perform overload resolution.
7356 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007357 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007358 case OR_Success: {
7359 // We found a built-in operator or an overloaded operator.
7360 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00007361
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007362 if (FnDecl) {
7363 // We matched an overloaded operator. Build a call to that
7364 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00007365
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007366 // Convert the arguments.
7367 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00007368 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00007369
John McCall6bb80172010-03-30 21:47:33 +00007370 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
7371 Best->FoundDecl, Method))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007372 return ExprError();
7373 } else {
7374 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00007375 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +00007376 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007377 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +00007378 FnDecl->getParamDecl(0)),
Douglas Gregore1a5c172009-12-23 17:40:29 +00007379 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +00007380 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +00007381 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007382 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00007383 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007384 }
7385
John McCallb697e082010-05-06 18:15:07 +00007386 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7387
John McCallf89e55a2010-11-18 06:31:45 +00007388 // Determine the result type.
7389 QualType ResultTy = FnDecl->getResultType();
7390 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7391 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00007392
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007393 // Build the actual expression node.
John McCallf89e55a2010-11-18 06:31:45 +00007394 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00007395
Eli Friedman4c3b8962009-11-18 03:58:17 +00007396 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +00007397 CallExpr *TheCall =
Anders Carlsson26a2a072009-10-13 21:19:37 +00007398 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCallf89e55a2010-11-18 06:31:45 +00007399 Args, NumArgs, ResultTy, VK, OpLoc);
John McCallb697e082010-05-06 18:15:07 +00007400
John McCall9ae2f072010-08-23 23:25:46 +00007401 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +00007402 FnDecl))
7403 return ExprError();
7404
John McCall9ae2f072010-08-23 23:25:46 +00007405 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007406 } else {
7407 // We matched a built-in operator. Convert the arguments, then
7408 // break out so that we will build the appropriate built-in
7409 // operator node.
7410 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00007411 Best->Conversions[0], AA_Passing))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007412 return ExprError();
7413
7414 break;
7415 }
7416 }
7417
7418 case OR_No_Viable_Function:
7419 // No viable function; fall through to handling this as a
7420 // built-in operator, which will produce an error message for us.
7421 break;
7422
7423 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00007424 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007425 << UnaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +00007426 << Input->getType()
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007427 << Input->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007428 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
7429 Args, NumArgs,
7430 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007431 return ExprError();
7432
7433 case OR_Deleted:
7434 Diag(OpLoc, diag::err_ovl_deleted_oper)
7435 << Best->Function->isDeleted()
7436 << UnaryOperator::getOpcodeStr(Opc)
7437 << Input->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007438 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007439 return ExprError();
7440 }
7441
7442 // Either we found no viable overloaded operator or we matched a
7443 // built-in operator. In either case, fall through to trying to
7444 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +00007445 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007446}
7447
Douglas Gregor063daf62009-03-13 18:40:31 +00007448/// \brief Create a binary operation that may resolve to an overloaded
7449/// operator.
7450///
7451/// \param OpLoc The location of the operator itself (e.g., '+').
7452///
7453/// \param OpcIn The BinaryOperator::Opcode that describes this
7454/// operator.
7455///
7456/// \param Functions The set of non-member functions that will be
7457/// considered by overload resolution. The caller needs to build this
7458/// set based on the context using, e.g.,
7459/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7460/// set should not contain any member functions; those will be added
7461/// by CreateOverloadedBinOp().
7462///
7463/// \param LHS Left-hand argument.
7464/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +00007465ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00007466Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00007467 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00007468 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00007469 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00007470 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007471 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00007472
7473 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
7474 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
7475 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7476
7477 // If either side is type-dependent, create an appropriate dependent
7478 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007479 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00007480 if (Fns.empty()) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007481 // If there are no functions to store, just build a dependent
7482 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +00007483 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007484 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +00007485 Context.DependentTy,
7486 VK_RValue, OK_Ordinary,
7487 OpLoc));
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007488
7489 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
7490 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00007491 VK_LValue,
7492 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007493 Context.DependentTy,
7494 Context.DependentTy,
7495 OpLoc));
7496 }
John McCall6e266892010-01-26 03:27:55 +00007497
7498 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00007499 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00007500 // TODO: provide better source location info in DNLoc component.
7501 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +00007502 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00007503 = UnresolvedLookupExpr::Create(Context, NamingClass, 0, SourceRange(),
7504 OpNameInfo, /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00007505 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00007506 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00007507 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00007508 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00007509 VK_RValue,
Douglas Gregor063daf62009-03-13 18:40:31 +00007510 OpLoc));
7511 }
7512
John McCall0e800c92010-12-04 08:14:53 +00007513 // Always do property rvalue conversions on the RHS.
7514 if (Args[1]->getObjectKind() == OK_ObjCProperty)
7515 ConvertPropertyForRValue(Args[1]);
7516
7517 // The LHS is more complicated.
7518 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
7519
7520 // There's a tension for assignment operators between primitive
7521 // property assignment and the overloaded operators.
7522 if (BinaryOperator::isAssignmentOp(Opc)) {
7523 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7524
7525 // Is the property "logically" settable?
7526 bool Settable = (PRE->isExplicitProperty() ||
7527 PRE->getImplicitPropertySetter());
7528
7529 // To avoid gratuitously inventing semantics, use the primitive
7530 // unless it isn't. Thoughts in case we ever really care:
7531 // - If the property isn't logically settable, we have to
7532 // load and hope.
7533 // - If the property is settable and this is simple assignment,
7534 // we really should use the primitive.
7535 // - If the property is settable, then we could try overloading
7536 // on a generic lvalue of the appropriate type; if it works
7537 // out to a builtin candidate, we would do that same operation
7538 // on the property, and otherwise just error.
7539 if (Settable)
7540 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7541 }
7542
7543 ConvertPropertyForRValue(Args[0]);
7544 }
Douglas Gregor063daf62009-03-13 18:40:31 +00007545
Sebastian Redl275c2b42009-11-18 23:10:33 +00007546 // If this is the assignment operator, we only perform overload resolution
7547 // if the left-hand side is a class or enumeration type. This is actually
7548 // a hack. The standard requires that we do overload resolution between the
7549 // various built-in candidates, but as DR507 points out, this can lead to
7550 // problems. So we do it this way, which pretty much follows what GCC does.
7551 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +00007552 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007553 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00007554
John McCall0e800c92010-12-04 08:14:53 +00007555 // If this is the .* operator, which is not overloadable, just
7556 // create a built-in binary operator.
7557 if (Opc == BO_PtrMemD)
7558 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7559
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007560 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00007561 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00007562
7563 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00007564 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00007565
7566 // Add operator candidates that are member functions.
7567 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
7568
John McCall6e266892010-01-26 03:27:55 +00007569 // Add candidates from ADL.
7570 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
7571 Args, 2,
7572 /*ExplicitTemplateArgs*/ 0,
7573 CandidateSet);
7574
Douglas Gregor063daf62009-03-13 18:40:31 +00007575 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00007576 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00007577
7578 // Perform overload resolution.
7579 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007580 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007581 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00007582 // We found a built-in operator or an overloaded operator.
7583 FunctionDecl *FnDecl = Best->Function;
7584
7585 if (FnDecl) {
7586 // We matched an overloaded operator. Build a call to that
7587 // operator.
7588
7589 // Convert the arguments.
7590 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00007591 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +00007592 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00007593
Chandler Carruth6df868e2010-12-12 08:17:55 +00007594 ExprResult Arg1 =
7595 PerformCopyInitialization(
7596 InitializedEntity::InitializeParameter(Context,
7597 FnDecl->getParamDecl(0)),
7598 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007599 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00007600 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007601
Douglas Gregor5fccd362010-03-03 23:55:11 +00007602 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007603 Best->FoundDecl, Method))
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007604 return ExprError();
7605
7606 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00007607 } else {
7608 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +00007609 ExprResult Arg0 = PerformCopyInitialization(
7610 InitializedEntity::InitializeParameter(Context,
7611 FnDecl->getParamDecl(0)),
7612 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007613 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00007614 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007615
Chandler Carruth6df868e2010-12-12 08:17:55 +00007616 ExprResult Arg1 =
7617 PerformCopyInitialization(
7618 InitializedEntity::InitializeParameter(Context,
7619 FnDecl->getParamDecl(1)),
7620 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007621 if (Arg1.isInvalid())
7622 return ExprError();
7623 Args[0] = LHS = Arg0.takeAs<Expr>();
7624 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00007625 }
7626
John McCallb697e082010-05-06 18:15:07 +00007627 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7628
John McCallf89e55a2010-11-18 06:31:45 +00007629 // Determine the result type.
7630 QualType ResultTy = FnDecl->getResultType();
7631 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7632 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +00007633
7634 // Build the actual expression node.
John McCallf89e55a2010-11-18 06:31:45 +00007635 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00007636
John McCall9ae2f072010-08-23 23:25:46 +00007637 CXXOperatorCallExpr *TheCall =
7638 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCallf89e55a2010-11-18 06:31:45 +00007639 Args, 2, ResultTy, VK, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +00007640
John McCall9ae2f072010-08-23 23:25:46 +00007641 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00007642 FnDecl))
7643 return ExprError();
7644
John McCall9ae2f072010-08-23 23:25:46 +00007645 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +00007646 } else {
7647 // We matched a built-in operator. Convert the arguments, then
7648 // break out so that we will build the appropriate built-in
7649 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007650 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00007651 Best->Conversions[0], AA_Passing) ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007652 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00007653 Best->Conversions[1], AA_Passing))
Douglas Gregor063daf62009-03-13 18:40:31 +00007654 return ExprError();
7655
7656 break;
7657 }
7658 }
7659
Douglas Gregor33074752009-09-30 21:46:01 +00007660 case OR_No_Viable_Function: {
7661 // C++ [over.match.oper]p9:
7662 // If the operator is the operator , [...] and there are no
7663 // viable functions, then the operator is assumed to be the
7664 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +00007665 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +00007666 break;
7667
Chandler Carruth6df868e2010-12-12 08:17:55 +00007668 // For class as left operand for assignment or compound assigment
7669 // operator do not fall through to handling in built-in, but report that
7670 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +00007671 ExprResult Result = ExprError();
Douglas Gregor33074752009-09-30 21:46:01 +00007672 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +00007673 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00007674 Diag(OpLoc, diag::err_ovl_no_viable_oper)
7675 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007676 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00007677 } else {
7678 // No viable function; try to create a built-in operation, which will
7679 // produce an error. Then, show the non-viable candidates.
7680 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00007681 }
Douglas Gregor33074752009-09-30 21:46:01 +00007682 assert(Result.isInvalid() &&
7683 "C++ binary operator overloading is missing candidates!");
7684 if (Result.isInvalid())
John McCall120d63c2010-08-24 20:38:10 +00007685 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7686 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00007687 return move(Result);
7688 }
Douglas Gregor063daf62009-03-13 18:40:31 +00007689
7690 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00007691 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +00007692 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +00007693 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007694 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007695 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7696 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00007697 return ExprError();
7698
7699 case OR_Deleted:
7700 Diag(OpLoc, diag::err_ovl_deleted_oper)
7701 << Best->Function->isDeleted()
7702 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007703 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007704 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor063daf62009-03-13 18:40:31 +00007705 return ExprError();
John McCall1d318332010-01-12 00:44:57 +00007706 }
Douglas Gregor063daf62009-03-13 18:40:31 +00007707
Douglas Gregor33074752009-09-30 21:46:01 +00007708 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007709 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00007710}
7711
John McCall60d7b3a2010-08-24 06:29:42 +00007712ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +00007713Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7714 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +00007715 Expr *Base, Expr *Idx) {
7716 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +00007717 DeclarationName OpName =
7718 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7719
7720 // If either side is type-dependent, create an appropriate dependent
7721 // expression.
7722 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7723
John McCallc373d482010-01-27 01:50:18 +00007724 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00007725 // CHECKME: no 'operator' keyword?
7726 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7727 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +00007728 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00007729 = UnresolvedLookupExpr::Create(Context, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00007730 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00007731 /*ADL*/ true, /*Overloaded*/ false,
7732 UnresolvedSetIterator(),
7733 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +00007734 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00007735
Sebastian Redlf322ed62009-10-29 20:17:01 +00007736 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7737 Args, 2,
7738 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00007739 VK_RValue,
Sebastian Redlf322ed62009-10-29 20:17:01 +00007740 RLoc));
7741 }
7742
John McCall0e800c92010-12-04 08:14:53 +00007743 if (Args[0]->getObjectKind() == OK_ObjCProperty)
7744 ConvertPropertyForRValue(Args[0]);
7745 if (Args[1]->getObjectKind() == OK_ObjCProperty)
7746 ConvertPropertyForRValue(Args[1]);
7747
Sebastian Redlf322ed62009-10-29 20:17:01 +00007748 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00007749 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007750
7751 // Subscript can only be overloaded as a member function.
7752
7753 // Add operator candidates that are member functions.
7754 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7755
7756 // Add builtin operator candidates.
7757 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7758
7759 // Perform overload resolution.
7760 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007761 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00007762 case OR_Success: {
7763 // We found a built-in operator or an overloaded operator.
7764 FunctionDecl *FnDecl = Best->Function;
7765
7766 if (FnDecl) {
7767 // We matched an overloaded operator. Build a call to that
7768 // operator.
7769
John McCall9aa472c2010-03-19 07:35:19 +00007770 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007771 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +00007772
Sebastian Redlf322ed62009-10-29 20:17:01 +00007773 // Convert the arguments.
7774 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007775 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007776 Best->FoundDecl, Method))
Sebastian Redlf322ed62009-10-29 20:17:01 +00007777 return ExprError();
7778
Anders Carlsson38f88ab2010-01-29 18:37:50 +00007779 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00007780 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +00007781 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007782 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +00007783 FnDecl->getParamDecl(0)),
7784 SourceLocation(),
7785 Owned(Args[1]));
7786 if (InputInit.isInvalid())
7787 return ExprError();
7788
7789 Args[1] = InputInit.takeAs<Expr>();
7790
Sebastian Redlf322ed62009-10-29 20:17:01 +00007791 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +00007792 QualType ResultTy = FnDecl->getResultType();
7793 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7794 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007795
7796 // Build the actual expression node.
John McCallf89e55a2010-11-18 06:31:45 +00007797 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007798
John McCall9ae2f072010-08-23 23:25:46 +00007799 CXXOperatorCallExpr *TheCall =
7800 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7801 FnExpr, Args, 2,
John McCallf89e55a2010-11-18 06:31:45 +00007802 ResultTy, VK, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007803
John McCall9ae2f072010-08-23 23:25:46 +00007804 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +00007805 FnDecl))
7806 return ExprError();
7807
John McCall9ae2f072010-08-23 23:25:46 +00007808 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007809 } else {
7810 // We matched a built-in operator. Convert the arguments, then
7811 // break out so that we will build the appropriate built-in
7812 // operator node.
7813 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00007814 Best->Conversions[0], AA_Passing) ||
Sebastian Redlf322ed62009-10-29 20:17:01 +00007815 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00007816 Best->Conversions[1], AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00007817 return ExprError();
7818
7819 break;
7820 }
7821 }
7822
7823 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00007824 if (CandidateSet.empty())
7825 Diag(LLoc, diag::err_ovl_no_oper)
7826 << Args[0]->getType() << /*subscript*/ 0
7827 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7828 else
7829 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7830 << Args[0]->getType()
7831 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007832 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7833 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +00007834 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00007835 }
7836
7837 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00007838 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
7839 << "[]"
7840 << Args[0]->getType() << Args[1]->getType()
7841 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007842 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7843 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007844 return ExprError();
7845
7846 case OR_Deleted:
7847 Diag(LLoc, diag::err_ovl_deleted_oper)
7848 << Best->Function->isDeleted() << "[]"
7849 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007850 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7851 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007852 return ExprError();
7853 }
7854
7855 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +00007856 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007857}
7858
Douglas Gregor88a35142008-12-22 05:46:06 +00007859/// BuildCallToMemberFunction - Build a call to a member
7860/// function. MemExpr is the expression that refers to the member
7861/// function (and includes the object parameter), Args/NumArgs are the
7862/// arguments to the function call (not including the object
7863/// parameter). The caller needs to validate that the member
7864/// expression refers to a member function or an overloaded member
7865/// function.
John McCall60d7b3a2010-08-24 06:29:42 +00007866ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00007867Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7868 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +00007869 unsigned NumArgs, SourceLocation RParenLoc) {
Douglas Gregor88a35142008-12-22 05:46:06 +00007870 // Dig out the member expression. This holds both the object
7871 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00007872 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7873
John McCall129e2df2009-11-30 22:42:35 +00007874 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00007875 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +00007876 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007877 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +00007878 if (isa<MemberExpr>(NakedMemExpr)) {
7879 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00007880 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +00007881 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +00007882 Qualifier = MemExpr->getQualifier();
John McCall129e2df2009-11-30 22:42:35 +00007883 } else {
7884 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007885 Qualifier = UnresExpr->getQualifier();
7886
John McCall701c89e2009-12-03 04:06:58 +00007887 QualType ObjectType = UnresExpr->getBaseType();
John McCall129e2df2009-11-30 22:42:35 +00007888
Douglas Gregor88a35142008-12-22 05:46:06 +00007889 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +00007890 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00007891
John McCallaa81e162009-12-01 22:10:20 +00007892 // FIXME: avoid copy.
7893 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7894 if (UnresExpr->hasExplicitTemplateArgs()) {
7895 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7896 TemplateArgs = &TemplateArgsBuffer;
7897 }
7898
John McCall129e2df2009-11-30 22:42:35 +00007899 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7900 E = UnresExpr->decls_end(); I != E; ++I) {
7901
John McCall701c89e2009-12-03 04:06:58 +00007902 NamedDecl *Func = *I;
7903 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7904 if (isa<UsingShadowDecl>(Func))
7905 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7906
John McCall129e2df2009-11-30 22:42:35 +00007907 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00007908 // If explicit template arguments were provided, we can't call a
7909 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00007910 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00007911 continue;
7912
John McCall9aa472c2010-03-19 07:35:19 +00007913 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCall86820f52010-01-26 01:37:31 +00007914 Args, NumArgs,
John McCall701c89e2009-12-03 04:06:58 +00007915 CandidateSet, /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00007916 } else {
John McCall129e2df2009-11-30 22:42:35 +00007917 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +00007918 I.getPair(), ActingDC, TemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00007919 ObjectType, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00007920 CandidateSet,
7921 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00007922 }
Douglas Gregordec06662009-08-21 18:42:58 +00007923 }
Mike Stump1eb44332009-09-09 15:08:12 +00007924
John McCall129e2df2009-11-30 22:42:35 +00007925 DeclarationName DeclName = UnresExpr->getMemberName();
7926
Douglas Gregor88a35142008-12-22 05:46:06 +00007927 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007928 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +00007929 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00007930 case OR_Success:
7931 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00007932 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +00007933 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007934 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +00007935 break;
7936
7937 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00007938 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00007939 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00007940 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007941 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00007942 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007943 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007944
7945 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00007946 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00007947 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007948 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00007949 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007950 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007951
7952 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00007953 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007954 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00007955 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007956 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007957 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007958 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007959 }
7960
John McCall6bb80172010-03-30 21:47:33 +00007961 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +00007962
John McCallaa81e162009-12-01 22:10:20 +00007963 // If overload resolution picked a static member, build a
7964 // non-member call based on that function.
7965 if (Method->isStatic()) {
7966 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7967 Args, NumArgs, RParenLoc);
7968 }
7969
John McCall129e2df2009-11-30 22:42:35 +00007970 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00007971 }
7972
John McCallf89e55a2010-11-18 06:31:45 +00007973 QualType ResultType = Method->getResultType();
7974 ExprValueKind VK = Expr::getValueKindForType(ResultType);
7975 ResultType = ResultType.getNonLValueExprType(Context);
7976
Douglas Gregor88a35142008-12-22 05:46:06 +00007977 assert(Method && "Member call to something that isn't a method?");
John McCall9ae2f072010-08-23 23:25:46 +00007978 CXXMemberCallExpr *TheCall =
7979 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCallf89e55a2010-11-18 06:31:45 +00007980 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +00007981
Anders Carlssoneed3e692009-10-10 00:06:20 +00007982 // Check for a valid return type.
7983 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +00007984 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +00007985 return ExprError();
Anders Carlssoneed3e692009-10-10 00:06:20 +00007986
Douglas Gregor88a35142008-12-22 05:46:06 +00007987 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +00007988 // We only need to do this if there was actually an overload; otherwise
7989 // it was done at lookup.
John McCallaa81e162009-12-01 22:10:20 +00007990 Expr *ObjectArg = MemExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00007991 if (!Method->isStatic() &&
John McCall6bb80172010-03-30 21:47:33 +00007992 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7993 FoundDecl, Method))
John McCallaa81e162009-12-01 22:10:20 +00007994 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007995 MemExpr->setBase(ObjectArg);
7996
7997 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +00007998 const FunctionProtoType *Proto =
7999 Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +00008000 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00008001 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00008002 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00008003
John McCall9ae2f072010-08-23 23:25:46 +00008004 if (CheckFunctionCall(Method, TheCall))
John McCallaa81e162009-12-01 22:10:20 +00008005 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00008006
John McCall9ae2f072010-08-23 23:25:46 +00008007 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +00008008}
8009
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008010/// BuildCallToObjectOfClassType - Build a call to an object of class
8011/// type (C++ [over.call.object]), which can end up invoking an
8012/// overloaded function call operator (@c operator()) or performing a
8013/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +00008014ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00008015Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00008016 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008017 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008018 SourceLocation RParenLoc) {
John McCall0e800c92010-12-04 08:14:53 +00008019 if (Object->getObjectKind() == OK_ObjCProperty)
8020 ConvertPropertyForRValue(Object);
8021
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008022 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00008023 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00008024
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008025 // C++ [over.call.object]p1:
8026 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00008027 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008028 // candidate functions includes at least the function call
8029 // operators of T. The function call operators of T are obtained by
8030 // ordinary lookup of the name operator() in the context of
8031 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +00008032 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00008033 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00008034
8035 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00008036 PDiag(diag::err_incomplete_object_call)
Douglas Gregor593564b2009-11-15 07:48:03 +00008037 << Object->getSourceRange()))
8038 return true;
8039
John McCalla24dc2e2009-11-17 02:14:36 +00008040 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
8041 LookupQualifiedName(R, Record->getDecl());
8042 R.suppressDiagnostics();
8043
Douglas Gregor593564b2009-11-15 07:48:03 +00008044 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00008045 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00008046 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCall86820f52010-01-26 01:37:31 +00008047 Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00008048 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00008049 }
Douglas Gregor4a27d702009-10-21 06:18:39 +00008050
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008051 // C++ [over.call.object]p2:
8052 // In addition, for each conversion function declared in T of the
8053 // form
8054 //
8055 // operator conversion-type-id () cv-qualifier;
8056 //
8057 // where cv-qualifier is the same cv-qualification as, or a
8058 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00008059 // denotes the type "pointer to function of (P1,...,Pn) returning
8060 // R", or the type "reference to pointer to function of
8061 // (P1,...,Pn) returning R", or the type "reference to function
8062 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008063 // is also considered as a candidate function. Similarly,
8064 // surrogate call functions are added to the set of candidate
8065 // functions for each conversion function declared in an
8066 // accessible base class provided the function is not hidden
8067 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +00008068 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00008069 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00008070 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00008071 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00008072 NamedDecl *D = *I;
8073 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
8074 if (isa<UsingShadowDecl>(D))
8075 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8076
Douglas Gregor4a27d702009-10-21 06:18:39 +00008077 // Skip over templated conversion functions; they aren't
8078 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00008079 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00008080 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00008081
John McCall701c89e2009-12-03 04:06:58 +00008082 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCallba135432009-11-21 08:51:07 +00008083
Douglas Gregor4a27d702009-10-21 06:18:39 +00008084 // Strip the reference type (if any) and then the pointer type (if
8085 // any) to get down to what might be a function type.
8086 QualType ConvType = Conv->getConversionType().getNonReferenceType();
8087 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8088 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008089
Douglas Gregor4a27d702009-10-21 06:18:39 +00008090 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall9aa472c2010-03-19 07:35:19 +00008091 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall701c89e2009-12-03 04:06:58 +00008092 Object->getType(), Args, NumArgs,
8093 CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008094 }
Mike Stump1eb44332009-09-09 15:08:12 +00008095
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008096 // Perform overload resolution.
8097 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00008098 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
8099 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008100 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008101 // Overload resolution succeeded; we'll build the appropriate call
8102 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008103 break;
8104
8105 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00008106 if (CandidateSet.empty())
8107 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
8108 << Object->getType() << /*call*/ 1
8109 << Object->getSourceRange();
8110 else
8111 Diag(Object->getSourceRange().getBegin(),
8112 diag::err_ovl_no_viable_object_call)
8113 << Object->getType() << Object->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008114 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008115 break;
8116
8117 case OR_Ambiguous:
8118 Diag(Object->getSourceRange().getBegin(),
8119 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00008120 << Object->getType() << Object->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008121 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008122 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008123
8124 case OR_Deleted:
8125 Diag(Object->getSourceRange().getBegin(),
8126 diag::err_ovl_deleted_object_call)
8127 << Best->Function->isDeleted()
8128 << Object->getType() << Object->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008129 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008130 break;
Mike Stump1eb44332009-09-09 15:08:12 +00008131 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008132
Douglas Gregorff331c12010-07-25 18:17:45 +00008133 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008134 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008135
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008136 if (Best->Function == 0) {
8137 // Since there is no function declaration, this is one of the
8138 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00008139 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008140 = cast<CXXConversionDecl>(
8141 Best->Conversions[0].UserDefined.ConversionFunction);
8142
John McCall9aa472c2010-03-19 07:35:19 +00008143 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00008144 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00008145
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008146 // We selected one of the surrogate functions that converts the
8147 // object parameter to a function pointer. Perform the conversion
8148 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00008149
8150 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00008151 // and then call it.
John McCall6bb80172010-03-30 21:47:33 +00008152 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
8153 Conv);
Fariborz Jahanianb7400232009-09-28 23:23:40 +00008154
John McCallf312b1e2010-08-26 23:41:50 +00008155 return ActOnCallExpr(S, CE, LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00008156 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008157 }
8158
John McCall9aa472c2010-03-19 07:35:19 +00008159 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00008160 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00008161
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008162 // We found an overloaded operator(). Build a CXXOperatorCallExpr
8163 // that calls this method, using Object for the implicit object
8164 // parameter and passing along the remaining arguments.
8165 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth6df868e2010-12-12 08:17:55 +00008166 const FunctionProtoType *Proto =
8167 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008168
8169 unsigned NumArgsInProto = Proto->getNumArgs();
8170 unsigned NumArgsToCheck = NumArgs;
8171
8172 // Build the full argument list for the method call (the
8173 // implicit object parameter is placed at the beginning of the
8174 // list).
8175 Expr **MethodArgs;
8176 if (NumArgs < NumArgsInProto) {
8177 NumArgsToCheck = NumArgsInProto;
8178 MethodArgs = new Expr*[NumArgsInProto + 1];
8179 } else {
8180 MethodArgs = new Expr*[NumArgs + 1];
8181 }
8182 MethodArgs[0] = Object;
8183 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
8184 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00008185
John McCallf89e55a2010-11-18 06:31:45 +00008186 Expr *NewFn = CreateFunctionRefExpr(*this, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008187
8188 // Once we've built TheCall, all of the expressions are properly
8189 // owned.
John McCallf89e55a2010-11-18 06:31:45 +00008190 QualType ResultTy = Method->getResultType();
8191 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8192 ResultTy = ResultTy.getNonLValueExprType(Context);
8193
John McCall9ae2f072010-08-23 23:25:46 +00008194 CXXOperatorCallExpr *TheCall =
8195 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
8196 MethodArgs, NumArgs + 1,
John McCallf89e55a2010-11-18 06:31:45 +00008197 ResultTy, VK, RParenLoc);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008198 delete [] MethodArgs;
8199
John McCall9ae2f072010-08-23 23:25:46 +00008200 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +00008201 Method))
8202 return true;
8203
Douglas Gregor518fda12009-01-13 05:10:00 +00008204 // We may have default arguments. If so, we need to allocate more
8205 // slots in the call for them.
8206 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00008207 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00008208 else if (NumArgs > NumArgsInProto)
8209 NumArgsToCheck = NumArgsInProto;
8210
Chris Lattner312531a2009-04-12 08:11:20 +00008211 bool IsError = false;
8212
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008213 // Initialize the implicit object parameter.
Douglas Gregor5fccd362010-03-03 23:55:11 +00008214 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00008215 Best->FoundDecl, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008216 TheCall->setArg(0, Object);
8217
Chris Lattner312531a2009-04-12 08:11:20 +00008218
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008219 // Check the argument types.
8220 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008221 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00008222 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008223 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00008224
Douglas Gregor518fda12009-01-13 05:10:00 +00008225 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +00008226
John McCall60d7b3a2010-08-24 06:29:42 +00008227 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +00008228 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00008229 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +00008230 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +00008231 SourceLocation(), Arg);
Anders Carlsson3faa4862010-01-29 18:43:53 +00008232
8233 IsError |= InputInit.isInvalid();
8234 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00008235 } else {
John McCall60d7b3a2010-08-24 06:29:42 +00008236 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +00008237 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
8238 if (DefArg.isInvalid()) {
8239 IsError = true;
8240 break;
8241 }
8242
8243 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00008244 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008245
8246 TheCall->setArg(i + 1, Arg);
8247 }
8248
8249 // If this is a variadic call, handle args passed through "...".
8250 if (Proto->isVariadic()) {
8251 // Promote the arguments (C99 6.5.2.2p7).
8252 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
8253 Expr *Arg = Args[i];
Chris Lattner40378332010-05-16 04:01:30 +00008254 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008255 TheCall->setArg(i + 1, Arg);
8256 }
8257 }
8258
Chris Lattner312531a2009-04-12 08:11:20 +00008259 if (IsError) return true;
8260
John McCall9ae2f072010-08-23 23:25:46 +00008261 if (CheckFunctionCall(Method, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00008262 return true;
8263
John McCall182f7092010-08-24 06:09:16 +00008264 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008265}
8266
Douglas Gregor8ba10742008-11-20 16:27:02 +00008267/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00008268/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00008269/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +00008270ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00008271Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008272 assert(Base->getType()->isRecordType() &&
8273 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00008274
John McCall0e800c92010-12-04 08:14:53 +00008275 if (Base->getObjectKind() == OK_ObjCProperty)
8276 ConvertPropertyForRValue(Base);
8277
John McCall5769d612010-02-08 23:07:23 +00008278 SourceLocation Loc = Base->getExprLoc();
8279
Douglas Gregor8ba10742008-11-20 16:27:02 +00008280 // C++ [over.ref]p1:
8281 //
8282 // [...] An expression x->m is interpreted as (x.operator->())->m
8283 // for a class object x of type T if T::operator->() exists and if
8284 // the operator is selected as the best match function by the
8285 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +00008286 DeclarationName OpName =
8287 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +00008288 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +00008289 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008290
John McCall5769d612010-02-08 23:07:23 +00008291 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +00008292 PDiag(diag::err_typecheck_incomplete_tag)
8293 << Base->getSourceRange()))
8294 return ExprError();
8295
John McCalla24dc2e2009-11-17 02:14:36 +00008296 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
8297 LookupQualifiedName(R, BaseRecord->getDecl());
8298 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00008299
8300 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00008301 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00008302 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00008303 /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00008304 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00008305
8306 // Perform overload resolution.
8307 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00008308 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00008309 case OR_Success:
8310 // Overload resolution succeeded; we'll build the call below.
8311 break;
8312
8313 case OR_No_Viable_Function:
8314 if (CandidateSet.empty())
8315 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008316 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00008317 else
8318 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008319 << "operator->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008320 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008321 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00008322
8323 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00008324 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8325 << "->" << Base->getType() << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008326 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008327 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008328
8329 case OR_Deleted:
8330 Diag(OpLoc, diag::err_ovl_deleted_oper)
8331 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00008332 << "->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008333 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008334 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00008335 }
8336
John McCall9aa472c2010-03-19 07:35:19 +00008337 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00008338 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +00008339
Douglas Gregor8ba10742008-11-20 16:27:02 +00008340 // Convert the object parameter.
8341 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00008342 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
8343 Best->FoundDecl, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008344 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00008345
Douglas Gregor8ba10742008-11-20 16:27:02 +00008346 // Build the operator call.
John McCallf89e55a2010-11-18 06:31:45 +00008347 Expr *FnExpr = CreateFunctionRefExpr(*this, Method);
Anders Carlsson15ea3782009-10-13 22:43:21 +00008348
John McCallf89e55a2010-11-18 06:31:45 +00008349 QualType ResultTy = Method->getResultType();
8350 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8351 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +00008352 CXXOperatorCallExpr *TheCall =
8353 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
John McCallf89e55a2010-11-18 06:31:45 +00008354 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +00008355
John McCall9ae2f072010-08-23 23:25:46 +00008356 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00008357 Method))
8358 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00008359 return Owned(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00008360}
8361
Douglas Gregor904eed32008-11-10 20:40:00 +00008362/// FixOverloadedFunctionReference - E is an expression that refers to
8363/// a C++ overloaded function (possibly with some parentheses and
8364/// perhaps a '&' around it). We have resolved the overloaded function
8365/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00008366/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +00008367Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +00008368 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00008369 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00008370 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
8371 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00008372 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00008373 return PE;
Douglas Gregor699ee522009-11-20 19:42:02 +00008374
8375 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
8376 }
8377
8378 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00008379 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
8380 Found, Fn);
Douglas Gregor097bfb12009-10-23 22:18:25 +00008381 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00008382 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00008383 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +00008384 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +00008385 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00008386 return ICE;
Douglas Gregor699ee522009-11-20 19:42:02 +00008387
John McCallf871d0c2010-08-07 06:22:56 +00008388 return ImplicitCastExpr::Create(Context, ICE->getType(),
8389 ICE->getCastKind(),
8390 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +00008391 ICE->getValueKind());
Douglas Gregor699ee522009-11-20 19:42:02 +00008392 }
8393
8394 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00008395 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00008396 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00008397 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8398 if (Method->isStatic()) {
8399 // Do nothing: static member functions aren't any different
8400 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00008401 } else {
John McCallf7a1a742009-11-24 19:00:30 +00008402 // Fix the sub expression, which really has to be an
8403 // UnresolvedLookupExpr holding an overloaded member function
8404 // or template.
John McCall6bb80172010-03-30 21:47:33 +00008405 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8406 Found, Fn);
John McCallba135432009-11-21 08:51:07 +00008407 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00008408 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +00008409
John McCallba135432009-11-21 08:51:07 +00008410 assert(isa<DeclRefExpr>(SubExpr)
8411 && "fixed to something other than a decl ref");
8412 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
8413 && "fixed to a member ref with no nested name qualifier");
8414
8415 // We have taken the address of a pointer to member
8416 // function. Perform the computation here so that we get the
8417 // appropriate pointer to member type.
8418 QualType ClassType
8419 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
8420 QualType MemPtrType
8421 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
8422
John McCallf89e55a2010-11-18 06:31:45 +00008423 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
8424 VK_RValue, OK_Ordinary,
8425 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00008426 }
8427 }
John McCall6bb80172010-03-30 21:47:33 +00008428 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8429 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00008430 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00008431 return UnOp;
Anders Carlsson96ad5332009-10-21 17:16:23 +00008432
John McCall2de56d12010-08-25 11:45:40 +00008433 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +00008434 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00008435 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +00008436 UnOp->getOperatorLoc());
Douglas Gregor699ee522009-11-20 19:42:02 +00008437 }
John McCallba135432009-11-21 08:51:07 +00008438
8439 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00008440 // FIXME: avoid copy.
8441 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00008442 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00008443 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
8444 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00008445 }
8446
John McCallba135432009-11-21 08:51:07 +00008447 return DeclRefExpr::Create(Context,
8448 ULE->getQualifier(),
8449 ULE->getQualifierRange(),
8450 Fn,
8451 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00008452 Fn->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00008453 VK_LValue,
John McCallaa81e162009-12-01 22:10:20 +00008454 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00008455 }
8456
John McCall129e2df2009-11-30 22:42:35 +00008457 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00008458 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00008459 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8460 if (MemExpr->hasExplicitTemplateArgs()) {
8461 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8462 TemplateArgs = &TemplateArgsBuffer;
8463 }
John McCalld5532b62009-11-23 01:53:49 +00008464
John McCallaa81e162009-12-01 22:10:20 +00008465 Expr *Base;
8466
John McCallf89e55a2010-11-18 06:31:45 +00008467 // If we're filling in a static method where we used to have an
8468 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +00008469 if (MemExpr->isImplicitAccess()) {
8470 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
8471 return DeclRefExpr::Create(Context,
8472 MemExpr->getQualifier(),
8473 MemExpr->getQualifierRange(),
8474 Fn,
8475 MemExpr->getMemberLoc(),
8476 Fn->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00008477 VK_LValue,
John McCallaa81e162009-12-01 22:10:20 +00008478 TemplateArgs);
Douglas Gregor828a1972010-01-07 23:12:05 +00008479 } else {
8480 SourceLocation Loc = MemExpr->getMemberLoc();
8481 if (MemExpr->getQualifier())
8482 Loc = MemExpr->getQualifierRange().getBegin();
8483 Base = new (Context) CXXThisExpr(Loc,
8484 MemExpr->getBaseType(),
8485 /*isImplicit=*/true);
8486 }
John McCallaa81e162009-12-01 22:10:20 +00008487 } else
John McCall3fa5cae2010-10-26 07:05:15 +00008488 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +00008489
8490 return MemberExpr::Create(Context, Base,
Douglas Gregor699ee522009-11-20 19:42:02 +00008491 MemExpr->isArrow(),
8492 MemExpr->getQualifier(),
8493 MemExpr->getQualifierRange(),
8494 Fn,
John McCall6bb80172010-03-30 21:47:33 +00008495 Found,
Abramo Bagnara25777432010-08-11 22:01:17 +00008496 MemExpr->getMemberNameInfo(),
John McCallaa81e162009-12-01 22:10:20 +00008497 TemplateArgs,
John McCallf89e55a2010-11-18 06:31:45 +00008498 Fn->getType(),
8499 cast<CXXMethodDecl>(Fn)->isStatic()
8500 ? VK_LValue : VK_RValue,
8501 OK_Ordinary);
Douglas Gregor699ee522009-11-20 19:42:02 +00008502 }
8503
John McCall3fa5cae2010-10-26 07:05:15 +00008504 llvm_unreachable("Invalid reference to overloaded function");
8505 return E;
Douglas Gregor904eed32008-11-10 20:40:00 +00008506}
8507
John McCall60d7b3a2010-08-24 06:29:42 +00008508ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
8509 DeclAccessPair Found,
8510 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +00008511 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +00008512}
8513
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008514} // end namespace clang