blob: 569be2667761e60c4e3e43bc27140ccf86ce143b [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
885 // Strip the noreturn off the type we're converting from; noreturn can
886 // safely be removed.
887 FromType = Context.getNoReturnType(FromType, false);
888 if (!Context.hasSameUnqualifiedType(FromType, ToType))
889 return false;
890
891 ResultTy = FromType;
892 return true;
893}
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000894
895/// \brief Determine whether the conversion from FromType to ToType is a valid
896/// vector conversion.
897///
898/// \param ICK Will be set to the vector conversion kind, if this is a vector
899/// conversion.
900static bool IsVectorConversion(ASTContext &Context, QualType FromType,
901 QualType ToType, ImplicitConversionKind &ICK) {
902 // We need at least one of these types to be a vector type to have a vector
903 // conversion.
904 if (!ToType->isVectorType() && !FromType->isVectorType())
905 return false;
906
907 // Identical types require no conversions.
908 if (Context.hasSameUnqualifiedType(FromType, ToType))
909 return false;
910
911 // There are no conversions between extended vector types, only identity.
912 if (ToType->isExtVectorType()) {
913 // There are no conversions between extended vector types other than the
914 // identity conversion.
915 if (FromType->isExtVectorType())
916 return false;
917
918 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +0000919 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000920 ICK = ICK_Vector_Splat;
921 return true;
922 }
923 }
Douglas Gregor255210e2010-08-06 10:14:59 +0000924
925 // We can perform the conversion between vector types in the following cases:
926 // 1)vector types are equivalent AltiVec and GCC vector types
927 // 2)lax vector conversions are permitted and the vector types are of the
928 // same size
929 if (ToType->isVectorType() && FromType->isVectorType()) {
930 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruthc45eb9c2010-08-08 05:02:51 +0000931 (Context.getLangOptions().LaxVectorConversions &&
932 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +0000933 ICK = ICK_Vector_Conversion;
934 return true;
935 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000936 }
Douglas Gregor255210e2010-08-06 10:14:59 +0000937
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000938 return false;
939}
Douglas Gregor43c79c22009-12-09 00:47:37 +0000940
Douglas Gregor60d62c22008-10-31 16:23:19 +0000941/// IsStandardConversion - Determines whether there is a standard
942/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
943/// expression From to the type ToType. Standard conversion sequences
944/// only consider non-class types; for conversions that involve class
945/// types, use TryImplicitConversion. If a conversion exists, SCS will
946/// contain the standard conversion sequence required to perform this
947/// conversion and this routine will return true. Otherwise, this
948/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +0000949static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
950 bool InOverloadResolution,
951 StandardConversionSequence &SCS) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000952 QualType FromType = From->getType();
John McCall120d63c2010-08-24 20:38:10 +0000953
Douglas Gregor60d62c22008-10-31 16:23:19 +0000954 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000955 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +0000956 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000957 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +0000958 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000959 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000960
Douglas Gregorf9201e02009-02-11 23:02:49 +0000961 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +0000962 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +0000963 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall120d63c2010-08-24 20:38:10 +0000964 if (S.getLangOptions().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000965 return false;
966
Mike Stump1eb44332009-09-09 15:08:12 +0000967 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000968 }
969
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000970 // The first conversion can be an lvalue-to-rvalue conversion,
971 // array-to-pointer conversion, or function-to-pointer conversion
972 // (C++ 4p1).
973
John McCall120d63c2010-08-24 20:38:10 +0000974 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000975 DeclAccessPair AccessPair;
976 if (FunctionDecl *Fn
John McCall120d63c2010-08-24 20:38:10 +0000977 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
978 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000979 // We were able to resolve the address of the overloaded function,
980 // so we can convert to the type of that function.
981 FromType = Fn->getType();
982 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
983 if (!Method->isStatic()) {
984 Type *ClassType
John McCall120d63c2010-08-24 20:38:10 +0000985 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
986 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000987 }
988 }
989
990 // If the "from" expression takes the address of the overloaded
991 // function, update the type of the resulting expression accordingly.
992 if (FromType->getAs<FunctionType>())
993 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
John McCall2de56d12010-08-25 11:45:40 +0000994 if (UnOp->getOpcode() == UO_AddrOf)
John McCall120d63c2010-08-24 20:38:10 +0000995 FromType = S.Context.getPointerType(FromType);
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000996
997 // Check that we've computed the proper type after overload resolution.
John McCall120d63c2010-08-24 20:38:10 +0000998 assert(S.Context.hasSameType(FromType,
999 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001000 } else {
1001 return false;
1002 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001003 }
Mike Stump1eb44332009-09-09 15:08:12 +00001004 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001005 // An lvalue (3.10) of a non-function, non-array type T can be
1006 // converted to an rvalue.
John McCall7eb0a9e2010-11-24 05:12:34 +00001007 bool argIsLValue = From->isLValue();
1008 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001009 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001010 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001011 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001012
1013 // If T is a non-class type, the type of the rvalue is the
1014 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001015 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1016 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001017 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001018 } else if (FromType->isArrayType()) {
1019 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001020 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001021
1022 // An lvalue or rvalue of type "array of N T" or "array of unknown
1023 // bound of T" can be converted to an rvalue of type "pointer to
1024 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001025 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001026
John McCall120d63c2010-08-24 20:38:10 +00001027 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001028 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001029 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001030
1031 // For the purpose of ranking in overload resolution
1032 // (13.3.3.1.1), this conversion is considered an
1033 // array-to-pointer conversion followed by a qualification
1034 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001035 SCS.Second = ICK_Identity;
1036 SCS.Third = ICK_Qualification;
Douglas Gregorad323a82010-01-27 03:51:04 +00001037 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001038 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001039 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001040 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001041 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001042 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001043
1044 // An lvalue of function type T can be converted to an rvalue of
1045 // type "pointer to T." The result is a pointer to the
1046 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001047 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001048 } else {
1049 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001050 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001051 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001052 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001053
1054 // The second conversion can be an integral promotion, floating
1055 // point promotion, integral conversion, floating point conversion,
1056 // floating-integral conversion, pointer conversion,
1057 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001058 // For overloading in C, this can also be a "compatible-type"
1059 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001060 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001061 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001062 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001063 // The unqualified versions of the types are the same: there's no
1064 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001065 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001066 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001067 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001068 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001069 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001070 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001071 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001072 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001073 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001074 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001075 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001076 SCS.Second = ICK_Complex_Promotion;
1077 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001078 } else if (ToType->isBooleanType() &&
1079 (FromType->isArithmeticType() ||
1080 FromType->isAnyPointerType() ||
1081 FromType->isBlockPointerType() ||
1082 FromType->isMemberPointerType() ||
1083 FromType->isNullPtrType())) {
1084 // Boolean conversions (C++ 4.12).
1085 SCS.Second = ICK_Boolean_Conversion;
1086 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001087 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001088 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001089 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001090 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001091 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001092 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001093 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001094 SCS.Second = ICK_Complex_Conversion;
1095 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001096 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1097 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001098 // Complex-real conversions (C99 6.3.1.7)
1099 SCS.Second = ICK_Complex_Real;
1100 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001101 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001102 // Floating point conversions (C++ 4.8).
1103 SCS.Second = ICK_Floating_Conversion;
1104 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001105 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001106 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001107 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001108 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001109 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001110 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001111 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001112 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1113 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001114 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001115 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001116 SCS.IncompatibleObjC = IncompatibleObjC;
John McCall120d63c2010-08-24 20:38:10 +00001117 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1118 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001119 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001120 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001121 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001122 SCS.Second = SecondICK;
1123 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001124 } else if (!S.getLangOptions().CPlusPlus &&
1125 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001126 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001127 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001128 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001129 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001130 // Treat a conversion that strips "noreturn" as an identity conversion.
1131 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001132 } else {
1133 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001134 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001135 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001136 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001137
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001138 QualType CanonFrom;
1139 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001140 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall120d63c2010-08-24 20:38:10 +00001141 if (S.IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001142 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001143 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001144 CanonFrom = S.Context.getCanonicalType(FromType);
1145 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001146 } else {
1147 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001148 SCS.Third = ICK_Identity;
1149
Mike Stump1eb44332009-09-09 15:08:12 +00001150 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001151 // [...] Any difference in top-level cv-qualification is
1152 // subsumed by the initialization itself and does not constitute
1153 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001154 CanonFrom = S.Context.getCanonicalType(FromType);
1155 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00001156 if (CanonFrom.getLocalUnqualifiedType()
1157 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001158 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1159 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001160 FromType = ToType;
1161 CanonFrom = CanonTo;
1162 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001163 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001164 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001165
1166 // If we have not converted the argument type to the parameter type,
1167 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001168 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001169 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001170
Douglas Gregor60d62c22008-10-31 16:23:19 +00001171 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001172}
1173
1174/// IsIntegralPromotion - Determines whether the conversion from the
1175/// expression From (whose potentially-adjusted type is FromType) to
1176/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1177/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001178bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001179 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001180 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001181 if (!To) {
1182 return false;
1183 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001184
1185 // An rvalue of type char, signed char, unsigned char, short int, or
1186 // unsigned short int can be converted to an rvalue of type int if
1187 // int can represent all the values of the source type; otherwise,
1188 // the source rvalue can be converted to an rvalue of type unsigned
1189 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001190 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1191 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001192 if (// We can promote any signed, promotable integer type to an int
1193 (FromType->isSignedIntegerType() ||
1194 // We can promote any unsigned integer type whose size is
1195 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001196 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001197 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001198 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001199 }
1200
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001201 return To->getKind() == BuiltinType::UInt;
1202 }
1203
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001204 // C++0x [conv.prom]p3:
1205 // A prvalue of an unscoped enumeration type whose underlying type is not
1206 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1207 // following types that can represent all the values of the enumeration
1208 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1209 // unsigned int, long int, unsigned long int, long long int, or unsigned
1210 // long long int. If none of the types in that list can represent all the
1211 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1212 // type can be converted to an rvalue a prvalue of the extended integer type
1213 // with lowest integer conversion rank (4.13) greater than the rank of long
1214 // long in which all the values of the enumeration can be represented. If
1215 // there are two such extended types, the signed one is chosen.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001216 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1217 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1218 // provided for a scoped enumeration.
1219 if (FromEnumType->getDecl()->isScoped())
1220 return false;
1221
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001222 // We have already pre-calculated the promotion type, so this is trivial.
Douglas Gregor5dde1602010-09-12 03:38:25 +00001223 if (ToType->isIntegerType() &&
1224 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall842aef82009-12-09 09:09:27 +00001225 return Context.hasSameUnqualifiedType(ToType,
1226 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001227 }
John McCall842aef82009-12-09 09:09:27 +00001228
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001229 // C++0x [conv.prom]p2:
1230 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1231 // to an rvalue a prvalue of the first of the following types that can
1232 // represent all the values of its underlying type: int, unsigned int,
1233 // long int, unsigned long int, long long int, or unsigned long long int.
1234 // If none of the types in that list can represent all the values of its
1235 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
1236 // or wchar_t can be converted to an rvalue a prvalue of its underlying
1237 // type.
1238 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1239 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001240 // Determine whether the type we're converting from is signed or
1241 // unsigned.
1242 bool FromIsSigned;
1243 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall842aef82009-12-09 09:09:27 +00001244
1245 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1246 FromIsSigned = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001247
1248 // The types we'll try to promote to, in the appropriate
1249 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001250 QualType PromoteTypes[6] = {
1251 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001252 Context.LongTy, Context.UnsignedLongTy ,
1253 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001254 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001255 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001256 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1257 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001258 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001259 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1260 // We found the type that we can promote to. If this is the
1261 // type we wanted, we have a promotion. Otherwise, no
1262 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001263 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001264 }
1265 }
1266 }
1267
1268 // An rvalue for an integral bit-field (9.6) can be converted to an
1269 // rvalue of type int if int can represent all the values of the
1270 // bit-field; otherwise, it can be converted to unsigned int if
1271 // unsigned int can represent all the values of the bit-field. If
1272 // the bit-field is larger yet, no integral promotion applies to
1273 // it. If the bit-field has an enumerated type, it is treated as any
1274 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001275 // FIXME: We should delay checking of bit-fields until we actually perform the
1276 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001277 using llvm::APSInt;
1278 if (From)
1279 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001280 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001281 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001282 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1283 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1284 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001285
Douglas Gregor86f19402008-12-20 23:49:58 +00001286 // Are we promoting to an int from a bitfield that fits in an int?
1287 if (BitWidth < ToSize ||
1288 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1289 return To->getKind() == BuiltinType::Int;
1290 }
Mike Stump1eb44332009-09-09 15:08:12 +00001291
Douglas Gregor86f19402008-12-20 23:49:58 +00001292 // Are we promoting to an unsigned int from an unsigned bitfield
1293 // that fits into an unsigned int?
1294 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1295 return To->getKind() == BuiltinType::UInt;
1296 }
Mike Stump1eb44332009-09-09 15:08:12 +00001297
Douglas Gregor86f19402008-12-20 23:49:58 +00001298 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001299 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001300 }
Mike Stump1eb44332009-09-09 15:08:12 +00001301
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001302 // An rvalue of type bool can be converted to an rvalue of type int,
1303 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001304 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001305 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001306 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001307
1308 return false;
1309}
1310
1311/// IsFloatingPointPromotion - Determines whether the conversion from
1312/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1313/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001314bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001315 /// An rvalue of type float can be converted to an rvalue of type
1316 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +00001317 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1318 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001319 if (FromBuiltin->getKind() == BuiltinType::Float &&
1320 ToBuiltin->getKind() == BuiltinType::Double)
1321 return true;
1322
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001323 // C99 6.3.1.5p1:
1324 // When a float is promoted to double or long double, or a
1325 // double is promoted to long double [...].
1326 if (!getLangOptions().CPlusPlus &&
1327 (FromBuiltin->getKind() == BuiltinType::Float ||
1328 FromBuiltin->getKind() == BuiltinType::Double) &&
1329 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1330 return true;
1331 }
1332
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001333 return false;
1334}
1335
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001336/// \brief Determine if a conversion is a complex promotion.
1337///
1338/// A complex promotion is defined as a complex -> complex conversion
1339/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001340/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001341bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001342 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001343 if (!FromComplex)
1344 return false;
1345
John McCall183700f2009-09-21 23:43:11 +00001346 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001347 if (!ToComplex)
1348 return false;
1349
1350 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001351 ToComplex->getElementType()) ||
1352 IsIntegralPromotion(0, FromComplex->getElementType(),
1353 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001354}
1355
Douglas Gregorcb7de522008-11-26 23:31:11 +00001356/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1357/// the pointer type FromPtr to a pointer to type ToPointee, with the
1358/// same type qualifiers as FromPtr has on its pointee type. ToType,
1359/// if non-empty, will be a pointer to ToType that may or may not have
1360/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +00001361static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001362BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001363 QualType ToPointee, QualType ToType,
1364 ASTContext &Context) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001365 assert((FromPtr->getTypeClass() == Type::Pointer ||
1366 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1367 "Invalid similarly-qualified pointer type");
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001368
1369 /// \brief Conversions to 'id' subsume cv-qualifier conversions.
1370 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1371 return ToType.getUnqualifiedType();
1372
Douglas Gregorda80f742010-12-01 21:43:58 +00001373 QualType CanonFromPointee
1374 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001375 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001376 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001377
1378 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001379 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001380 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001381 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001382 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001383
1384 // Build a pointer to ToPointee. It has the right qualifiers
1385 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001386 if (isa<ObjCObjectPointerType>(ToType))
1387 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001388 return Context.getPointerType(ToPointee);
1389 }
1390
1391 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001392 QualType QualifiedCanonToPointee
1393 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001394
Douglas Gregorda80f742010-12-01 21:43:58 +00001395 if (isa<ObjCObjectPointerType>(ToType))
1396 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1397 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001398}
1399
Mike Stump1eb44332009-09-09 15:08:12 +00001400static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001401 bool InOverloadResolution,
1402 ASTContext &Context) {
1403 // Handle value-dependent integral null pointer constants correctly.
1404 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1405 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001406 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001407 return !InOverloadResolution;
1408
Douglas Gregorce940492009-09-25 04:25:58 +00001409 return Expr->isNullPointerConstant(Context,
1410 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1411 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001412}
Mike Stump1eb44332009-09-09 15:08:12 +00001413
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001414/// IsPointerConversion - Determines whether the conversion of the
1415/// expression From, which has the (possibly adjusted) type FromType,
1416/// can be converted to the type ToType via a pointer conversion (C++
1417/// 4.10). If so, returns true and places the converted type (that
1418/// might differ from ToType in its cv-qualifiers at some level) into
1419/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001420///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001421/// This routine also supports conversions to and from block pointers
1422/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1423/// pointers to interfaces. FIXME: Once we've determined the
1424/// appropriate overloading rules for Objective-C, we may want to
1425/// split the Objective-C checks into a different routine; however,
1426/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001427/// conversions, so for now they live here. IncompatibleObjC will be
1428/// set if the conversion is an allowed Objective-C conversion that
1429/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001430bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001431 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001432 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001433 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001434 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00001435 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1436 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00001437 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001438
Mike Stump1eb44332009-09-09 15:08:12 +00001439 // Conversion from a null pointer constant to any Objective-C pointer type.
1440 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001441 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001442 ConvertedType = ToType;
1443 return true;
1444 }
1445
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001446 // Blocks: Block pointers can be converted to void*.
1447 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001448 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001449 ConvertedType = ToType;
1450 return true;
1451 }
1452 // Blocks: A null pointer constant can be converted to a block
1453 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001454 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001455 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001456 ConvertedType = ToType;
1457 return true;
1458 }
1459
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001460 // If the left-hand-side is nullptr_t, the right side can be a null
1461 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001462 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001463 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001464 ConvertedType = ToType;
1465 return true;
1466 }
1467
Ted Kremenek6217b802009-07-29 21:53:49 +00001468 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001469 if (!ToTypePtr)
1470 return false;
1471
1472 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001473 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001474 ConvertedType = ToType;
1475 return true;
1476 }
Sebastian Redl07779722008-10-31 14:43:28 +00001477
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001478 // Beyond this point, both types need to be pointers
1479 // , including objective-c pointers.
1480 QualType ToPointeeType = ToTypePtr->getPointeeType();
1481 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001482 ConvertedType = BuildSimilarlyQualifiedPointerType(
1483 FromType->getAs<ObjCObjectPointerType>(),
1484 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001485 ToType, Context);
1486 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001487 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001488 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001489 if (!FromTypePtr)
1490 return false;
1491
1492 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001493
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00001494 // If the unqualified pointee types are the same, this can't be a
1495 // pointer conversion, so don't do all of the work below.
1496 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1497 return false;
1498
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001499 // An rvalue of type "pointer to cv T," where T is an object type,
1500 // can be converted to an rvalue of type "pointer to cv void" (C++
1501 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00001502 if (FromPointeeType->isIncompleteOrObjectType() &&
1503 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001504 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001505 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001506 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001507 return true;
1508 }
1509
Douglas Gregorf9201e02009-02-11 23:02:49 +00001510 // When we're overloading in C, we allow a special kind of pointer
1511 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001512 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001513 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001514 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001515 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001516 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001517 return true;
1518 }
1519
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001520 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001521 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001522 // An rvalue of type "pointer to cv D," where D is a class type,
1523 // can be converted to an rvalue of type "pointer to cv B," where
1524 // B is a base class (clause 10) of D. If B is an inaccessible
1525 // (clause 11) or ambiguous (10.2) base class of D, a program that
1526 // necessitates this conversion is ill-formed. The result of the
1527 // conversion is a pointer to the base class sub-object of the
1528 // derived class object. The null pointer value is converted to
1529 // the null pointer value of the destination type.
1530 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001531 // Note that we do not check for ambiguity or inaccessibility
1532 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001533 if (getLangOptions().CPlusPlus &&
1534 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001535 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001536 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001537 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001538 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001539 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001540 ToType, Context);
1541 return true;
1542 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001543
Douglas Gregorc7887512008-12-19 19:13:09 +00001544 return false;
1545}
1546
1547/// isObjCPointerConversion - Determines whether this is an
1548/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1549/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001550bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001551 QualType& ConvertedType,
1552 bool &IncompatibleObjC) {
1553 if (!getLangOptions().ObjC1)
1554 return false;
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001555
Steve Naroff14108da2009-07-10 23:34:53 +00001556 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00001557 const ObjCObjectPointerType* ToObjCPtr =
1558 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001559 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001560 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001561
Steve Naroff14108da2009-07-10 23:34:53 +00001562 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001563 // If the pointee types are the same (ignoring qualifications),
1564 // then this is not a pointer conversion.
1565 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1566 FromObjCPtr->getPointeeType()))
1567 return false;
1568
Steve Naroffde2e22d2009-07-15 18:40:39 +00001569 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001570 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001571 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001572 ConvertedType = ToType;
1573 return true;
1574 }
1575 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001576 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001577 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001578 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001579 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001580 ConvertedType = ToType;
1581 return true;
1582 }
1583 // Objective C++: We're able to convert from a pointer to an
1584 // interface to a pointer to a different interface.
1585 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00001586 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1587 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1588 if (getLangOptions().CPlusPlus && LHS && RHS &&
1589 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1590 FromObjCPtr->getPointeeType()))
1591 return false;
Douglas Gregorda80f742010-12-01 21:43:58 +00001592 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
1593 ToObjCPtr->getPointeeType(),
1594 ToType, Context);
Steve Naroff14108da2009-07-10 23:34:53 +00001595 return true;
1596 }
1597
1598 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1599 // Okay: this is some kind of implicit downcast of Objective-C
1600 // interfaces, which is permitted. However, we're going to
1601 // complain about it.
1602 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00001603 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
1604 ToObjCPtr->getPointeeType(),
1605 ToType, Context);
Steve Naroff14108da2009-07-10 23:34:53 +00001606 return true;
1607 }
Mike Stump1eb44332009-09-09 15:08:12 +00001608 }
Steve Naroff14108da2009-07-10 23:34:53 +00001609 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001610 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001611 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001612 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001613 else if (const BlockPointerType *ToBlockPtr =
1614 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00001615 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001616 // to a block pointer type.
1617 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1618 ConvertedType = ToType;
1619 return true;
1620 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001621 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001622 }
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001623 else if (FromType->getAs<BlockPointerType>() &&
1624 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1625 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00001626 // pointer to any object.
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001627 ConvertedType = ToType;
1628 return true;
1629 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001630 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001631 return false;
1632
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001633 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001634 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001635 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00001636 else if (const BlockPointerType *FromBlockPtr =
1637 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001638 FromPointeeType = FromBlockPtr->getPointeeType();
1639 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001640 return false;
1641
Douglas Gregorc7887512008-12-19 19:13:09 +00001642 // If we have pointers to pointers, recursively check whether this
1643 // is an Objective-C conversion.
1644 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1645 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1646 IncompatibleObjC)) {
1647 // We always complain about this conversion.
1648 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00001649 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregorc7887512008-12-19 19:13:09 +00001650 return true;
1651 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001652 // Allow conversion of pointee being objective-c pointer to another one;
1653 // as in I* to id.
1654 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1655 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1656 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1657 IncompatibleObjC)) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001658 ConvertedType = Context.getPointerType(ConvertedType);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001659 return true;
1660 }
1661
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001662 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001663 // differences in the argument and result types are in Objective-C
1664 // pointer conversions. If so, we permit the conversion (but
1665 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001666 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001667 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001668 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001669 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001670 if (FromFunctionType && ToFunctionType) {
1671 // If the function types are exactly the same, this isn't an
1672 // Objective-C pointer conversion.
1673 if (Context.getCanonicalType(FromPointeeType)
1674 == Context.getCanonicalType(ToPointeeType))
1675 return false;
1676
1677 // Perform the quick checks that will tell us whether these
1678 // function types are obviously different.
1679 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1680 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1681 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1682 return false;
1683
1684 bool HasObjCConversion = false;
1685 if (Context.getCanonicalType(FromFunctionType->getResultType())
1686 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1687 // Okay, the types match exactly. Nothing to do.
1688 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1689 ToFunctionType->getResultType(),
1690 ConvertedType, IncompatibleObjC)) {
1691 // Okay, we have an Objective-C pointer conversion.
1692 HasObjCConversion = true;
1693 } else {
1694 // Function types are too different. Abort.
1695 return false;
1696 }
Mike Stump1eb44332009-09-09 15:08:12 +00001697
Douglas Gregorc7887512008-12-19 19:13:09 +00001698 // Check argument types.
1699 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1700 ArgIdx != NumArgs; ++ArgIdx) {
1701 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1702 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1703 if (Context.getCanonicalType(FromArgType)
1704 == Context.getCanonicalType(ToArgType)) {
1705 // Okay, the types match exactly. Nothing to do.
1706 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1707 ConvertedType, IncompatibleObjC)) {
1708 // Okay, we have an Objective-C pointer conversion.
1709 HasObjCConversion = true;
1710 } else {
1711 // Argument types are too different. Abort.
1712 return false;
1713 }
1714 }
1715
1716 if (HasObjCConversion) {
1717 // We had an Objective-C conversion. Allow this pointer
1718 // conversion, but complain about it.
1719 ConvertedType = ToType;
1720 IncompatibleObjC = true;
1721 return true;
1722 }
1723 }
1724
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001725 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001726}
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001727
1728/// FunctionArgTypesAreEqual - This routine checks two function proto types
1729/// for equlity of their argument types. Caller has already checked that
1730/// they have same number of arguments. This routine assumes that Objective-C
1731/// pointer types which only differ in their protocol qualifiers are equal.
1732bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1733 FunctionProtoType* NewType){
1734 if (!getLangOptions().ObjC1)
1735 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1736 NewType->arg_type_begin());
1737
1738 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1739 N = NewType->arg_type_begin(),
1740 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1741 QualType ToType = (*O);
1742 QualType FromType = (*N);
1743 if (ToType != FromType) {
1744 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1745 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00001746 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1747 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1748 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1749 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001750 continue;
1751 }
John McCallc12c5bb2010-05-15 11:32:37 +00001752 else if (const ObjCObjectPointerType *PTTo =
1753 ToType->getAs<ObjCObjectPointerType>()) {
1754 if (const ObjCObjectPointerType *PTFr =
1755 FromType->getAs<ObjCObjectPointerType>())
1756 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1757 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001758 }
1759 return false;
1760 }
1761 }
1762 return true;
1763}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001764
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001765/// CheckPointerConversion - Check the pointer conversion from the
1766/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001767/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001768/// conversions for which IsPointerConversion has already returned
1769/// true. It returns true and produces a diagnostic if there was an
1770/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001771bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00001772 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001773 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001774 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001775 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00001776 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001777
John McCalldaa8e4e2010-11-15 09:13:47 +00001778 Kind = CK_BitCast;
1779
Douglas Gregord7a95972010-06-08 17:35:15 +00001780 if (CXXBoolLiteralExpr* LitBool
1781 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00001782 if (!IsCStyleOrFunctionalCast && LitBool->getValue() == false)
Douglas Gregord7a95972010-06-08 17:35:15 +00001783 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1784 << ToType;
1785
Ted Kremenek6217b802009-07-29 21:53:49 +00001786 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1787 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001788 QualType FromPointeeType = FromPtrType->getPointeeType(),
1789 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001790
Douglas Gregor5fccd362010-03-03 23:55:11 +00001791 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1792 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001793 // We must have a derived-to-base conversion. Check an
1794 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001795 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1796 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001797 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001798 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001799 return true;
1800
1801 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00001802 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001803 }
1804 }
Mike Stump1eb44332009-09-09 15:08:12 +00001805 if (const ObjCObjectPointerType *FromPtrType =
John McCalldaa8e4e2010-11-15 09:13:47 +00001806 FromType->getAs<ObjCObjectPointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001807 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00001808 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001809 // Objective-C++ conversions are always okay.
1810 // FIXME: We should have a different class of conversions for the
1811 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001812 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001813 return false;
John McCalldaa8e4e2010-11-15 09:13:47 +00001814 }
Steve Naroff14108da2009-07-10 23:34:53 +00001815 }
John McCalldaa8e4e2010-11-15 09:13:47 +00001816
1817 // We shouldn't fall into this case unless it's valid for other
1818 // reasons.
1819 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
1820 Kind = CK_NullToPointer;
1821
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001822 return false;
1823}
1824
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001825/// IsMemberPointerConversion - Determines whether the conversion of the
1826/// expression From, which has the (possibly adjusted) type FromType, can be
1827/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1828/// If so, returns true and places the converted type (that might differ from
1829/// ToType in its cv-qualifiers at some level) into ConvertedType.
1830bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregorce940492009-09-25 04:25:58 +00001831 QualType ToType,
1832 bool InOverloadResolution,
1833 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001834 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001835 if (!ToTypePtr)
1836 return false;
1837
1838 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00001839 if (From->isNullPointerConstant(Context,
1840 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1841 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001842 ConvertedType = ToType;
1843 return true;
1844 }
1845
1846 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001847 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001848 if (!FromTypePtr)
1849 return false;
1850
1851 // A pointer to member of B can be converted to a pointer to member of D,
1852 // where D is derived from B (C++ 4.11p2).
1853 QualType FromClass(FromTypePtr->getClass(), 0);
1854 QualType ToClass(ToTypePtr->getClass(), 0);
1855 // FIXME: What happens when these are dependent? Is this function even called?
1856
1857 if (IsDerivedFrom(ToClass, FromClass)) {
1858 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1859 ToClass.getTypePtr());
1860 return true;
1861 }
1862
1863 return false;
1864}
Douglas Gregor43c79c22009-12-09 00:47:37 +00001865
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001866/// CheckMemberPointerConversion - Check the member pointer conversion from the
1867/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00001868/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001869/// for which IsMemberPointerConversion has already returned true. It returns
1870/// true and produces a diagnostic if there was an error, or returns false
1871/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001872bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00001873 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001874 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001875 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001876 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001877 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001878 if (!FromPtrType) {
1879 // This must be a null pointer to member pointer conversion
Douglas Gregorce940492009-09-25 04:25:58 +00001880 assert(From->isNullPointerConstant(Context,
1881 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001882 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00001883 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001884 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001885 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001886
Ted Kremenek6217b802009-07-29 21:53:49 +00001887 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001888 assert(ToPtrType && "No member pointer cast has a target type "
1889 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001890
Sebastian Redl21593ac2009-01-28 18:33:18 +00001891 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1892 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001893
Sebastian Redl21593ac2009-01-28 18:33:18 +00001894 // FIXME: What about dependent types?
1895 assert(FromClass->isRecordType() && "Pointer into non-class.");
1896 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001897
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001898 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001899 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00001900 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1901 assert(DerivationOkay &&
1902 "Should not have been called if derivation isn't OK.");
1903 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001904
Sebastian Redl21593ac2009-01-28 18:33:18 +00001905 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1906 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001907 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1908 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1909 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1910 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001911 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001912
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001913 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001914 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1915 << FromClass << ToClass << QualType(VBase, 0)
1916 << From->getSourceRange();
1917 return true;
1918 }
1919
John McCall6b2accb2010-02-10 09:31:12 +00001920 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00001921 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1922 Paths.front(),
1923 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00001924
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001925 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001926 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00001927 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001928 return false;
1929}
1930
Douglas Gregor98cd5992008-10-21 23:43:52 +00001931/// IsQualificationConversion - Determines whether the conversion from
1932/// an rvalue of type FromType to ToType is a qualification conversion
1933/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001934bool
1935Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001936 FromType = Context.getCanonicalType(FromType);
1937 ToType = Context.getCanonicalType(ToType);
1938
1939 // If FromType and ToType are the same type, this is not a
1940 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00001941 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00001942 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001943
Douglas Gregor98cd5992008-10-21 23:43:52 +00001944 // (C++ 4.4p4):
1945 // A conversion can add cv-qualifiers at levels other than the first
1946 // in multi-level pointers, subject to the following rules: [...]
1947 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001948 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00001949 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001950 // Within each iteration of the loop, we check the qualifiers to
1951 // determine if this still looks like a qualification
1952 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001953 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001954 // until there are no more pointers or pointers-to-members left to
1955 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001956 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001957
1958 // -- for every j > 0, if const is in cv 1,j then const is in cv
1959 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001960 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001961 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001962
Douglas Gregor98cd5992008-10-21 23:43:52 +00001963 // -- if the cv 1,j and cv 2,j are different, then const is in
1964 // every cv for 0 < k < j.
1965 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001966 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001967 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001968
Douglas Gregor98cd5992008-10-21 23:43:52 +00001969 // Keep track of whether all prior cv-qualifiers in the "to" type
1970 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00001971 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00001972 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001973 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001974
1975 // We are left with FromType and ToType being the pointee types
1976 // after unwrapping the original FromType and ToType the same number
1977 // of types. If we unwrapped any pointers, and if FromType and
1978 // ToType have the same unqualified type (since we checked
1979 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001980 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00001981}
1982
Douglas Gregor734d9862009-01-30 23:27:23 +00001983/// Determines whether there is a user-defined conversion sequence
1984/// (C++ [over.ics.user]) that converts expression From to the type
1985/// ToType. If such a conversion exists, User will contain the
1986/// user-defined conversion sequence that performs such a conversion
1987/// and this routine will return true. Otherwise, this routine returns
1988/// false and User is unspecified.
1989///
Douglas Gregor734d9862009-01-30 23:27:23 +00001990/// \param AllowExplicit true if the conversion should consider C++0x
1991/// "explicit" conversion functions as well as non-explicit conversion
1992/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00001993static OverloadingResult
1994IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1995 UserDefinedConversionSequence& User,
1996 OverloadCandidateSet& CandidateSet,
1997 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001998 // Whether we will only visit constructors.
1999 bool ConstructorsOnly = false;
2000
2001 // If the type we are conversion to is a class type, enumerate its
2002 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00002003 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002004 // C++ [over.match.ctor]p1:
2005 // When objects of class type are direct-initialized (8.5), or
2006 // copy-initialized from an expression of the same or a
2007 // derived class type (8.5), overload resolution selects the
2008 // constructor. [...] For copy-initialization, the candidate
2009 // functions are all the converting constructors (12.3.1) of
2010 // that class. The argument list is the expression-list within
2011 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00002012 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002013 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00002014 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002015 ConstructorsOnly = true;
2016
John McCall120d63c2010-08-24 20:38:10 +00002017 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag())) {
Douglas Gregor393896f2009-11-05 13:06:35 +00002018 // We're not going to find any constructors.
2019 } else if (CXXRecordDecl *ToRecordDecl
2020 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002021 DeclContext::lookup_iterator Con, ConEnd;
John McCall120d63c2010-08-24 20:38:10 +00002022 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002023 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002024 NamedDecl *D = *Con;
2025 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2026
Douglas Gregordec06662009-08-21 18:42:58 +00002027 // Find the constructor (which may be a template).
2028 CXXConstructorDecl *Constructor = 0;
2029 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00002030 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00002031 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00002032 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00002033 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2034 else
John McCall9aa472c2010-03-19 07:35:19 +00002035 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002036
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00002037 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00002038 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00002039 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00002040 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2041 /*ExplicitArgs*/ 0,
2042 &From, 1, CandidateSet,
2043 /*SuppressUserConversions=*/
2044 !ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00002045 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00002046 // Allow one user-defined conversion when user specifies a
2047 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00002048 S.AddOverloadCandidate(Constructor, FoundDecl,
2049 &From, 1, CandidateSet,
2050 /*SuppressUserConversions=*/
2051 !ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00002052 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002053 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002054 }
2055 }
2056
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002057 // Enumerate conversion functions, if we're allowed to.
2058 if (ConstructorsOnly) {
John McCall120d63c2010-08-24 20:38:10 +00002059 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2060 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00002061 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00002062 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002063 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002064 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002065 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2066 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00002067 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002068 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002069 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00002070 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00002071 DeclAccessPair FoundDecl = I.getPair();
2072 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00002073 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2074 if (isa<UsingShadowDecl>(D))
2075 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2076
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002077 CXXConversionDecl *Conv;
2078 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00002079 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2080 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002081 else
John McCall32daa422010-03-31 01:36:47 +00002082 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002083
2084 if (AllowExplicit || !Conv->isExplicit()) {
2085 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00002086 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2087 ActingContext, From, ToType,
2088 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002089 else
John McCall120d63c2010-08-24 20:38:10 +00002090 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2091 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002092 }
2093 }
2094 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002095 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002096
2097 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002098 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00002099 case OR_Success:
2100 // Record the standard conversion we used and the conversion function.
2101 if (CXXConstructorDecl *Constructor
2102 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
2103 // C++ [over.ics.user]p1:
2104 // If the user-defined conversion is specified by a
2105 // constructor (12.3.1), the initial standard conversion
2106 // sequence converts the source type to the type required by
2107 // the argument of the constructor.
2108 //
2109 QualType ThisType = Constructor->getThisType(S.Context);
2110 if (Best->Conversions[0].isEllipsis())
2111 User.EllipsisConversion = true;
2112 else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002113 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002114 User.EllipsisConversion = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002115 }
John McCall120d63c2010-08-24 20:38:10 +00002116 User.ConversionFunction = Constructor;
2117 User.After.setAsIdentityConversion();
2118 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2119 User.After.setAllToTypes(ToType);
2120 return OR_Success;
2121 } else if (CXXConversionDecl *Conversion
2122 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2123 // C++ [over.ics.user]p1:
2124 //
2125 // [...] If the user-defined conversion is specified by a
2126 // conversion function (12.3.2), the initial standard
2127 // conversion sequence converts the source type to the
2128 // implicit object parameter of the conversion function.
2129 User.Before = Best->Conversions[0].Standard;
2130 User.ConversionFunction = Conversion;
2131 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002132
John McCall120d63c2010-08-24 20:38:10 +00002133 // C++ [over.ics.user]p2:
2134 // The second standard conversion sequence converts the
2135 // result of the user-defined conversion to the target type
2136 // for the sequence. Since an implicit conversion sequence
2137 // is an initialization, the special rules for
2138 // initialization by user-defined conversion apply when
2139 // selecting the best user-defined conversion for a
2140 // user-defined conversion sequence (see 13.3.3 and
2141 // 13.3.3.1).
2142 User.After = Best->FinalConversion;
2143 return OR_Success;
2144 } else {
2145 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002146 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002147 }
2148
John McCall120d63c2010-08-24 20:38:10 +00002149 case OR_No_Viable_Function:
2150 return OR_No_Viable_Function;
2151 case OR_Deleted:
2152 // No conversion here! We're done.
2153 return OR_Deleted;
2154
2155 case OR_Ambiguous:
2156 return OR_Ambiguous;
2157 }
2158
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002159 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002160}
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002161
2162bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002163Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002164 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00002165 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002166 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00002167 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002168 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002169 if (OvResult == OR_Ambiguous)
2170 Diag(From->getSourceRange().getBegin(),
2171 diag::err_typecheck_ambiguous_condition)
2172 << From->getType() << ToType << From->getSourceRange();
2173 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2174 Diag(From->getSourceRange().getBegin(),
2175 diag::err_typecheck_nonviable_condition)
2176 << From->getType() << ToType << From->getSourceRange();
2177 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002178 return false;
John McCall120d63c2010-08-24 20:38:10 +00002179 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002180 return true;
2181}
Douglas Gregor60d62c22008-10-31 16:23:19 +00002182
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002183/// CompareImplicitConversionSequences - Compare two implicit
2184/// conversion sequences to determine whether one is better than the
2185/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00002186static ImplicitConversionSequence::CompareKind
2187CompareImplicitConversionSequences(Sema &S,
2188 const ImplicitConversionSequence& ICS1,
2189 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002190{
2191 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2192 // conversion sequences (as defined in 13.3.3.1)
2193 // -- a standard conversion sequence (13.3.3.1.1) is a better
2194 // conversion sequence than a user-defined conversion sequence or
2195 // an ellipsis conversion sequence, and
2196 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2197 // conversion sequence than an ellipsis conversion sequence
2198 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002199 //
John McCall1d318332010-01-12 00:44:57 +00002200 // C++0x [over.best.ics]p10:
2201 // For the purpose of ranking implicit conversion sequences as
2202 // described in 13.3.3.2, the ambiguous conversion sequence is
2203 // treated as a user-defined sequence that is indistinguishable
2204 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002205 if (ICS1.getKindRank() < ICS2.getKindRank())
2206 return ImplicitConversionSequence::Better;
2207 else if (ICS2.getKindRank() < ICS1.getKindRank())
2208 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002209
Benjamin Kramerb6eee072010-04-18 12:05:54 +00002210 // The following checks require both conversion sequences to be of
2211 // the same kind.
2212 if (ICS1.getKind() != ICS2.getKind())
2213 return ImplicitConversionSequence::Indistinguishable;
2214
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002215 // Two implicit conversion sequences of the same form are
2216 // indistinguishable conversion sequences unless one of the
2217 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00002218 if (ICS1.isStandard())
John McCall120d63c2010-08-24 20:38:10 +00002219 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00002220 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002221 // User-defined conversion sequence U1 is a better conversion
2222 // sequence than another user-defined conversion sequence U2 if
2223 // they contain the same user-defined conversion function or
2224 // constructor and if the second standard conversion sequence of
2225 // U1 is better than the second standard conversion sequence of
2226 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002227 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002228 ICS2.UserDefined.ConversionFunction)
John McCall120d63c2010-08-24 20:38:10 +00002229 return CompareStandardConversionSequences(S,
2230 ICS1.UserDefined.After,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002231 ICS2.UserDefined.After);
2232 }
2233
2234 return ImplicitConversionSequence::Indistinguishable;
2235}
2236
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002237static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2238 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2239 Qualifiers Quals;
2240 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2241 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2242 }
2243
2244 return Context.hasSameUnqualifiedType(T1, T2);
2245}
2246
Douglas Gregorad323a82010-01-27 03:51:04 +00002247// Per 13.3.3.2p3, compare the given standard conversion sequences to
2248// determine if one is a proper subset of the other.
2249static ImplicitConversionSequence::CompareKind
2250compareStandardConversionSubsets(ASTContext &Context,
2251 const StandardConversionSequence& SCS1,
2252 const StandardConversionSequence& SCS2) {
2253 ImplicitConversionSequence::CompareKind Result
2254 = ImplicitConversionSequence::Indistinguishable;
2255
Douglas Gregorae65f4b2010-05-23 22:10:15 +00002256 // the identity conversion sequence is considered to be a subsequence of
2257 // any non-identity conversion sequence
2258 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2259 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2260 return ImplicitConversionSequence::Better;
2261 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2262 return ImplicitConversionSequence::Worse;
2263 }
2264
Douglas Gregorad323a82010-01-27 03:51:04 +00002265 if (SCS1.Second != SCS2.Second) {
2266 if (SCS1.Second == ICK_Identity)
2267 Result = ImplicitConversionSequence::Better;
2268 else if (SCS2.Second == ICK_Identity)
2269 Result = ImplicitConversionSequence::Worse;
2270 else
2271 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002272 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00002273 return ImplicitConversionSequence::Indistinguishable;
2274
2275 if (SCS1.Third == SCS2.Third) {
2276 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2277 : ImplicitConversionSequence::Indistinguishable;
2278 }
2279
2280 if (SCS1.Third == ICK_Identity)
2281 return Result == ImplicitConversionSequence::Worse
2282 ? ImplicitConversionSequence::Indistinguishable
2283 : ImplicitConversionSequence::Better;
2284
2285 if (SCS2.Third == ICK_Identity)
2286 return Result == ImplicitConversionSequence::Better
2287 ? ImplicitConversionSequence::Indistinguishable
2288 : ImplicitConversionSequence::Worse;
2289
2290 return ImplicitConversionSequence::Indistinguishable;
2291}
2292
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002293/// CompareStandardConversionSequences - Compare two standard
2294/// conversion sequences to determine whether one is better than the
2295/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00002296static ImplicitConversionSequence::CompareKind
2297CompareStandardConversionSequences(Sema &S,
2298 const StandardConversionSequence& SCS1,
2299 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002300{
2301 // Standard conversion sequence S1 is a better conversion sequence
2302 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2303
2304 // -- S1 is a proper subsequence of S2 (comparing the conversion
2305 // sequences in the canonical form defined by 13.3.3.1.1,
2306 // excluding any Lvalue Transformation; the identity conversion
2307 // sequence is considered to be a subsequence of any
2308 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00002309 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00002310 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00002311 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002312
2313 // -- the rank of S1 is better than the rank of S2 (by the rules
2314 // defined below), or, if not that,
2315 ImplicitConversionRank Rank1 = SCS1.getRank();
2316 ImplicitConversionRank Rank2 = SCS2.getRank();
2317 if (Rank1 < Rank2)
2318 return ImplicitConversionSequence::Better;
2319 else if (Rank2 < Rank1)
2320 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002321
Douglas Gregor57373262008-10-22 14:17:15 +00002322 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2323 // are indistinguishable unless one of the following rules
2324 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00002325
Douglas Gregor57373262008-10-22 14:17:15 +00002326 // A conversion that is not a conversion of a pointer, or
2327 // pointer to member, to bool is better than another conversion
2328 // that is such a conversion.
2329 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2330 return SCS2.isPointerConversionToBool()
2331 ? ImplicitConversionSequence::Better
2332 : ImplicitConversionSequence::Worse;
2333
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002334 // C++ [over.ics.rank]p4b2:
2335 //
2336 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002337 // conversion of B* to A* is better than conversion of B* to
2338 // void*, and conversion of A* to void* is better than conversion
2339 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00002340 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00002341 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002342 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00002343 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002344 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2345 // Exactly one of the conversion sequences is a conversion to
2346 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002347 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2348 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002349 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2350 // Neither conversion sequence converts to a void pointer; compare
2351 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002352 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00002353 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002354 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002355 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2356 // Both conversion sequences are conversions to void
2357 // pointers. Compare the source types to determine if there's an
2358 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00002359 QualType FromType1 = SCS1.getFromType();
2360 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002361
2362 // Adjust the types we're converting from via the array-to-pointer
2363 // conversion, if we need to.
2364 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002365 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002366 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002367 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002368
Douglas Gregor01919692009-12-13 21:37:05 +00002369 QualType FromPointee1
2370 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2371 QualType FromPointee2
2372 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002373
John McCall120d63c2010-08-24 20:38:10 +00002374 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00002375 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002376 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00002377 return ImplicitConversionSequence::Worse;
2378
2379 // Objective-C++: If one interface is more specific than the
2380 // other, it is the better one.
John McCallc12c5bb2010-05-15 11:32:37 +00002381 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2382 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor01919692009-12-13 21:37:05 +00002383 if (FromIface1 && FromIface1) {
John McCall120d63c2010-08-24 20:38:10 +00002384 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor01919692009-12-13 21:37:05 +00002385 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002386 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor01919692009-12-13 21:37:05 +00002387 return ImplicitConversionSequence::Worse;
2388 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002389 }
Douglas Gregor57373262008-10-22 14:17:15 +00002390
2391 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2392 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00002393 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00002394 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002395 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00002396
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002397 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002398 // C++0x [over.ics.rank]p3b4:
2399 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2400 // implicit object parameter of a non-static member function declared
2401 // without a ref-qualifier, and S1 binds an rvalue reference to an
2402 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00002403 // FIXME: We don't know if we're dealing with the implicit object parameter,
2404 // or if the member function in this case has a ref qualifier.
2405 // (Of course, we don't have ref qualifiers yet.)
2406 if (SCS1.RRefBinding != SCS2.RRefBinding)
2407 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2408 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002409
2410 // C++ [over.ics.rank]p3b4:
2411 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2412 // which the references refer are the same type except for
2413 // top-level cv-qualifiers, and the type to which the reference
2414 // initialized by S2 refers is more cv-qualified than the type
2415 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00002416 QualType T1 = SCS1.getToType(2);
2417 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00002418 T1 = S.Context.getCanonicalType(T1);
2419 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002420 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00002421 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2422 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002423 if (UnqualT1 == UnqualT2) {
Chandler Carruth6df868e2010-12-12 08:17:55 +00002424 // If the type is an array type, promote the element qualifiers to the
2425 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00002426 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00002427 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002428 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00002429 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002430 if (T2.isMoreQualifiedThan(T1))
2431 return ImplicitConversionSequence::Better;
2432 else if (T1.isMoreQualifiedThan(T2))
2433 return ImplicitConversionSequence::Worse;
2434 }
2435 }
Douglas Gregor57373262008-10-22 14:17:15 +00002436
2437 return ImplicitConversionSequence::Indistinguishable;
2438}
2439
2440/// CompareQualificationConversions - Compares two standard conversion
2441/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00002442/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2443ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00002444CompareQualificationConversions(Sema &S,
2445 const StandardConversionSequence& SCS1,
2446 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00002447 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00002448 // -- S1 and S2 differ only in their qualification conversion and
2449 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2450 // cv-qualification signature of type T1 is a proper subset of
2451 // the cv-qualification signature of type T2, and S1 is not the
2452 // deprecated string literal array-to-pointer conversion (4.2).
2453 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2454 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2455 return ImplicitConversionSequence::Indistinguishable;
2456
2457 // FIXME: the example in the standard doesn't use a qualification
2458 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00002459 QualType T1 = SCS1.getToType(2);
2460 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00002461 T1 = S.Context.getCanonicalType(T1);
2462 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002463 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00002464 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2465 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00002466
2467 // If the types are the same, we won't learn anything by unwrapped
2468 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00002469 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00002470 return ImplicitConversionSequence::Indistinguishable;
2471
Chandler Carruth28e318c2009-12-29 07:16:59 +00002472 // If the type is an array type, promote the element qualifiers to the type
2473 // for comparison.
2474 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00002475 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002476 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00002477 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002478
Mike Stump1eb44332009-09-09 15:08:12 +00002479 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00002480 = ImplicitConversionSequence::Indistinguishable;
John McCall120d63c2010-08-24 20:38:10 +00002481 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00002482 // Within each iteration of the loop, we check the qualifiers to
2483 // determine if this still looks like a qualification
2484 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002485 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00002486 // until there are no more pointers or pointers-to-members left
2487 // to unwrap. This essentially mimics what
2488 // IsQualificationConversion does, but here we're checking for a
2489 // strict subset of qualifiers.
2490 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2491 // The qualifiers are the same, so this doesn't tell us anything
2492 // about how the sequences rank.
2493 ;
2494 else if (T2.isMoreQualifiedThan(T1)) {
2495 // T1 has fewer qualifiers, so it could be the better sequence.
2496 if (Result == ImplicitConversionSequence::Worse)
2497 // Neither has qualifiers that are a subset of the other's
2498 // qualifiers.
2499 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002500
Douglas Gregor57373262008-10-22 14:17:15 +00002501 Result = ImplicitConversionSequence::Better;
2502 } else if (T1.isMoreQualifiedThan(T2)) {
2503 // T2 has fewer qualifiers, so it could be the better sequence.
2504 if (Result == ImplicitConversionSequence::Better)
2505 // Neither has qualifiers that are a subset of the other's
2506 // qualifiers.
2507 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002508
Douglas Gregor57373262008-10-22 14:17:15 +00002509 Result = ImplicitConversionSequence::Worse;
2510 } else {
2511 // Qualifiers are disjoint.
2512 return ImplicitConversionSequence::Indistinguishable;
2513 }
2514
2515 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00002516 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00002517 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002518 }
2519
Douglas Gregor57373262008-10-22 14:17:15 +00002520 // Check that the winning standard conversion sequence isn't using
2521 // the deprecated string literal array to pointer conversion.
2522 switch (Result) {
2523 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00002524 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002525 Result = ImplicitConversionSequence::Indistinguishable;
2526 break;
2527
2528 case ImplicitConversionSequence::Indistinguishable:
2529 break;
2530
2531 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00002532 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002533 Result = ImplicitConversionSequence::Indistinguishable;
2534 break;
2535 }
2536
2537 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002538}
2539
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002540/// CompareDerivedToBaseConversions - Compares two standard conversion
2541/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00002542/// various kinds of derived-to-base conversions (C++
2543/// [over.ics.rank]p4b3). As part of these checks, we also look at
2544/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002545ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00002546CompareDerivedToBaseConversions(Sema &S,
2547 const StandardConversionSequence& SCS1,
2548 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00002549 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002550 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00002551 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002552 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002553
2554 // Adjust the types we're converting from via the array-to-pointer
2555 // conversion, if we need to.
2556 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002557 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002558 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002559 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002560
2561 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00002562 FromType1 = S.Context.getCanonicalType(FromType1);
2563 ToType1 = S.Context.getCanonicalType(ToType1);
2564 FromType2 = S.Context.getCanonicalType(FromType2);
2565 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002566
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002567 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002568 //
2569 // If class B is derived directly or indirectly from class A and
2570 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002571 //
2572 // For Objective-C, we let A, B, and C also be Objective-C
2573 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002574
2575 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00002576 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00002577 SCS2.Second == ICK_Pointer_Conversion &&
2578 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2579 FromType1->isPointerType() && FromType2->isPointerType() &&
2580 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002581 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002582 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002583 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002584 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002585 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002586 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002587 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002588 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002589
John McCallc12c5bb2010-05-15 11:32:37 +00002590 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2591 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2592 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2593 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002594
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002595 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002596 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002597 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002598 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002599 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002600 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00002601
2602 if (ToIface1 && ToIface2) {
John McCall120d63c2010-08-24 20:38:10 +00002603 if (S.Context.canAssignObjCInterfaces(ToIface2, ToIface1))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002604 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002605 else if (S.Context.canAssignObjCInterfaces(ToIface1, ToIface2))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002606 return ImplicitConversionSequence::Worse;
2607 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002608 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002609
2610 // -- conversion of B* to A* is better than conversion of C* to A*,
2611 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002612 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002613 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002614 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002615 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00002616
Douglas Gregorcb7de522008-11-26 23:31:11 +00002617 if (FromIface1 && FromIface2) {
John McCall120d63c2010-08-24 20:38:10 +00002618 if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002619 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002620 else if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002621 return ImplicitConversionSequence::Worse;
2622 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002623 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002624 }
2625
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002626 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002627 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2628 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2629 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2630 const MemberPointerType * FromMemPointer1 =
2631 FromType1->getAs<MemberPointerType>();
2632 const MemberPointerType * ToMemPointer1 =
2633 ToType1->getAs<MemberPointerType>();
2634 const MemberPointerType * FromMemPointer2 =
2635 FromType2->getAs<MemberPointerType>();
2636 const MemberPointerType * ToMemPointer2 =
2637 ToType2->getAs<MemberPointerType>();
2638 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2639 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2640 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2641 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2642 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2643 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2644 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2645 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002646 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002647 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002648 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002649 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00002650 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002651 return ImplicitConversionSequence::Better;
2652 }
2653 // conversion of B::* to C::* is better than conversion of A::* to C::*
2654 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002655 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002656 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002657 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002658 return ImplicitConversionSequence::Worse;
2659 }
2660 }
2661
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002662 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002663 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00002664 // -- binding of an expression of type C to a reference of type
2665 // B& is better than binding an expression of type C to a
2666 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00002667 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2668 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2669 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002670 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002671 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002672 return ImplicitConversionSequence::Worse;
2673 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002674
Douglas Gregor225c41e2008-11-03 19:09:14 +00002675 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00002676 // -- binding of an expression of type B to a reference of type
2677 // A& is better than binding an expression of type C to a
2678 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00002679 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2680 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2681 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002682 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002683 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002684 return ImplicitConversionSequence::Worse;
2685 }
2686 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002687
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002688 return ImplicitConversionSequence::Indistinguishable;
2689}
2690
Douglas Gregorabe183d2010-04-13 16:31:36 +00002691/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2692/// determine whether they are reference-related,
2693/// reference-compatible, reference-compatible with added
2694/// qualification, or incompatible, for use in C++ initialization by
2695/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2696/// type, and the first type (T1) is the pointee type of the reference
2697/// type being initialized.
2698Sema::ReferenceCompareResult
2699Sema::CompareReferenceRelationship(SourceLocation Loc,
2700 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00002701 bool &DerivedToBase,
2702 bool &ObjCConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002703 assert(!OrigT1->isReferenceType() &&
2704 "T1 must be the pointee type of the reference type");
2705 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2706
2707 QualType T1 = Context.getCanonicalType(OrigT1);
2708 QualType T2 = Context.getCanonicalType(OrigT2);
2709 Qualifiers T1Quals, T2Quals;
2710 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2711 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2712
2713 // C++ [dcl.init.ref]p4:
2714 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2715 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2716 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00002717 DerivedToBase = false;
2718 ObjCConversion = false;
2719 if (UnqualT1 == UnqualT2) {
2720 // Nothing to do.
2721 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00002722 IsDerivedFrom(UnqualT2, UnqualT1))
2723 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00002724 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2725 UnqualT2->isObjCObjectOrInterfaceType() &&
2726 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2727 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002728 else
2729 return Ref_Incompatible;
2730
2731 // At this point, we know that T1 and T2 are reference-related (at
2732 // least).
2733
2734 // If the type is an array type, promote the element qualifiers to the type
2735 // for comparison.
2736 if (isa<ArrayType>(T1) && T1Quals)
2737 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2738 if (isa<ArrayType>(T2) && T2Quals)
2739 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2740
2741 // C++ [dcl.init.ref]p4:
2742 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2743 // reference-related to T2 and cv1 is the same cv-qualification
2744 // as, or greater cv-qualification than, cv2. For purposes of
2745 // overload resolution, cases for which cv1 is greater
2746 // cv-qualification than cv2 are identified as
2747 // reference-compatible with added qualification (see 13.3.3.2).
2748 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2749 return Ref_Compatible;
2750 else if (T1.isMoreQualifiedThan(T2))
2751 return Ref_Compatible_With_Added_Qualification;
2752 else
2753 return Ref_Related;
2754}
2755
Douglas Gregor604eb652010-08-11 02:15:33 +00002756/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00002757/// with DeclType. Return true if something definite is found.
2758static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00002759FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2760 QualType DeclType, SourceLocation DeclLoc,
2761 Expr *Init, QualType T2, bool AllowRvalues,
2762 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00002763 assert(T2->isRecordType() && "Can only find conversions of record types.");
2764 CXXRecordDecl *T2RecordDecl
2765 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2766
Douglas Gregor604eb652010-08-11 02:15:33 +00002767 QualType ToType
2768 = AllowRvalues? DeclType->getAs<ReferenceType>()->getPointeeType()
2769 : DeclType;
2770
Sebastian Redl4680bf22010-06-30 18:13:39 +00002771 OverloadCandidateSet CandidateSet(DeclLoc);
2772 const UnresolvedSetImpl *Conversions
2773 = T2RecordDecl->getVisibleConversionFunctions();
2774 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2775 E = Conversions->end(); I != E; ++I) {
2776 NamedDecl *D = *I;
2777 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2778 if (isa<UsingShadowDecl>(D))
2779 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2780
2781 FunctionTemplateDecl *ConvTemplate
2782 = dyn_cast<FunctionTemplateDecl>(D);
2783 CXXConversionDecl *Conv;
2784 if (ConvTemplate)
2785 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2786 else
2787 Conv = cast<CXXConversionDecl>(D);
2788
Douglas Gregor604eb652010-08-11 02:15:33 +00002789 // If this is an explicit conversion, and we're not allowed to consider
2790 // explicit conversions, skip it.
2791 if (!AllowExplicit && Conv->isExplicit())
2792 continue;
2793
2794 if (AllowRvalues) {
2795 bool DerivedToBase = false;
2796 bool ObjCConversion = false;
2797 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00002798 S.CompareReferenceRelationship(
2799 DeclLoc,
2800 Conv->getConversionType().getNonReferenceType()
2801 .getUnqualifiedType(),
2802 DeclType.getNonReferenceType().getUnqualifiedType(),
2803 DerivedToBase, ObjCConversion) ==
2804 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00002805 continue;
2806 } else {
2807 // If the conversion function doesn't return a reference type,
2808 // it can't be considered for this conversion. An rvalue reference
2809 // is only acceptable if its referencee is a function type.
2810
2811 const ReferenceType *RefType =
2812 Conv->getConversionType()->getAs<ReferenceType>();
2813 if (!RefType ||
2814 (!RefType->isLValueReferenceType() &&
2815 !RefType->getPointeeType()->isFunctionType()))
2816 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002817 }
Douglas Gregor604eb652010-08-11 02:15:33 +00002818
2819 if (ConvTemplate)
2820 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2821 Init, ToType, CandidateSet);
2822 else
2823 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2824 ToType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002825 }
2826
2827 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002828 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00002829 case OR_Success:
2830 // C++ [over.ics.ref]p1:
2831 //
2832 // [...] If the parameter binds directly to the result of
2833 // applying a conversion function to the argument
2834 // expression, the implicit conversion sequence is a
2835 // user-defined conversion sequence (13.3.3.1.2), with the
2836 // second standard conversion sequence either an identity
2837 // conversion or, if the conversion function returns an
2838 // entity of a type that is a derived class of the parameter
2839 // type, a derived-to-base Conversion.
2840 if (!Best->FinalConversion.DirectBinding)
2841 return false;
2842
2843 ICS.setUserDefined();
2844 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2845 ICS.UserDefined.After = Best->FinalConversion;
2846 ICS.UserDefined.ConversionFunction = Best->Function;
2847 ICS.UserDefined.EllipsisConversion = false;
2848 assert(ICS.UserDefined.After.ReferenceBinding &&
2849 ICS.UserDefined.After.DirectBinding &&
2850 "Expected a direct reference binding!");
2851 return true;
2852
2853 case OR_Ambiguous:
2854 ICS.setAmbiguous();
2855 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2856 Cand != CandidateSet.end(); ++Cand)
2857 if (Cand->Viable)
2858 ICS.Ambiguous.addConversion(Cand->Function);
2859 return true;
2860
2861 case OR_No_Viable_Function:
2862 case OR_Deleted:
2863 // There was no suitable conversion, or we found a deleted
2864 // conversion; continue with other checks.
2865 return false;
2866 }
Eric Christopher1c3d5022010-06-30 18:36:32 +00002867
2868 return false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002869}
2870
Douglas Gregorabe183d2010-04-13 16:31:36 +00002871/// \brief Compute an implicit conversion sequence for reference
2872/// initialization.
2873static ImplicitConversionSequence
2874TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2875 SourceLocation DeclLoc,
2876 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00002877 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002878 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2879
2880 // Most paths end in a failed conversion.
2881 ImplicitConversionSequence ICS;
2882 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2883
2884 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2885 QualType T2 = Init->getType();
2886
2887 // If the initializer is the address of an overloaded function, try
2888 // to resolve the overloaded function. If all goes well, T2 is the
2889 // type of the resulting function.
2890 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2891 DeclAccessPair Found;
2892 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2893 false, Found))
2894 T2 = Fn->getType();
2895 }
2896
2897 // Compute some basic properties of the types and the initializer.
2898 bool isRValRef = DeclType->isRValueReferenceType();
2899 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002900 bool ObjCConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002901 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002902 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00002903 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
2904 ObjCConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002905
Douglas Gregorabe183d2010-04-13 16:31:36 +00002906
Sebastian Redl4680bf22010-06-30 18:13:39 +00002907 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00002908 // A reference to type "cv1 T1" is initialized by an expression
2909 // of type "cv2 T2" as follows:
2910
Sebastian Redl4680bf22010-06-30 18:13:39 +00002911 // -- If reference is an lvalue reference and the initializer expression
2912 // The next bullet point (T1 is a function) is pretty much equivalent to this
2913 // one, so it's handled here.
2914 if (!isRValRef || T1->isFunctionType()) {
2915 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2916 // reference-compatible with "cv2 T2," or
2917 //
2918 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2919 if (InitCategory.isLValue() &&
2920 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002921 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00002922 // When a parameter of reference type binds directly (8.5.3)
2923 // to an argument expression, the implicit conversion sequence
2924 // is the identity conversion, unless the argument expression
2925 // has a type that is a derived class of the parameter type,
2926 // in which case the implicit conversion sequence is a
2927 // derived-to-base Conversion (13.3.3.1).
2928 ICS.setStandard();
2929 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00002930 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2931 : ObjCConversion? ICK_Compatible_Conversion
2932 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002933 ICS.Standard.Third = ICK_Identity;
2934 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2935 ICS.Standard.setToType(0, T2);
2936 ICS.Standard.setToType(1, T1);
2937 ICS.Standard.setToType(2, T1);
2938 ICS.Standard.ReferenceBinding = true;
2939 ICS.Standard.DirectBinding = true;
2940 ICS.Standard.RRefBinding = isRValRef;
2941 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002942
Sebastian Redl4680bf22010-06-30 18:13:39 +00002943 // Nothing more to do: the inaccessibility/ambiguity check for
2944 // derived-to-base conversions is suppressed when we're
2945 // computing the implicit conversion sequence (C++
2946 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00002947 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002948 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00002949
Sebastian Redl4680bf22010-06-30 18:13:39 +00002950 // -- has a class type (i.e., T2 is a class type), where T1 is
2951 // not reference-related to T2, and can be implicitly
2952 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2953 // is reference-compatible with "cv3 T3" 92) (this
2954 // conversion is selected by enumerating the applicable
2955 // conversion functions (13.3.1.6) and choosing the best
2956 // one through overload resolution (13.3)),
2957 if (!SuppressUserConversions && T2->isRecordType() &&
2958 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2959 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00002960 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2961 Init, T2, /*AllowRvalues=*/false,
2962 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00002963 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002964 }
2965 }
2966
Sebastian Redl4680bf22010-06-30 18:13:39 +00002967 // -- Otherwise, the reference shall be an lvalue reference to a
2968 // non-volatile const type (i.e., cv1 shall be const), or the reference
2969 // shall be an rvalue reference and the initializer expression shall be
2970 // an rvalue or have a function type.
Douglas Gregor66821b52010-04-18 09:22:00 +00002971 //
2972 // We actually handle one oddity of C++ [over.ics.ref] at this
2973 // point, which is that, due to p2 (which short-circuits reference
2974 // binding by only attempting a simple conversion for non-direct
2975 // bindings) and p3's strange wording, we allow a const volatile
2976 // reference to bind to an rvalue. Hence the check for the presence
2977 // of "const" rather than checking for "const" being the only
2978 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00002979 // This is also the point where rvalue references and lvalue inits no longer
2980 // go together.
2981 if ((!isRValRef && !T1.isConstQualified()) ||
2982 (isRValRef && InitCategory.isLValue()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00002983 return ICS;
2984
Sebastian Redl4680bf22010-06-30 18:13:39 +00002985 // -- If T1 is a function type, then
2986 // -- if T2 is the same type as T1, the reference is bound to the
2987 // initializer expression lvalue;
2988 // -- if T2 is a class type and the initializer expression can be
2989 // implicitly converted to an lvalue of type T1 [...], the
2990 // reference is bound to the function lvalue that is the result
2991 // of the conversion;
2992 // This is the same as for the lvalue case above, so it was handled there.
2993 // -- otherwise, the program is ill-formed.
2994 // This is the one difference to the lvalue case.
2995 if (T1->isFunctionType())
2996 return ICS;
2997
2998 // -- Otherwise, if T2 is a class type and
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002999 // -- the initializer expression is an rvalue and "cv1 T1"
3000 // is reference-compatible with "cv2 T2," or
Douglas Gregorabe183d2010-04-13 16:31:36 +00003001 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00003002 // -- T1 is not reference-related to T2 and the initializer
3003 // expression can be implicitly converted to an rvalue
3004 // of type "cv3 T3" (this conversion is selected by
3005 // enumerating the applicable conversion functions
3006 // (13.3.1.6) and choosing the best one through overload
3007 // resolution (13.3)),
Douglas Gregorabe183d2010-04-13 16:31:36 +00003008 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00003009 // then the reference is bound to the initializer
3010 // expression rvalue in the first case and to the object
3011 // that is the result of the conversion in the second case
3012 // (or, in either case, to the appropriate base class
3013 // subobject of the object).
Douglas Gregor604eb652010-08-11 02:15:33 +00003014 if (T2->isRecordType()) {
3015 // First case: "cv1 T1" is reference-compatible with "cv2 T2". This is a
3016 // direct binding in C++0x but not in C++03.
3017 if (InitCategory.isRValue() &&
3018 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
3019 ICS.setStandard();
3020 ICS.Standard.First = ICK_Identity;
3021 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3022 : ObjCConversion? ICK_Compatible_Conversion
3023 : ICK_Identity;
3024 ICS.Standard.Third = ICK_Identity;
3025 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3026 ICS.Standard.setToType(0, T2);
3027 ICS.Standard.setToType(1, T1);
3028 ICS.Standard.setToType(2, T1);
3029 ICS.Standard.ReferenceBinding = true;
3030 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
3031 ICS.Standard.RRefBinding = isRValRef;
3032 ICS.Standard.CopyConstructor = 0;
3033 return ICS;
3034 }
3035
3036 // Second case: not reference-related.
3037 if (RefRelationship == Sema::Ref_Incompatible &&
3038 !S.RequireCompleteType(DeclLoc, T2, 0) &&
3039 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3040 Init, T2, /*AllowRvalues=*/true,
3041 AllowExplicit))
3042 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003043 }
Douglas Gregor604eb652010-08-11 02:15:33 +00003044
Douglas Gregorabe183d2010-04-13 16:31:36 +00003045 // -- Otherwise, a temporary of type "cv1 T1" is created and
3046 // initialized from the initializer expression using the
3047 // rules for a non-reference copy initialization (8.5). The
3048 // reference is then bound to the temporary. If T1 is
3049 // reference-related to T2, cv1 must be the same
3050 // cv-qualification as, or greater cv-qualification than,
3051 // cv2; otherwise, the program is ill-formed.
3052 if (RefRelationship == Sema::Ref_Related) {
3053 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3054 // we would be reference-compatible or reference-compatible with
3055 // added qualification. But that wasn't the case, so the reference
3056 // initialization fails.
3057 return ICS;
3058 }
3059
3060 // If at least one of the types is a class type, the types are not
3061 // related, and we aren't allowed any user conversions, the
3062 // reference binding fails. This case is important for breaking
3063 // recursion, since TryImplicitConversion below will attempt to
3064 // create a temporary through the use of a copy constructor.
3065 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3066 (T1->isRecordType() || T2->isRecordType()))
3067 return ICS;
3068
3069 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00003070 // When a parameter of reference type is not bound directly to
3071 // an argument expression, the conversion sequence is the one
3072 // required to convert the argument expression to the
3073 // underlying type of the reference according to
3074 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3075 // to copy-initializing a temporary of the underlying type with
3076 // the argument expression. Any difference in top-level
3077 // cv-qualification is subsumed by the initialization itself
3078 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00003079 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3080 /*AllowExplicit=*/false,
3081 /*InOverloadResolution=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003082
3083 // Of course, that's still a reference binding.
3084 if (ICS.isStandard()) {
3085 ICS.Standard.ReferenceBinding = true;
3086 ICS.Standard.RRefBinding = isRValRef;
3087 } else if (ICS.isUserDefined()) {
3088 ICS.UserDefined.After.ReferenceBinding = true;
3089 ICS.UserDefined.After.RRefBinding = isRValRef;
3090 }
3091 return ICS;
3092}
3093
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003094/// TryCopyInitialization - Try to copy-initialize a value of type
3095/// ToType from the expression From. Return the implicit conversion
3096/// sequence required to pass this argument, which may be a bad
3097/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00003098/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00003099/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00003100static ImplicitConversionSequence
3101TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregorb7f9e6a2010-04-16 17:53:55 +00003102 bool SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00003103 bool InOverloadResolution) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003104 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00003105 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00003106 /*FIXME:*/From->getLocStart(),
3107 SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00003108 /*AllowExplicit=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003109
John McCall120d63c2010-08-24 20:38:10 +00003110 return TryImplicitConversion(S, From, ToType,
3111 SuppressUserConversions,
3112 /*AllowExplicit=*/false,
3113 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003114}
3115
Douglas Gregor96176b32008-11-18 23:14:02 +00003116/// TryObjectArgumentInitialization - Try to initialize the object
3117/// parameter of the given member function (@c Method) from the
3118/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00003119static ImplicitConversionSequence
3120TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
3121 CXXMethodDecl *Method,
3122 CXXRecordDecl *ActingContext) {
3123 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00003124 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3125 // const volatile object.
3126 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3127 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00003128 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00003129
3130 // Set up the conversion sequence as a "bad" conversion, to allow us
3131 // to exit early.
3132 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00003133
3134 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00003135 QualType FromType = OrigFromType;
Ted Kremenek6217b802009-07-29 21:53:49 +00003136 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00003137 FromType = PT->getPointeeType();
3138
3139 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00003140
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00003141 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor96176b32008-11-18 23:14:02 +00003142 // where X is the class of which the function is a member
3143 // (C++ [over.match.funcs]p4). However, when finding an implicit
3144 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00003145 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00003146 // (C++ [over.match.funcs]p5). We perform a simplified version of
3147 // reference binding here, that allows class rvalues to bind to
3148 // non-constant references.
3149
3150 // First check the qualifiers. We don't care about lvalue-vs-rvalue
3151 // with the implicit object parameter (C++ [over.match.funcs]p5).
John McCall120d63c2010-08-24 20:38:10 +00003152 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00003153 if (ImplicitParamType.getCVRQualifiers()
3154 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00003155 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00003156 ICS.setBad(BadConversionSequence::bad_qualifiers,
3157 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003158 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003159 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003160
3161 // Check that we have either the same type or a derived type. It
3162 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00003163 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00003164 ImplicitConversionKind SecondKind;
3165 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3166 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00003167 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00003168 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00003169 else {
John McCallb1bdc622010-02-25 01:37:24 +00003170 ICS.setBad(BadConversionSequence::unrelated_class,
3171 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003172 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003173 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003174
3175 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00003176 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00003177 ICS.Standard.setAsIdentityConversion();
3178 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00003179 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003180 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003181 ICS.Standard.ReferenceBinding = true;
3182 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00003183 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003184 return ICS;
3185}
3186
3187/// PerformObjectArgumentInitialization - Perform initialization of
3188/// the implicit object parameter for the given Method with the given
3189/// expression.
3190bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00003191Sema::PerformObjectArgumentInitialization(Expr *&From,
3192 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00003193 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00003194 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003195 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00003196 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00003197 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003198
Ted Kremenek6217b802009-07-29 21:53:49 +00003199 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003200 FromRecordType = PT->getPointeeType();
3201 DestType = Method->getThisType(Context);
3202 } else {
3203 FromRecordType = From->getType();
3204 DestType = ImplicitParamRecordType;
3205 }
3206
John McCall701c89e2009-12-03 04:06:58 +00003207 // Note that we always use the true parent context when performing
3208 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003209 ImplicitConversionSequence ICS
John McCall120d63c2010-08-24 20:38:10 +00003210 = TryObjectArgumentInitialization(*this, From->getType(), Method,
John McCall701c89e2009-12-03 04:06:58 +00003211 Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00003212 if (ICS.isBad()) {
3213 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3214 Qualifiers FromQs = FromRecordType.getQualifiers();
3215 Qualifiers ToQs = DestType.getQualifiers();
3216 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3217 if (CVR) {
3218 Diag(From->getSourceRange().getBegin(),
3219 diag::err_member_function_call_bad_cvr)
3220 << Method->getDeclName() << FromRecordType << (CVR - 1)
3221 << From->getSourceRange();
3222 Diag(Method->getLocation(), diag::note_previous_decl)
3223 << Method->getDeclName();
3224 return true;
3225 }
3226 }
3227
Douglas Gregor96176b32008-11-18 23:14:02 +00003228 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003229 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00003230 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00003231 }
Mike Stump1eb44332009-09-09 15:08:12 +00003232
Douglas Gregor5fccd362010-03-03 23:55:11 +00003233 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall6bb80172010-03-30 21:47:33 +00003234 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor96176b32008-11-18 23:14:02 +00003235
Douglas Gregor5fccd362010-03-03 23:55:11 +00003236 if (!Context.hasSameType(From->getType(), DestType))
John McCall2de56d12010-08-25 11:45:40 +00003237 ImpCastExprToType(From, DestType, CK_NoOp,
John McCall5baba9d2010-08-25 10:28:54 +00003238 From->getType()->isPointerType() ? VK_RValue : VK_LValue);
Douglas Gregor96176b32008-11-18 23:14:02 +00003239 return false;
3240}
3241
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003242/// TryContextuallyConvertToBool - Attempt to contextually convert the
3243/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00003244static ImplicitConversionSequence
3245TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00003246 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00003247 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00003248 // FIXME: Are these flags correct?
3249 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00003250 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00003251 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003252}
3253
3254/// PerformContextuallyConvertToBool - Perform a contextual conversion
3255/// of the expression From to bool (C++0x [conv]p3).
3256bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
John McCall120d63c2010-08-24 20:38:10 +00003257 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00003258 if (!ICS.isBad())
3259 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003260
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003261 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003262 return Diag(From->getSourceRange().getBegin(),
3263 diag::err_typecheck_bool_condition)
3264 << From->getType() << From->getSourceRange();
3265 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003266}
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003267
3268/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3269/// expression From to 'id'.
John McCall120d63c2010-08-24 20:38:10 +00003270static ImplicitConversionSequence
3271TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3272 QualType Ty = S.Context.getObjCIdType();
3273 return TryImplicitConversion(S, From, Ty,
3274 // FIXME: Are these flags correct?
3275 /*SuppressUserConversions=*/false,
3276 /*AllowExplicit=*/true,
3277 /*InOverloadResolution=*/false);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003278}
John McCall120d63c2010-08-24 20:38:10 +00003279
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003280/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3281/// of the expression From to 'id'.
3282bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCallc12c5bb2010-05-15 11:32:37 +00003283 QualType Ty = Context.getObjCIdType();
John McCall120d63c2010-08-24 20:38:10 +00003284 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003285 if (!ICS.isBad())
3286 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3287 return true;
3288}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003289
Douglas Gregorc30614b2010-06-29 23:17:37 +00003290/// \brief Attempt to convert the given expression to an integral or
3291/// enumeration type.
3292///
3293/// This routine will attempt to convert an expression of class type to an
3294/// integral or enumeration type, if that class type only has a single
3295/// conversion to an integral or enumeration type.
3296///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003297/// \param Loc The source location of the construct that requires the
3298/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00003299///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003300/// \param FromE The expression we're converting from.
3301///
3302/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3303/// have integral or enumeration type.
3304///
3305/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3306/// incomplete class type.
3307///
3308/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3309/// explicit conversion function (because no implicit conversion functions
3310/// were available). This is a recovery mode.
3311///
3312/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3313/// showing which conversion was picked.
3314///
3315/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3316/// conversion function that could convert to integral or enumeration type.
3317///
3318/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3319/// usable conversion function.
3320///
3321/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3322/// function, which may be an extension in this case.
3323///
3324/// \returns The expression, converted to an integral or enumeration type if
3325/// successful.
John McCall60d7b3a2010-08-24 06:29:42 +00003326ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003327Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorc30614b2010-06-29 23:17:37 +00003328 const PartialDiagnostic &NotIntDiag,
3329 const PartialDiagnostic &IncompleteDiag,
3330 const PartialDiagnostic &ExplicitConvDiag,
3331 const PartialDiagnostic &ExplicitConvNote,
3332 const PartialDiagnostic &AmbigDiag,
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003333 const PartialDiagnostic &AmbigNote,
3334 const PartialDiagnostic &ConvDiag) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00003335 // We can't perform any more checking for type-dependent expressions.
3336 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00003337 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003338
3339 // If the expression already has integral or enumeration type, we're golden.
3340 QualType T = From->getType();
3341 if (T->isIntegralOrEnumerationType())
John McCall9ae2f072010-08-23 23:25:46 +00003342 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003343
3344 // FIXME: Check for missing '()' if T is a function type?
3345
3346 // If we don't have a class type in C++, there's no way we can get an
3347 // expression of integral or enumeration type.
3348 const RecordType *RecordTy = T->getAs<RecordType>();
3349 if (!RecordTy || !getLangOptions().CPlusPlus) {
3350 Diag(Loc, NotIntDiag)
3351 << T << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00003352 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003353 }
3354
3355 // We must have a complete class type.
3356 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCall9ae2f072010-08-23 23:25:46 +00003357 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003358
3359 // Look for a conversion to an integral or enumeration type.
3360 UnresolvedSet<4> ViableConversions;
3361 UnresolvedSet<4> ExplicitConversions;
3362 const UnresolvedSetImpl *Conversions
3363 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3364
3365 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3366 E = Conversions->end();
3367 I != E;
3368 ++I) {
3369 if (CXXConversionDecl *Conversion
3370 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3371 if (Conversion->getConversionType().getNonReferenceType()
3372 ->isIntegralOrEnumerationType()) {
3373 if (Conversion->isExplicit())
3374 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3375 else
3376 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3377 }
3378 }
3379
3380 switch (ViableConversions.size()) {
3381 case 0:
3382 if (ExplicitConversions.size() == 1) {
3383 DeclAccessPair Found = ExplicitConversions[0];
3384 CXXConversionDecl *Conversion
3385 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3386
3387 // The user probably meant to invoke the given explicit
3388 // conversion; use it.
3389 QualType ConvTy
3390 = Conversion->getConversionType().getNonReferenceType();
3391 std::string TypeStr;
3392 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3393
3394 Diag(Loc, ExplicitConvDiag)
3395 << T << ConvTy
3396 << FixItHint::CreateInsertion(From->getLocStart(),
3397 "static_cast<" + TypeStr + ">(")
3398 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3399 ")");
3400 Diag(Conversion->getLocation(), ExplicitConvNote)
3401 << ConvTy->isEnumeralType() << ConvTy;
3402
3403 // If we aren't in a SFINAE context, build a call to the
3404 // explicit conversion function.
3405 if (isSFINAEContext())
3406 return ExprError();
3407
3408 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
John McCall9ae2f072010-08-23 23:25:46 +00003409 From = BuildCXXMemberCallExpr(From, Found, Conversion);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003410 }
3411
3412 // We'll complain below about a non-integral condition type.
3413 break;
3414
3415 case 1: {
3416 // Apply this conversion.
3417 DeclAccessPair Found = ViableConversions[0];
3418 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003419
3420 CXXConversionDecl *Conversion
3421 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3422 QualType ConvTy
3423 = Conversion->getConversionType().getNonReferenceType();
3424 if (ConvDiag.getDiagID()) {
3425 if (isSFINAEContext())
3426 return ExprError();
3427
3428 Diag(Loc, ConvDiag)
3429 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3430 }
3431
John McCall9ae2f072010-08-23 23:25:46 +00003432 From = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorc30614b2010-06-29 23:17:37 +00003433 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregorc30614b2010-06-29 23:17:37 +00003434 break;
3435 }
3436
3437 default:
3438 Diag(Loc, AmbigDiag)
3439 << T << From->getSourceRange();
3440 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3441 CXXConversionDecl *Conv
3442 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3443 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3444 Diag(Conv->getLocation(), AmbigNote)
3445 << ConvTy->isEnumeralType() << ConvTy;
3446 }
John McCall9ae2f072010-08-23 23:25:46 +00003447 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003448 }
3449
Douglas Gregoracb0bd82010-06-29 23:25:20 +00003450 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorc30614b2010-06-29 23:17:37 +00003451 Diag(Loc, NotIntDiag)
3452 << From->getType() << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00003453
John McCall9ae2f072010-08-23 23:25:46 +00003454 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003455}
3456
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003457/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00003458/// candidate functions, using the given function call arguments. If
3459/// @p SuppressUserConversions, then don't allow user-defined
3460/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003461///
3462/// \para PartialOverloading true if we are performing "partial" overloading
3463/// based on an incomplete set of function arguments. This feature is used by
3464/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00003465void
3466Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00003467 DeclAccessPair FoundDecl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003468 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00003469 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00003470 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003471 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00003472 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003473 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003474 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00003475 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00003476 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00003477
Douglas Gregor88a35142008-12-22 05:46:06 +00003478 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003479 if (!isa<CXXConstructorDecl>(Method)) {
3480 // If we get here, it's because we're calling a member function
3481 // that is named without a member access expression (e.g.,
3482 // "this->f") that was either written explicitly or created
3483 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00003484 // function, e.g., X::f(). We use an empty type for the implied
3485 // object argument (C++ [over.call.func]p3), and the acting context
3486 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00003487 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall701c89e2009-12-03 04:06:58 +00003488 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003489 SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003490 return;
3491 }
3492 // We treat a constructor like a non-member function, since its object
3493 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00003494 }
3495
Douglas Gregorfd476482009-11-13 23:59:09 +00003496 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00003497 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00003498
Douglas Gregor7edfb692009-11-23 12:27:39 +00003499 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003500 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003501
Douglas Gregor66724ea2009-11-14 01:20:54 +00003502 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3503 // C++ [class.copy]p3:
3504 // A member function template is never instantiated to perform the copy
3505 // of a class object to an object of its class type.
3506 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3507 if (NumArgs == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00003508 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00003509 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3510 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00003511 return;
3512 }
3513
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003514 // Add this candidate
3515 CandidateSet.push_back(OverloadCandidate());
3516 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003517 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003518 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00003519 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003520 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003521 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003522
3523 unsigned NumArgsInProto = Proto->getNumArgs();
3524
3525 // (C++ 13.3.2p2): A candidate function having fewer than m
3526 // parameters is viable only if it has an ellipsis in its parameter
3527 // list (8.3.5).
Douglas Gregor5bd1a112009-09-23 14:56:09 +00003528 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3529 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003530 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003531 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003532 return;
3533 }
3534
3535 // (C++ 13.3.2p2): A candidate function having more than m parameters
3536 // is viable only if the (m+1)st parameter has a default argument
3537 // (8.3.6). For the purposes of overload resolution, the
3538 // parameter list is truncated on the right, so that there are
3539 // exactly m parameters.
3540 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003541 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003542 // Not enough arguments.
3543 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003544 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003545 return;
3546 }
3547
3548 // Determine the implicit conversion sequences for each of the
3549 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003550 Candidate.Conversions.resize(NumArgs);
3551 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3552 if (ArgIdx < NumArgsInProto) {
3553 // (C++ 13.3.2p3): for F to be a viable function, there shall
3554 // exist for each argument an implicit conversion sequence
3555 // (13.3.3.1) that converts that argument to the corresponding
3556 // parameter of F.
3557 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003558 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003559 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003560 SuppressUserConversions,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003561 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003562 if (Candidate.Conversions[ArgIdx].isBad()) {
3563 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003564 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00003565 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00003566 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003567 } else {
3568 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3569 // argument for which there is no corresponding parameter is
3570 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003571 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003572 }
3573 }
3574}
3575
Douglas Gregor063daf62009-03-13 18:40:31 +00003576/// \brief Add all of the function declarations in the given function set to
3577/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00003578void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00003579 Expr **Args, unsigned NumArgs,
3580 OverloadCandidateSet& CandidateSet,
3581 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00003582 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00003583 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3584 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003585 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003586 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003587 cast<CXXMethodDecl>(FD)->getParent(),
3588 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003589 CandidateSet, SuppressUserConversions);
3590 else
John McCall9aa472c2010-03-19 07:35:19 +00003591 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00003592 SuppressUserConversions);
3593 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003594 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00003595 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3596 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003597 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003598 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00003599 /*FIXME: explicit args */ 0,
John McCall701c89e2009-12-03 04:06:58 +00003600 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003601 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00003602 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00003603 else
John McCall9aa472c2010-03-19 07:35:19 +00003604 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCalld5532b62009-11-23 01:53:49 +00003605 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00003606 Args, NumArgs, CandidateSet,
3607 SuppressUserConversions);
3608 }
Douglas Gregor364e0212009-06-27 21:05:07 +00003609 }
Douglas Gregor063daf62009-03-13 18:40:31 +00003610}
3611
John McCall314be4e2009-11-17 07:50:12 +00003612/// AddMethodCandidate - Adds a named decl (which is some kind of
3613/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00003614void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003615 QualType ObjectType,
John McCall314be4e2009-11-17 07:50:12 +00003616 Expr **Args, unsigned NumArgs,
3617 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003618 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00003619 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003620 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00003621
3622 if (isa<UsingShadowDecl>(Decl))
3623 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3624
3625 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3626 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3627 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00003628 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3629 /*ExplicitArgs*/ 0,
John McCall701c89e2009-12-03 04:06:58 +00003630 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00003631 CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003632 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003633 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003634 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall701c89e2009-12-03 04:06:58 +00003635 ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003636 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003637 }
3638}
3639
Douglas Gregor96176b32008-11-18 23:14:02 +00003640/// AddMethodCandidate - Adds the given C++ member function to the set
3641/// of candidate functions, using the given function call arguments
3642/// and the object argument (@c Object). For example, in a call
3643/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3644/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3645/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00003646/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00003647void
John McCall9aa472c2010-03-19 07:35:19 +00003648Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003649 CXXRecordDecl *ActingContext, QualType ObjectType,
3650 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00003651 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003652 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00003653 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003654 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00003655 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003656 assert(!isa<CXXConstructorDecl>(Method) &&
3657 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00003658
Douglas Gregor3f396022009-09-28 04:47:19 +00003659 if (!CandidateSet.isNewCandidate(Method))
3660 return;
3661
Douglas Gregor7edfb692009-11-23 12:27:39 +00003662 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003663 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003664
Douglas Gregor96176b32008-11-18 23:14:02 +00003665 // Add this candidate
3666 CandidateSet.push_back(OverloadCandidate());
3667 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003668 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00003669 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003670 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003671 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003672
3673 unsigned NumArgsInProto = Proto->getNumArgs();
3674
3675 // (C++ 13.3.2p2): A candidate function having fewer than m
3676 // parameters is viable only if it has an ellipsis in its parameter
3677 // list (8.3.5).
3678 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3679 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003680 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003681 return;
3682 }
3683
3684 // (C++ 13.3.2p2): A candidate function having more than m parameters
3685 // is viable only if the (m+1)st parameter has a default argument
3686 // (8.3.6). For the purposes of overload resolution, the
3687 // parameter list is truncated on the right, so that there are
3688 // exactly m parameters.
3689 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3690 if (NumArgs < MinRequiredArgs) {
3691 // Not enough arguments.
3692 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003693 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003694 return;
3695 }
3696
3697 Candidate.Viable = true;
3698 Candidate.Conversions.resize(NumArgs + 1);
3699
John McCall701c89e2009-12-03 04:06:58 +00003700 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00003701 // The implicit object argument is ignored.
3702 Candidate.IgnoreObjectArgument = true;
3703 else {
3704 // Determine the implicit conversion sequence for the object
3705 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00003706 Candidate.Conversions[0]
John McCall120d63c2010-08-24 20:38:10 +00003707 = TryObjectArgumentInitialization(*this, ObjectType, Method,
3708 ActingContext);
John McCall1d318332010-01-12 00:44:57 +00003709 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003710 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003711 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00003712 return;
3713 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003714 }
3715
3716 // Determine the implicit conversion sequences for each of the
3717 // arguments.
3718 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3719 if (ArgIdx < NumArgsInProto) {
3720 // (C++ 13.3.2p3): for F to be a viable function, there shall
3721 // exist for each argument an implicit conversion sequence
3722 // (13.3.3.1) that converts that argument to the corresponding
3723 // parameter of F.
3724 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003725 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003726 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003727 SuppressUserConversions,
Anders Carlsson08972922009-08-28 15:33:32 +00003728 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003729 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00003730 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003731 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00003732 break;
3733 }
3734 } else {
3735 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3736 // argument for which there is no corresponding parameter is
3737 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003738 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00003739 }
3740 }
3741}
Douglas Gregora9333192010-05-08 17:41:32 +00003742
Douglas Gregor6b906862009-08-21 00:16:32 +00003743/// \brief Add a C++ member function template as a candidate to the candidate
3744/// set, using template argument deduction to produce an appropriate member
3745/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003746void
Douglas Gregor6b906862009-08-21 00:16:32 +00003747Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00003748 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003749 CXXRecordDecl *ActingContext,
John McCalld5532b62009-11-23 01:53:49 +00003750 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00003751 QualType ObjectType,
3752 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003753 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003754 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003755 if (!CandidateSet.isNewCandidate(MethodTmpl))
3756 return;
3757
Douglas Gregor6b906862009-08-21 00:16:32 +00003758 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003759 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00003760 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003761 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00003762 // candidate functions in the usual way.113) A given name can refer to one
3763 // or more function templates and also to a set of overloaded non-template
3764 // functions. In such a case, the candidate functions generated from each
3765 // function template are combined with the set of non-template candidate
3766 // functions.
John McCall5769d612010-02-08 23:07:23 +00003767 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00003768 FunctionDecl *Specialization = 0;
3769 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003770 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003771 Args, NumArgs, Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003772 CandidateSet.push_back(OverloadCandidate());
3773 OverloadCandidate &Candidate = CandidateSet.back();
3774 Candidate.FoundDecl = FoundDecl;
3775 Candidate.Function = MethodTmpl->getTemplatedDecl();
3776 Candidate.Viable = false;
3777 Candidate.FailureKind = ovl_fail_bad_deduction;
3778 Candidate.IsSurrogate = false;
3779 Candidate.IgnoreObjectArgument = false;
3780 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3781 Info);
3782 return;
3783 }
Mike Stump1eb44332009-09-09 15:08:12 +00003784
Douglas Gregor6b906862009-08-21 00:16:32 +00003785 // Add the function template specialization produced by template argument
3786 // deduction as a candidate.
3787 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00003788 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00003789 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00003790 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003791 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003792 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00003793}
3794
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003795/// \brief Add a C++ function template specialization as a candidate
3796/// in the candidate set, using template argument deduction to produce
3797/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003798void
Douglas Gregore53060f2009-06-25 22:08:12 +00003799Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003800 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00003801 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00003802 Expr **Args, unsigned NumArgs,
3803 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003804 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003805 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3806 return;
3807
Douglas Gregore53060f2009-06-25 22:08:12 +00003808 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003809 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00003810 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003811 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00003812 // candidate functions in the usual way.113) A given name can refer to one
3813 // or more function templates and also to a set of overloaded non-template
3814 // functions. In such a case, the candidate functions generated from each
3815 // function template are combined with the set of non-template candidate
3816 // functions.
John McCall5769d612010-02-08 23:07:23 +00003817 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00003818 FunctionDecl *Specialization = 0;
3819 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003820 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003821 Args, NumArgs, Specialization, Info)) {
John McCall578b69b2009-12-16 08:11:27 +00003822 CandidateSet.push_back(OverloadCandidate());
3823 OverloadCandidate &Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003824 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00003825 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3826 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003827 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00003828 Candidate.IsSurrogate = false;
3829 Candidate.IgnoreObjectArgument = false;
Douglas Gregorff5adac2010-05-08 20:18:54 +00003830 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3831 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00003832 return;
3833 }
Mike Stump1eb44332009-09-09 15:08:12 +00003834
Douglas Gregore53060f2009-06-25 22:08:12 +00003835 // Add the function template specialization produced by template argument
3836 // deduction as a candidate.
3837 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003838 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003839 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00003840}
Mike Stump1eb44332009-09-09 15:08:12 +00003841
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003842/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00003843/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003844/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00003845/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003846/// (which may or may not be the same type as the type that the
3847/// conversion function produces).
3848void
3849Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003850 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003851 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003852 Expr *From, QualType ToType,
3853 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003854 assert(!Conversion->getDescribedFunctionTemplate() &&
3855 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003856 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00003857 if (!CandidateSet.isNewCandidate(Conversion))
3858 return;
3859
Douglas Gregor7edfb692009-11-23 12:27:39 +00003860 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003861 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003862
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003863 // Add this candidate
3864 CandidateSet.push_back(OverloadCandidate());
3865 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003866 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003867 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003868 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003869 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003870 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003871 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003872 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003873 Candidate.Viable = true;
3874 Candidate.Conversions.resize(1);
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003875
Douglas Gregorbca39322010-08-19 15:37:02 +00003876 // C++ [over.match.funcs]p4:
3877 // For conversion functions, the function is considered to be a member of
3878 // the class of the implicit implied object argument for the purpose of
3879 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003880 //
3881 // Determine the implicit conversion sequence for the implicit
3882 // object parameter.
3883 QualType ImplicitParamType = From->getType();
3884 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
3885 ImplicitParamType = FromPtrType->getPointeeType();
3886 CXXRecordDecl *ConversionContext
3887 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
3888
3889 Candidate.Conversions[0]
John McCall120d63c2010-08-24 20:38:10 +00003890 = TryObjectArgumentInitialization(*this, From->getType(), Conversion,
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003891 ConversionContext);
3892
John McCall1d318332010-01-12 00:44:57 +00003893 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003894 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003895 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003896 return;
3897 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003898
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003899 // We won't go through a user-define type conversion function to convert a
3900 // derived to base as such conversions are given Conversion Rank. They only
3901 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3902 QualType FromCanon
3903 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3904 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3905 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3906 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003907 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003908 return;
3909 }
3910
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003911 // To determine what the conversion from the result of calling the
3912 // conversion function to the type we're eventually trying to
3913 // convert to (ToType), we need to synthesize a call to the
3914 // conversion function and attempt copy initialization from it. This
3915 // makes sure that we get the right semantics with respect to
3916 // lvalues/rvalues and the type. Fortunately, we can allocate this
3917 // call on the stack and we don't need its arguments to be
3918 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00003919 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00003920 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00003921 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
3922 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00003923 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00003924 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00003925
Douglas Gregor7d14d382010-11-13 19:36:57 +00003926 QualType CallResultType
3927 = Conversion->getConversionType().getNonLValueExprType(Context);
3928 if (RequireCompleteType(From->getLocStart(), CallResultType, 0)) {
3929 Candidate.Viable = false;
3930 Candidate.FailureKind = ovl_fail_bad_final_conversion;
3931 return;
3932 }
3933
John McCallf89e55a2010-11-18 06:31:45 +00003934 ExprValueKind VK = Expr::getValueKindForType(Conversion->getConversionType());
3935
Mike Stump1eb44332009-09-09 15:08:12 +00003936 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00003937 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3938 // allocator).
John McCallf89e55a2010-11-18 06:31:45 +00003939 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003940 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00003941 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00003942 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00003943 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003944 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00003945
John McCall1d318332010-01-12 00:44:57 +00003946 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003947 case ImplicitConversionSequence::StandardConversion:
3948 Candidate.FinalConversion = ICS.Standard;
Douglas Gregorc520c842010-04-12 23:42:09 +00003949
3950 // C++ [over.ics.user]p3:
3951 // If the user-defined conversion is specified by a specialization of a
3952 // conversion function template, the second standard conversion sequence
3953 // shall have exact match rank.
3954 if (Conversion->getPrimaryTemplate() &&
3955 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3956 Candidate.Viable = false;
3957 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3958 }
3959
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003960 break;
3961
3962 case ImplicitConversionSequence::BadConversion:
3963 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003964 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003965 break;
3966
3967 default:
Mike Stump1eb44332009-09-09 15:08:12 +00003968 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003969 "Can only end up with a standard conversion sequence or failure");
3970 }
3971}
3972
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003973/// \brief Adds a conversion function template specialization
3974/// candidate to the overload set, using template argument deduction
3975/// to deduce the template arguments of the conversion function
3976/// template from the type that we are converting to (C++
3977/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00003978void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003979Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003980 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003981 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003982 Expr *From, QualType ToType,
3983 OverloadCandidateSet &CandidateSet) {
3984 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3985 "Only conversion function templates permitted here");
3986
Douglas Gregor3f396022009-09-28 04:47:19 +00003987 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3988 return;
3989
John McCall5769d612010-02-08 23:07:23 +00003990 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003991 CXXConversionDecl *Specialization = 0;
3992 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00003993 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003994 Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003995 CandidateSet.push_back(OverloadCandidate());
3996 OverloadCandidate &Candidate = CandidateSet.back();
3997 Candidate.FoundDecl = FoundDecl;
3998 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3999 Candidate.Viable = false;
4000 Candidate.FailureKind = ovl_fail_bad_deduction;
4001 Candidate.IsSurrogate = false;
4002 Candidate.IgnoreObjectArgument = false;
4003 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
4004 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004005 return;
4006 }
Mike Stump1eb44332009-09-09 15:08:12 +00004007
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004008 // Add the conversion function template specialization produced by
4009 // template argument deduction as a candidate.
4010 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00004011 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00004012 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004013}
4014
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004015/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4016/// converts the given @c Object to a function pointer via the
4017/// conversion function @c Conversion, and then attempts to call it
4018/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4019/// the type of function that we'll eventually be calling.
4020void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00004021 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004022 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00004023 const FunctionProtoType *Proto,
John McCall701c89e2009-12-03 04:06:58 +00004024 QualType ObjectType,
4025 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004026 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00004027 if (!CandidateSet.isNewCandidate(Conversion))
4028 return;
4029
Douglas Gregor7edfb692009-11-23 12:27:39 +00004030 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004031 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004032
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004033 CandidateSet.push_back(OverloadCandidate());
4034 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004035 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004036 Candidate.Function = 0;
4037 Candidate.Surrogate = Conversion;
4038 Candidate.Viable = true;
4039 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00004040 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004041 Candidate.Conversions.resize(NumArgs + 1);
4042
4043 // Determine the implicit conversion sequence for the implicit
4044 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00004045 ImplicitConversionSequence ObjectInit
John McCall120d63c2010-08-24 20:38:10 +00004046 = TryObjectArgumentInitialization(*this, ObjectType, Conversion,
4047 ActingContext);
John McCall1d318332010-01-12 00:44:57 +00004048 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004049 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004050 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00004051 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004052 return;
4053 }
4054
4055 // The first conversion is actually a user-defined conversion whose
4056 // first conversion is ObjectInit's standard conversion (which is
4057 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00004058 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004059 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00004060 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004061 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00004062 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004063 = Candidate.Conversions[0].UserDefined.Before;
4064 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4065
Mike Stump1eb44332009-09-09 15:08:12 +00004066 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004067 unsigned NumArgsInProto = Proto->getNumArgs();
4068
4069 // (C++ 13.3.2p2): A candidate function having fewer than m
4070 // parameters is viable only if it has an ellipsis in its parameter
4071 // list (8.3.5).
4072 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4073 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004074 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004075 return;
4076 }
4077
4078 // Function types don't have any default arguments, so just check if
4079 // we have enough arguments.
4080 if (NumArgs < NumArgsInProto) {
4081 // Not enough arguments.
4082 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004083 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004084 return;
4085 }
4086
4087 // Determine the implicit conversion sequences for each of the
4088 // arguments.
4089 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4090 if (ArgIdx < NumArgsInProto) {
4091 // (C++ 13.3.2p3): for F to be a viable function, there shall
4092 // exist for each argument an implicit conversion sequence
4093 // (13.3.3.1) that converts that argument to the corresponding
4094 // parameter of F.
4095 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00004096 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004097 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00004098 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00004099 /*InOverloadResolution=*/false);
John McCall1d318332010-01-12 00:44:57 +00004100 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004101 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004102 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004103 break;
4104 }
4105 } else {
4106 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4107 // argument for which there is no corresponding parameter is
4108 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00004109 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004110 }
4111 }
4112}
4113
Douglas Gregor063daf62009-03-13 18:40:31 +00004114/// \brief Add overload candidates for overloaded operators that are
4115/// member functions.
4116///
4117/// Add the overloaded operator candidates that are member functions
4118/// for the operator Op that was used in an operator expression such
4119/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4120/// CandidateSet will store the added overload candidates. (C++
4121/// [over.match.oper]).
4122void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4123 SourceLocation OpLoc,
4124 Expr **Args, unsigned NumArgs,
4125 OverloadCandidateSet& CandidateSet,
4126 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00004127 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4128
4129 // C++ [over.match.oper]p3:
4130 // For a unary operator @ with an operand of a type whose
4131 // cv-unqualified version is T1, and for a binary operator @ with
4132 // a left operand of a type whose cv-unqualified version is T1 and
4133 // a right operand of a type whose cv-unqualified version is T2,
4134 // three sets of candidate functions, designated member
4135 // candidates, non-member candidates and built-in candidates, are
4136 // constructed as follows:
4137 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00004138
4139 // -- If T1 is a class type, the set of member candidates is the
4140 // result of the qualified lookup of T1::operator@
4141 // (13.3.1.1.1); otherwise, the set of member candidates is
4142 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00004143 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004144 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004145 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004146 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004147
John McCalla24dc2e2009-11-17 02:14:36 +00004148 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4149 LookupQualifiedName(Operators, T1Rec->getDecl());
4150 Operators.suppressDiagnostics();
4151
Mike Stump1eb44332009-09-09 15:08:12 +00004152 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004153 OperEnd = Operators.end();
4154 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00004155 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00004156 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall701c89e2009-12-03 04:06:58 +00004157 Args + 1, NumArgs - 1, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00004158 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00004159 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004160}
4161
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004162/// AddBuiltinCandidate - Add a candidate for a built-in
4163/// operator. ResultTy and ParamTys are the result and parameter types
4164/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004165/// arguments being passed to the candidate. IsAssignmentOperator
4166/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004167/// operator. NumContextualBoolArguments is the number of arguments
4168/// (at the beginning of the argument list) that will be contextually
4169/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00004170void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004171 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004172 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004173 bool IsAssignmentOperator,
4174 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00004175 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004176 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004177
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004178 // Add this candidate
4179 CandidateSet.push_back(OverloadCandidate());
4180 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004181 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004182 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00004183 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004184 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004185 Candidate.BuiltinTypes.ResultTy = ResultTy;
4186 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4187 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4188
4189 // Determine the implicit conversion sequences for each of the
4190 // arguments.
4191 Candidate.Viable = true;
4192 Candidate.Conversions.resize(NumArgs);
4193 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004194 // C++ [over.match.oper]p4:
4195 // For the built-in assignment operators, conversions of the
4196 // left operand are restricted as follows:
4197 // -- no temporaries are introduced to hold the left operand, and
4198 // -- no user-defined conversions are applied to the left
4199 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00004200 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004201 //
4202 // We block these conversions by turning off user-defined
4203 // conversions, since that is the only way that initialization of
4204 // a reference to a non-class type can occur from something that
4205 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004206 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00004207 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004208 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00004209 Candidate.Conversions[ArgIdx]
4210 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004211 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00004212 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004213 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00004214 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00004215 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004216 }
John McCall1d318332010-01-12 00:44:57 +00004217 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004218 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004219 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00004220 break;
4221 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004222 }
4223}
4224
4225/// BuiltinCandidateTypeSet - A set of types that will be used for the
4226/// candidate operator functions for built-in operators (C++
4227/// [over.built]). The types are separated into pointer types and
4228/// enumeration types.
4229class BuiltinCandidateTypeSet {
4230 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004231 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004232
4233 /// PointerTypes - The set of pointer types that will be used in the
4234 /// built-in candidates.
4235 TypeSet PointerTypes;
4236
Sebastian Redl78eb8742009-04-19 21:53:20 +00004237 /// MemberPointerTypes - The set of member pointer types that will be
4238 /// used in the built-in candidates.
4239 TypeSet MemberPointerTypes;
4240
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004241 /// EnumerationTypes - The set of enumeration types that will be
4242 /// used in the built-in candidates.
4243 TypeSet EnumerationTypes;
4244
Douglas Gregor26bcf672010-05-19 03:21:00 +00004245 /// \brief The set of vector types that will be used in the built-in
4246 /// candidates.
4247 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00004248
4249 /// \brief A flag indicating non-record types are viable candidates
4250 bool HasNonRecordTypes;
4251
4252 /// \brief A flag indicating whether either arithmetic or enumeration types
4253 /// were present in the candidate set.
4254 bool HasArithmeticOrEnumeralTypes;
4255
Douglas Gregor5842ba92009-08-24 15:23:48 +00004256 /// Sema - The semantic analysis instance where we are building the
4257 /// candidate type set.
4258 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00004259
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004260 /// Context - The AST context in which we will build the type sets.
4261 ASTContext &Context;
4262
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004263 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4264 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00004265 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004266
4267public:
4268 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004269 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004270
Mike Stump1eb44332009-09-09 15:08:12 +00004271 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00004272 : HasNonRecordTypes(false),
4273 HasArithmeticOrEnumeralTypes(false),
4274 SemaRef(SemaRef),
4275 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004276
Douglas Gregor573d9c32009-10-21 23:19:44 +00004277 void AddTypesConvertedFrom(QualType Ty,
4278 SourceLocation Loc,
4279 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004280 bool AllowExplicitConversions,
4281 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004282
4283 /// pointer_begin - First pointer type found;
4284 iterator pointer_begin() { return PointerTypes.begin(); }
4285
Sebastian Redl78eb8742009-04-19 21:53:20 +00004286 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004287 iterator pointer_end() { return PointerTypes.end(); }
4288
Sebastian Redl78eb8742009-04-19 21:53:20 +00004289 /// member_pointer_begin - First member pointer type found;
4290 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4291
4292 /// member_pointer_end - Past the last member pointer type found;
4293 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4294
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004295 /// enumeration_begin - First enumeration type found;
4296 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4297
Sebastian Redl78eb8742009-04-19 21:53:20 +00004298 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004299 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004300
4301 iterator vector_begin() { return VectorTypes.begin(); }
4302 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00004303
4304 bool hasNonRecordTypes() { return HasNonRecordTypes; }
4305 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004306};
4307
Sebastian Redl78eb8742009-04-19 21:53:20 +00004308/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004309/// the set of pointer types along with any more-qualified variants of
4310/// that type. For example, if @p Ty is "int const *", this routine
4311/// will add "int const *", "int const volatile *", "int const
4312/// restrict *", and "int const volatile restrict *" to the set of
4313/// pointer types. Returns true if the add of @p Ty itself succeeded,
4314/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00004315///
4316/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004317bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00004318BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4319 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00004320
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004321 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004322 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004323 return false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004324
4325 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00004326 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004327 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004328 if (!PointerTy) {
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004329 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004330 PointeeTy = PTy->getPointeeType();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004331 buildObjCPtr = true;
4332 }
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004333 else
4334 assert(false && "type was not a pointer type!");
4335 }
4336 else
4337 PointeeTy = PointerTy->getPointeeType();
4338
Sebastian Redla9efada2009-11-18 20:39:26 +00004339 // Don't add qualified variants of arrays. For one, they're not allowed
4340 // (the qualifier would sink to the element type), and for another, the
4341 // only overload situation where it matters is subscript or pointer +- int,
4342 // and those shouldn't have qualifier variants anyway.
4343 if (PointeeTy->isArrayType())
4344 return true;
John McCall0953e762009-09-24 19:53:00 +00004345 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00004346 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00004347 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004348 bool hasVolatile = VisibleQuals.hasVolatile();
4349 bool hasRestrict = VisibleQuals.hasRestrict();
4350
John McCall0953e762009-09-24 19:53:00 +00004351 // Iterate through all strict supersets of BaseCVR.
4352 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4353 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004354 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4355 // in the types.
4356 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4357 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00004358 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004359 if (!buildObjCPtr)
4360 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4361 else
4362 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004363 }
4364
4365 return true;
4366}
4367
Sebastian Redl78eb8742009-04-19 21:53:20 +00004368/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4369/// to the set of pointer types along with any more-qualified variants of
4370/// that type. For example, if @p Ty is "int const *", this routine
4371/// will add "int const *", "int const volatile *", "int const
4372/// restrict *", and "int const volatile restrict *" to the set of
4373/// pointer types. Returns true if the add of @p Ty itself succeeded,
4374/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00004375///
4376/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004377bool
4378BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4379 QualType Ty) {
4380 // Insert this type.
4381 if (!MemberPointerTypes.insert(Ty))
4382 return false;
4383
John McCall0953e762009-09-24 19:53:00 +00004384 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4385 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00004386
John McCall0953e762009-09-24 19:53:00 +00004387 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00004388 // Don't add qualified variants of arrays. For one, they're not allowed
4389 // (the qualifier would sink to the element type), and for another, the
4390 // only overload situation where it matters is subscript or pointer +- int,
4391 // and those shouldn't have qualifier variants anyway.
4392 if (PointeeTy->isArrayType())
4393 return true;
John McCall0953e762009-09-24 19:53:00 +00004394 const Type *ClassTy = PointerTy->getClass();
4395
4396 // Iterate through all strict supersets of the pointee type's CVR
4397 // qualifiers.
4398 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4399 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4400 if ((CVR | BaseCVR) != CVR) continue;
4401
4402 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00004403 MemberPointerTypes.insert(
4404 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00004405 }
4406
4407 return true;
4408}
4409
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004410/// AddTypesConvertedFrom - Add each of the types to which the type @p
4411/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00004412/// primarily interested in pointer types and enumeration types. We also
4413/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004414/// AllowUserConversions is true if we should look at the conversion
4415/// functions of a class type, and AllowExplicitConversions if we
4416/// should also include the explicit conversion functions of a class
4417/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00004418void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004419BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004420 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004421 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004422 bool AllowExplicitConversions,
4423 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004424 // Only deal with canonical types.
4425 Ty = Context.getCanonicalType(Ty);
4426
4427 // Look through reference types; they aren't part of the type of an
4428 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00004429 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004430 Ty = RefTy->getPointeeType();
4431
4432 // We don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004433 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004434
Chandler Carruth6a577462010-12-13 01:44:01 +00004435 // Flag if we ever add a non-record type.
4436 const RecordType *TyRec = Ty->getAs<RecordType>();
4437 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
4438
Sebastian Redla65b5512009-11-05 16:36:20 +00004439 // If we're dealing with an array type, decay to the pointer.
4440 if (Ty->isArrayType())
4441 Ty = SemaRef.Context.getArrayDecayedType(Ty);
Chandler Carruth6a577462010-12-13 01:44:01 +00004442
4443 // Flag if we encounter an arithmetic type.
4444 HasArithmeticOrEnumeralTypes =
4445 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
4446
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004447 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4448 PointerTypes.insert(Ty);
4449 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004450 // Insert our type, and its more-qualified variants, into the set
4451 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004452 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004453 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00004454 } else if (Ty->isMemberPointerType()) {
4455 // Member pointers are far easier, since the pointee can't be converted.
4456 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4457 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004458 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00004459 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00004460 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004461 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00004462 // We treat vector types as arithmetic types in many contexts as an
4463 // extension.
4464 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00004465 VectorTypes.insert(Ty);
Chandler Carruth6a577462010-12-13 01:44:01 +00004466 } else if (AllowUserConversions && TyRec) {
4467 // No conversion functions in incomplete types.
4468 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
4469 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004470
Chandler Carruth6a577462010-12-13 01:44:01 +00004471 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
4472 const UnresolvedSetImpl *Conversions
4473 = ClassDecl->getVisibleConversionFunctions();
4474 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
4475 E = Conversions->end(); I != E; ++I) {
4476 NamedDecl *D = I.getDecl();
4477 if (isa<UsingShadowDecl>(D))
4478 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004479
Chandler Carruth6a577462010-12-13 01:44:01 +00004480 // Skip conversion function templates; they don't tell us anything
4481 // about which builtin types we can convert to.
4482 if (isa<FunctionTemplateDecl>(D))
4483 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004484
Chandler Carruth6a577462010-12-13 01:44:01 +00004485 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
4486 if (AllowExplicitConversions || !Conv->isExplicit()) {
4487 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
4488 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004489 }
4490 }
4491 }
4492}
4493
Douglas Gregor19b7b152009-08-24 13:43:27 +00004494/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4495/// the volatile- and non-volatile-qualified assignment operators for the
4496/// given type to the candidate set.
4497static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4498 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00004499 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004500 unsigned NumArgs,
4501 OverloadCandidateSet &CandidateSet) {
4502 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00004503
Douglas Gregor19b7b152009-08-24 13:43:27 +00004504 // T& operator=(T&, T)
4505 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4506 ParamTypes[1] = T;
4507 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4508 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004509
Douglas Gregor19b7b152009-08-24 13:43:27 +00004510 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4511 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00004512 ParamTypes[0]
4513 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00004514 ParamTypes[1] = T;
4515 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00004516 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00004517 }
4518}
Mike Stump1eb44332009-09-09 15:08:12 +00004519
Sebastian Redl9994a342009-10-25 17:03:50 +00004520/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4521/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004522static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4523 Qualifiers VRQuals;
4524 const RecordType *TyRec;
4525 if (const MemberPointerType *RHSMPType =
4526 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004527 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004528 else
4529 TyRec = ArgExpr->getType()->getAs<RecordType>();
4530 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004531 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004532 VRQuals.addVolatile();
4533 VRQuals.addRestrict();
4534 return VRQuals;
4535 }
4536
4537 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00004538 if (!ClassDecl->hasDefinition())
4539 return VRQuals;
4540
John McCalleec51cf2010-01-20 00:46:10 +00004541 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00004542 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004543
John McCalleec51cf2010-01-20 00:46:10 +00004544 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004545 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00004546 NamedDecl *D = I.getDecl();
4547 if (isa<UsingShadowDecl>(D))
4548 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4549 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004550 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4551 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4552 CanTy = ResTypeRef->getPointeeType();
4553 // Need to go down the pointer/mempointer chain and add qualifiers
4554 // as see them.
4555 bool done = false;
4556 while (!done) {
4557 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4558 CanTy = ResTypePtr->getPointeeType();
4559 else if (const MemberPointerType *ResTypeMPtr =
4560 CanTy->getAs<MemberPointerType>())
4561 CanTy = ResTypeMPtr->getPointeeType();
4562 else
4563 done = true;
4564 if (CanTy.isVolatileQualified())
4565 VRQuals.addVolatile();
4566 if (CanTy.isRestrictQualified())
4567 VRQuals.addRestrict();
4568 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4569 return VRQuals;
4570 }
4571 }
4572 }
4573 return VRQuals;
4574}
John McCall00071ec2010-11-13 05:51:15 +00004575
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004576namespace {
John McCall00071ec2010-11-13 05:51:15 +00004577
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004578/// \brief Helper class to manage the addition of builtin operator overload
4579/// candidates. It provides shared state and utility methods used throughout
4580/// the process, as well as a helper method to add each group of builtin
4581/// operator overloads from the standard to a candidate set.
4582class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00004583 // Common instance state available to all overload candidate addition methods.
4584 Sema &S;
4585 Expr **Args;
4586 unsigned NumArgs;
4587 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00004588 bool HasArithmeticOrEnumeralCandidateType;
Chandler Carruth6d695582010-12-12 10:35:00 +00004589 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
4590 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004591
Chandler Carruth6d695582010-12-12 10:35:00 +00004592 // Define some constants used to index and iterate over the arithemetic types
4593 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00004594 // The "promoted arithmetic types" are the arithmetic
4595 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00004596 static const unsigned FirstIntegralType = 3;
4597 static const unsigned LastIntegralType = 18;
4598 static const unsigned FirstPromotedIntegralType = 3,
4599 LastPromotedIntegralType = 9;
4600 static const unsigned FirstPromotedArithmeticType = 0,
4601 LastPromotedArithmeticType = 9;
4602 static const unsigned NumArithmeticTypes = 18;
4603
Chandler Carruth6d695582010-12-12 10:35:00 +00004604 /// \brief Get the canonical type for a given arithmetic type index.
4605 CanQualType getArithmeticType(unsigned index) {
4606 assert(index < NumArithmeticTypes);
4607 static CanQualType ASTContext::* const
4608 ArithmeticTypes[NumArithmeticTypes] = {
4609 // Start of promoted types.
4610 &ASTContext::FloatTy,
4611 &ASTContext::DoubleTy,
4612 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00004613
Chandler Carruth6d695582010-12-12 10:35:00 +00004614 // Start of integral types.
4615 &ASTContext::IntTy,
4616 &ASTContext::LongTy,
4617 &ASTContext::LongLongTy,
4618 &ASTContext::UnsignedIntTy,
4619 &ASTContext::UnsignedLongTy,
4620 &ASTContext::UnsignedLongLongTy,
4621 // End of promoted types.
4622
4623 &ASTContext::BoolTy,
4624 &ASTContext::CharTy,
4625 &ASTContext::WCharTy,
4626 &ASTContext::Char16Ty,
4627 &ASTContext::Char32Ty,
4628 &ASTContext::SignedCharTy,
4629 &ASTContext::ShortTy,
4630 &ASTContext::UnsignedCharTy,
4631 &ASTContext::UnsignedShortTy,
4632 // End of integral types.
4633 // FIXME: What about complex?
4634 };
4635 return S.Context.*ArithmeticTypes[index];
4636 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004637
Chandler Carruth38ca8d12010-12-12 09:59:53 +00004638 /// \brief Gets the canonical type resulting from the usual arithemetic
4639 /// converions for the given arithmetic types.
4640 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
4641 // Accelerator table for performing the usual arithmetic conversions.
4642 // The rules are basically:
4643 // - if either is floating-point, use the wider floating-point
4644 // - if same signedness, use the higher rank
4645 // - if same size, use unsigned of the higher rank
4646 // - use the larger type
4647 // These rules, together with the axiom that higher ranks are
4648 // never smaller, are sufficient to precompute all of these results
4649 // *except* when dealing with signed types of higher rank.
4650 // (we could precompute SLL x UI for all known platforms, but it's
4651 // better not to make any assumptions).
4652 enum PromotedType {
4653 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
4654 };
4655 static PromotedType ConversionsTable[LastPromotedArithmeticType]
4656 [LastPromotedArithmeticType] = {
4657 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
4658 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
4659 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
4660 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
4661 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
4662 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
4663 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
4664 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
4665 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
4666 };
4667
4668 assert(L < LastPromotedArithmeticType);
4669 assert(R < LastPromotedArithmeticType);
4670 int Idx = ConversionsTable[L][R];
4671
4672 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00004673 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00004674
4675 // Slow path: we need to compare widths.
4676 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00004677 CanQualType LT = getArithmeticType(L),
4678 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00004679 unsigned LW = S.Context.getIntWidth(LT),
4680 RW = S.Context.getIntWidth(RT);
4681
4682 // If they're different widths, use the signed type.
4683 if (LW > RW) return LT;
4684 else if (LW < RW) return RT;
4685
4686 // Otherwise, use the unsigned type of the signed type's rank.
4687 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
4688 assert(L == SLL || R == SLL);
4689 return S.Context.UnsignedLongLongTy;
4690 }
4691
Chandler Carruth3c69dc42010-12-12 09:22:45 +00004692 /// \brief Helper method to factor out the common pattern of adding overloads
4693 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004694 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
4695 bool HasVolatile) {
4696 QualType ParamTypes[2] = {
4697 S.Context.getLValueReferenceType(CandidateTy),
4698 S.Context.IntTy
4699 };
4700
4701 // Non-volatile version.
4702 if (NumArgs == 1)
4703 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4704 else
4705 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
4706
4707 // Use a heuristic to reduce number of builtin candidates in the set:
4708 // add volatile version only if there are conversions to a volatile type.
4709 if (HasVolatile) {
4710 ParamTypes[0] =
4711 S.Context.getLValueReferenceType(
4712 S.Context.getVolatileType(CandidateTy));
4713 if (NumArgs == 1)
4714 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4715 else
4716 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
4717 }
4718 }
4719
4720public:
4721 BuiltinOperatorOverloadBuilder(
4722 Sema &S, Expr **Args, unsigned NumArgs,
4723 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00004724 bool HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004725 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
4726 OverloadCandidateSet &CandidateSet)
4727 : S(S), Args(Args), NumArgs(NumArgs),
4728 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00004729 HasArithmeticOrEnumeralCandidateType(
4730 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004731 CandidateTypes(CandidateTypes),
4732 CandidateSet(CandidateSet) {
4733 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00004734 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004735 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00004736 assert(getArithmeticType(LastPromotedIntegralType - 1)
4737 == S.Context.UnsignedLongLongTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004738 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00004739 assert(getArithmeticType(FirstPromotedArithmeticType)
4740 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004741 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00004742 assert(getArithmeticType(LastPromotedArithmeticType - 1)
4743 == S.Context.UnsignedLongLongTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004744 "Invalid last promoted arithmetic type");
4745 }
4746
4747 // C++ [over.built]p3:
4748 //
4749 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4750 // is either volatile or empty, there exist candidate operator
4751 // functions of the form
4752 //
4753 // VQ T& operator++(VQ T&);
4754 // T operator++(VQ T&, int);
4755 //
4756 // C++ [over.built]p4:
4757 //
4758 // For every pair (T, VQ), where T is an arithmetic type other
4759 // than bool, and VQ is either volatile or empty, there exist
4760 // candidate operator functions of the form
4761 //
4762 // VQ T& operator--(VQ T&);
4763 // T operator--(VQ T&, int);
4764 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00004765 if (!HasArithmeticOrEnumeralCandidateType)
4766 return;
4767
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004768 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
4769 Arith < NumArithmeticTypes; ++Arith) {
4770 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00004771 getArithmeticType(Arith),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004772 VisibleTypeConversionsQuals.hasVolatile());
4773 }
4774 }
4775
4776 // C++ [over.built]p5:
4777 //
4778 // For every pair (T, VQ), where T is a cv-qualified or
4779 // cv-unqualified object type, and VQ is either volatile or
4780 // empty, there exist candidate operator functions of the form
4781 //
4782 // T*VQ& operator++(T*VQ&);
4783 // T*VQ& operator--(T*VQ&);
4784 // T* operator++(T*VQ&, int);
4785 // T* operator--(T*VQ&, int);
4786 void addPlusPlusMinusMinusPointerOverloads() {
4787 for (BuiltinCandidateTypeSet::iterator
4788 Ptr = CandidateTypes[0].pointer_begin(),
4789 PtrEnd = CandidateTypes[0].pointer_end();
4790 Ptr != PtrEnd; ++Ptr) {
4791 // Skip pointer types that aren't pointers to object types.
4792 if (!(*Ptr)->getPointeeType()->isIncompleteOrObjectType())
4793 continue;
4794
4795 addPlusPlusMinusMinusStyleOverloads(*Ptr,
4796 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4797 VisibleTypeConversionsQuals.hasVolatile()));
4798 }
4799 }
4800
4801 // C++ [over.built]p6:
4802 // For every cv-qualified or cv-unqualified object type T, there
4803 // exist candidate operator functions of the form
4804 //
4805 // T& operator*(T*);
4806 //
4807 // C++ [over.built]p7:
4808 // For every function type T, there exist candidate operator
4809 // functions of the form
4810 // T& operator*(T*);
4811 void addUnaryStarPointerOverloads() {
4812 for (BuiltinCandidateTypeSet::iterator
4813 Ptr = CandidateTypes[0].pointer_begin(),
4814 PtrEnd = CandidateTypes[0].pointer_end();
4815 Ptr != PtrEnd; ++Ptr) {
4816 QualType ParamTy = *Ptr;
4817 QualType PointeeTy = ParamTy->getPointeeType();
4818 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
4819 &ParamTy, Args, 1, CandidateSet);
4820 }
4821 }
4822
4823 // C++ [over.built]p9:
4824 // For every promoted arithmetic type T, there exist candidate
4825 // operator functions of the form
4826 //
4827 // T operator+(T);
4828 // T operator-(T);
4829 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00004830 if (!HasArithmeticOrEnumeralCandidateType)
4831 return;
4832
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004833 for (unsigned Arith = FirstPromotedArithmeticType;
4834 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00004835 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004836 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4837 }
4838
4839 // Extension: We also add these operators for vector types.
4840 for (BuiltinCandidateTypeSet::iterator
4841 Vec = CandidateTypes[0].vector_begin(),
4842 VecEnd = CandidateTypes[0].vector_end();
4843 Vec != VecEnd; ++Vec) {
4844 QualType VecTy = *Vec;
4845 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4846 }
4847 }
4848
4849 // C++ [over.built]p8:
4850 // For every type T, there exist candidate operator functions of
4851 // the form
4852 //
4853 // T* operator+(T*);
4854 void addUnaryPlusPointerOverloads() {
4855 for (BuiltinCandidateTypeSet::iterator
4856 Ptr = CandidateTypes[0].pointer_begin(),
4857 PtrEnd = CandidateTypes[0].pointer_end();
4858 Ptr != PtrEnd; ++Ptr) {
4859 QualType ParamTy = *Ptr;
4860 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4861 }
4862 }
4863
4864 // C++ [over.built]p10:
4865 // For every promoted integral type T, there exist candidate
4866 // operator functions of the form
4867 //
4868 // T operator~(T);
4869 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00004870 if (!HasArithmeticOrEnumeralCandidateType)
4871 return;
4872
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004873 for (unsigned Int = FirstPromotedIntegralType;
4874 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00004875 QualType IntTy = getArithmeticType(Int);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004876 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4877 }
4878
4879 // Extension: We also add this operator for vector types.
4880 for (BuiltinCandidateTypeSet::iterator
4881 Vec = CandidateTypes[0].vector_begin(),
4882 VecEnd = CandidateTypes[0].vector_end();
4883 Vec != VecEnd; ++Vec) {
4884 QualType VecTy = *Vec;
4885 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4886 }
4887 }
4888
4889 // C++ [over.match.oper]p16:
4890 // For every pointer to member type T, there exist candidate operator
4891 // functions of the form
4892 //
4893 // bool operator==(T,T);
4894 // bool operator!=(T,T);
4895 void addEqualEqualOrNotEqualMemberPointerOverloads() {
4896 /// Set of (canonical) types that we've already handled.
4897 llvm::SmallPtrSet<QualType, 8> AddedTypes;
4898
4899 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4900 for (BuiltinCandidateTypeSet::iterator
4901 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
4902 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
4903 MemPtr != MemPtrEnd;
4904 ++MemPtr) {
4905 // Don't add the same builtin candidate twice.
4906 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
4907 continue;
4908
4909 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4910 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
4911 CandidateSet);
4912 }
4913 }
4914 }
4915
4916 // C++ [over.built]p15:
4917 //
4918 // For every pointer or enumeration type T, there exist
4919 // candidate operator functions of the form
4920 //
4921 // bool operator<(T, T);
4922 // bool operator>(T, T);
4923 // bool operator<=(T, T);
4924 // bool operator>=(T, T);
4925 // bool operator==(T, T);
4926 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00004927 void addRelationalPointerOrEnumeralOverloads() {
4928 // C++ [over.built]p1:
4929 // If there is a user-written candidate with the same name and parameter
4930 // types as a built-in candidate operator function, the built-in operator
4931 // function is hidden and is not included in the set of candidate
4932 // functions.
4933 //
4934 // The text is actually in a note, but if we don't implement it then we end
4935 // up with ambiguities when the user provides an overloaded operator for
4936 // an enumeration type. Note that only enumeration types have this problem,
4937 // so we track which enumeration types we've seen operators for. Also, the
4938 // only other overloaded operator with enumeration argumenst, operator=,
4939 // cannot be overloaded for enumeration types, so this is the only place
4940 // where we must suppress candidates like this.
4941 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
4942 UserDefinedBinaryOperators;
4943
4944 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4945 if (CandidateTypes[ArgIdx].enumeration_begin() !=
4946 CandidateTypes[ArgIdx].enumeration_end()) {
4947 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
4948 CEnd = CandidateSet.end();
4949 C != CEnd; ++C) {
4950 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
4951 continue;
4952
4953 QualType FirstParamType =
4954 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
4955 QualType SecondParamType =
4956 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
4957
4958 // Skip if either parameter isn't of enumeral type.
4959 if (!FirstParamType->isEnumeralType() ||
4960 !SecondParamType->isEnumeralType())
4961 continue;
4962
4963 // Add this operator to the set of known user-defined operators.
4964 UserDefinedBinaryOperators.insert(
4965 std::make_pair(S.Context.getCanonicalType(FirstParamType),
4966 S.Context.getCanonicalType(SecondParamType)));
4967 }
4968 }
4969 }
4970
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004971 /// Set of (canonical) types that we've already handled.
4972 llvm::SmallPtrSet<QualType, 8> AddedTypes;
4973
4974 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4975 for (BuiltinCandidateTypeSet::iterator
4976 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
4977 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
4978 Ptr != PtrEnd; ++Ptr) {
4979 // Don't add the same builtin candidate twice.
4980 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
4981 continue;
4982
4983 QualType ParamTypes[2] = { *Ptr, *Ptr };
4984 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
4985 CandidateSet);
4986 }
4987 for (BuiltinCandidateTypeSet::iterator
4988 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
4989 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
4990 Enum != EnumEnd; ++Enum) {
4991 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
4992
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00004993 // Don't add the same builtin candidate twice, or if a user defined
4994 // candidate exists.
4995 if (!AddedTypes.insert(CanonType) ||
4996 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
4997 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00004998 continue;
4999
5000 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00005001 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5002 CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005003 }
5004 }
5005 }
5006
5007 // C++ [over.built]p13:
5008 //
5009 // For every cv-qualified or cv-unqualified object type T
5010 // there exist candidate operator functions of the form
5011 //
5012 // T* operator+(T*, ptrdiff_t);
5013 // T& operator[](T*, ptrdiff_t); [BELOW]
5014 // T* operator-(T*, ptrdiff_t);
5015 // T* operator+(ptrdiff_t, T*);
5016 // T& operator[](ptrdiff_t, T*); [BELOW]
5017 //
5018 // C++ [over.built]p14:
5019 //
5020 // For every T, where T is a pointer to object type, there
5021 // exist candidate operator functions of the form
5022 //
5023 // ptrdiff_t operator-(T, T);
5024 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5025 /// Set of (canonical) types that we've already handled.
5026 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5027
5028 for (int Arg = 0; Arg < 2; ++Arg) {
5029 QualType AsymetricParamTypes[2] = {
5030 S.Context.getPointerDiffType(),
5031 S.Context.getPointerDiffType(),
5032 };
5033 for (BuiltinCandidateTypeSet::iterator
5034 Ptr = CandidateTypes[Arg].pointer_begin(),
5035 PtrEnd = CandidateTypes[Arg].pointer_end();
5036 Ptr != PtrEnd; ++Ptr) {
5037 AsymetricParamTypes[Arg] = *Ptr;
5038 if (Arg == 0 || Op == OO_Plus) {
5039 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5040 // T* operator+(ptrdiff_t, T*);
5041 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5042 CandidateSet);
5043 }
5044 if (Op == OO_Minus) {
5045 // ptrdiff_t operator-(T, T);
5046 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5047 continue;
5048
5049 QualType ParamTypes[2] = { *Ptr, *Ptr };
5050 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5051 Args, 2, CandidateSet);
5052 }
5053 }
5054 }
5055 }
5056
5057 // C++ [over.built]p12:
5058 //
5059 // For every pair of promoted arithmetic types L and R, there
5060 // exist candidate operator functions of the form
5061 //
5062 // LR operator*(L, R);
5063 // LR operator/(L, R);
5064 // LR operator+(L, R);
5065 // LR operator-(L, R);
5066 // bool operator<(L, R);
5067 // bool operator>(L, R);
5068 // bool operator<=(L, R);
5069 // bool operator>=(L, R);
5070 // bool operator==(L, R);
5071 // bool operator!=(L, R);
5072 //
5073 // where LR is the result of the usual arithmetic conversions
5074 // between types L and R.
5075 //
5076 // C++ [over.built]p24:
5077 //
5078 // For every pair of promoted arithmetic types L and R, there exist
5079 // candidate operator functions of the form
5080 //
5081 // LR operator?(bool, L, R);
5082 //
5083 // where LR is the result of the usual arithmetic conversions
5084 // between types L and R.
5085 // Our candidates ignore the first parameter.
5086 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005087 if (!HasArithmeticOrEnumeralCandidateType)
5088 return;
5089
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005090 for (unsigned Left = FirstPromotedArithmeticType;
5091 Left < LastPromotedArithmeticType; ++Left) {
5092 for (unsigned Right = FirstPromotedArithmeticType;
5093 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00005094 QualType LandR[2] = { getArithmeticType(Left),
5095 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005096 QualType Result =
5097 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005098 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005099 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5100 }
5101 }
5102
5103 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5104 // conditional operator for vector types.
5105 for (BuiltinCandidateTypeSet::iterator
5106 Vec1 = CandidateTypes[0].vector_begin(),
5107 Vec1End = CandidateTypes[0].vector_end();
5108 Vec1 != Vec1End; ++Vec1) {
5109 for (BuiltinCandidateTypeSet::iterator
5110 Vec2 = CandidateTypes[1].vector_begin(),
5111 Vec2End = CandidateTypes[1].vector_end();
5112 Vec2 != Vec2End; ++Vec2) {
5113 QualType LandR[2] = { *Vec1, *Vec2 };
5114 QualType Result = S.Context.BoolTy;
5115 if (!isComparison) {
5116 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5117 Result = *Vec1;
5118 else
5119 Result = *Vec2;
5120 }
5121
5122 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5123 }
5124 }
5125 }
5126
5127 // C++ [over.built]p17:
5128 //
5129 // For every pair of promoted integral types L and R, there
5130 // exist candidate operator functions of the form
5131 //
5132 // LR operator%(L, R);
5133 // LR operator&(L, R);
5134 // LR operator^(L, R);
5135 // LR operator|(L, R);
5136 // L operator<<(L, R);
5137 // L operator>>(L, R);
5138 //
5139 // where LR is the result of the usual arithmetic conversions
5140 // between types L and R.
5141 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005142 if (!HasArithmeticOrEnumeralCandidateType)
5143 return;
5144
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005145 for (unsigned Left = FirstPromotedIntegralType;
5146 Left < LastPromotedIntegralType; ++Left) {
5147 for (unsigned Right = FirstPromotedIntegralType;
5148 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00005149 QualType LandR[2] = { getArithmeticType(Left),
5150 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005151 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5152 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005153 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005154 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5155 }
5156 }
5157 }
5158
5159 // C++ [over.built]p20:
5160 //
5161 // For every pair (T, VQ), where T is an enumeration or
5162 // pointer to member type and VQ is either volatile or
5163 // empty, there exist candidate operator functions of the form
5164 //
5165 // VQ T& operator=(VQ T&, T);
5166 void addAssignmentMemberPointerOrEnumeralOverloads() {
5167 /// Set of (canonical) types that we've already handled.
5168 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5169
5170 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5171 for (BuiltinCandidateTypeSet::iterator
5172 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5173 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5174 Enum != EnumEnd; ++Enum) {
5175 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5176 continue;
5177
5178 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5179 CandidateSet);
5180 }
5181
5182 for (BuiltinCandidateTypeSet::iterator
5183 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5184 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5185 MemPtr != MemPtrEnd; ++MemPtr) {
5186 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5187 continue;
5188
5189 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5190 CandidateSet);
5191 }
5192 }
5193 }
5194
5195 // C++ [over.built]p19:
5196 //
5197 // For every pair (T, VQ), where T is any type and VQ is either
5198 // volatile or empty, there exist candidate operator functions
5199 // of the form
5200 //
5201 // T*VQ& operator=(T*VQ&, T*);
5202 //
5203 // C++ [over.built]p21:
5204 //
5205 // For every pair (T, VQ), where T is a cv-qualified or
5206 // cv-unqualified object type and VQ is either volatile or
5207 // empty, there exist candidate operator functions of the form
5208 //
5209 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5210 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5211 void addAssignmentPointerOverloads(bool isEqualOp) {
5212 /// Set of (canonical) types that we've already handled.
5213 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5214
5215 for (BuiltinCandidateTypeSet::iterator
5216 Ptr = CandidateTypes[0].pointer_begin(),
5217 PtrEnd = CandidateTypes[0].pointer_end();
5218 Ptr != PtrEnd; ++Ptr) {
5219 // If this is operator=, keep track of the builtin candidates we added.
5220 if (isEqualOp)
5221 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
5222
5223 // non-volatile version
5224 QualType ParamTypes[2] = {
5225 S.Context.getLValueReferenceType(*Ptr),
5226 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
5227 };
5228 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5229 /*IsAssigmentOperator=*/ isEqualOp);
5230
5231 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5232 VisibleTypeConversionsQuals.hasVolatile()) {
5233 // volatile version
5234 ParamTypes[0] =
5235 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5236 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5237 /*IsAssigmentOperator=*/isEqualOp);
5238 }
5239 }
5240
5241 if (isEqualOp) {
5242 for (BuiltinCandidateTypeSet::iterator
5243 Ptr = CandidateTypes[1].pointer_begin(),
5244 PtrEnd = CandidateTypes[1].pointer_end();
5245 Ptr != PtrEnd; ++Ptr) {
5246 // Make sure we don't add the same candidate twice.
5247 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5248 continue;
5249
Chandler Carruth6df868e2010-12-12 08:17:55 +00005250 QualType ParamTypes[2] = {
5251 S.Context.getLValueReferenceType(*Ptr),
5252 *Ptr,
5253 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005254
5255 // non-volatile version
5256 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5257 /*IsAssigmentOperator=*/true);
5258
5259 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5260 VisibleTypeConversionsQuals.hasVolatile()) {
5261 // volatile version
5262 ParamTypes[0] =
5263 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth6df868e2010-12-12 08:17:55 +00005264 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5265 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005266 }
5267 }
5268 }
5269 }
5270
5271 // C++ [over.built]p18:
5272 //
5273 // For every triple (L, VQ, R), where L is an arithmetic type,
5274 // VQ is either volatile or empty, and R is a promoted
5275 // arithmetic type, there exist candidate operator functions of
5276 // the form
5277 //
5278 // VQ L& operator=(VQ L&, R);
5279 // VQ L& operator*=(VQ L&, R);
5280 // VQ L& operator/=(VQ L&, R);
5281 // VQ L& operator+=(VQ L&, R);
5282 // VQ L& operator-=(VQ L&, R);
5283 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005284 if (!HasArithmeticOrEnumeralCandidateType)
5285 return;
5286
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005287 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
5288 for (unsigned Right = FirstPromotedArithmeticType;
5289 Right < LastPromotedArithmeticType; ++Right) {
5290 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00005291 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005292
5293 // Add this built-in operator as a candidate (VQ is empty).
5294 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00005295 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005296 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5297 /*IsAssigmentOperator=*/isEqualOp);
5298
5299 // Add this built-in operator as a candidate (VQ is 'volatile').
5300 if (VisibleTypeConversionsQuals.hasVolatile()) {
5301 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00005302 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005303 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00005304 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5305 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005306 /*IsAssigmentOperator=*/isEqualOp);
5307 }
5308 }
5309 }
5310
5311 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5312 for (BuiltinCandidateTypeSet::iterator
5313 Vec1 = CandidateTypes[0].vector_begin(),
5314 Vec1End = CandidateTypes[0].vector_end();
5315 Vec1 != Vec1End; ++Vec1) {
5316 for (BuiltinCandidateTypeSet::iterator
5317 Vec2 = CandidateTypes[1].vector_begin(),
5318 Vec2End = CandidateTypes[1].vector_end();
5319 Vec2 != Vec2End; ++Vec2) {
5320 QualType ParamTypes[2];
5321 ParamTypes[1] = *Vec2;
5322 // Add this built-in operator as a candidate (VQ is empty).
5323 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
5324 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5325 /*IsAssigmentOperator=*/isEqualOp);
5326
5327 // Add this built-in operator as a candidate (VQ is 'volatile').
5328 if (VisibleTypeConversionsQuals.hasVolatile()) {
5329 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
5330 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00005331 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5332 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005333 /*IsAssigmentOperator=*/isEqualOp);
5334 }
5335 }
5336 }
5337 }
5338
5339 // C++ [over.built]p22:
5340 //
5341 // For every triple (L, VQ, R), where L is an integral type, VQ
5342 // is either volatile or empty, and R is a promoted integral
5343 // type, there exist candidate operator functions of the form
5344 //
5345 // VQ L& operator%=(VQ L&, R);
5346 // VQ L& operator<<=(VQ L&, R);
5347 // VQ L& operator>>=(VQ L&, R);
5348 // VQ L& operator&=(VQ L&, R);
5349 // VQ L& operator^=(VQ L&, R);
5350 // VQ L& operator|=(VQ L&, R);
5351 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00005352 if (!HasArithmeticOrEnumeralCandidateType)
5353 return;
5354
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005355 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
5356 for (unsigned Right = FirstPromotedIntegralType;
5357 Right < LastPromotedIntegralType; ++Right) {
5358 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00005359 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005360
5361 // Add this built-in operator as a candidate (VQ is empty).
5362 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00005363 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005364 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5365 if (VisibleTypeConversionsQuals.hasVolatile()) {
5366 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00005367 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005368 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
5369 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
5370 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5371 CandidateSet);
5372 }
5373 }
5374 }
5375 }
5376
5377 // C++ [over.operator]p23:
5378 //
5379 // There also exist candidate operator functions of the form
5380 //
5381 // bool operator!(bool);
5382 // bool operator&&(bool, bool);
5383 // bool operator||(bool, bool);
5384 void addExclaimOverload() {
5385 QualType ParamTy = S.Context.BoolTy;
5386 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5387 /*IsAssignmentOperator=*/false,
5388 /*NumContextualBoolArguments=*/1);
5389 }
5390 void addAmpAmpOrPipePipeOverload() {
5391 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
5392 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5393 /*IsAssignmentOperator=*/false,
5394 /*NumContextualBoolArguments=*/2);
5395 }
5396
5397 // C++ [over.built]p13:
5398 //
5399 // For every cv-qualified or cv-unqualified object type T there
5400 // exist candidate operator functions of the form
5401 //
5402 // T* operator+(T*, ptrdiff_t); [ABOVE]
5403 // T& operator[](T*, ptrdiff_t);
5404 // T* operator-(T*, ptrdiff_t); [ABOVE]
5405 // T* operator+(ptrdiff_t, T*); [ABOVE]
5406 // T& operator[](ptrdiff_t, T*);
5407 void addSubscriptOverloads() {
5408 for (BuiltinCandidateTypeSet::iterator
5409 Ptr = CandidateTypes[0].pointer_begin(),
5410 PtrEnd = CandidateTypes[0].pointer_end();
5411 Ptr != PtrEnd; ++Ptr) {
5412 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
5413 QualType PointeeType = (*Ptr)->getPointeeType();
5414 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5415
5416 // T& operator[](T*, ptrdiff_t)
5417 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5418 }
5419
5420 for (BuiltinCandidateTypeSet::iterator
5421 Ptr = CandidateTypes[1].pointer_begin(),
5422 PtrEnd = CandidateTypes[1].pointer_end();
5423 Ptr != PtrEnd; ++Ptr) {
5424 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
5425 QualType PointeeType = (*Ptr)->getPointeeType();
5426 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5427
5428 // T& operator[](ptrdiff_t, T*)
5429 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5430 }
5431 }
5432
5433 // C++ [over.built]p11:
5434 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5435 // C1 is the same type as C2 or is a derived class of C2, T is an object
5436 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5437 // there exist candidate operator functions of the form
5438 //
5439 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5440 //
5441 // where CV12 is the union of CV1 and CV2.
5442 void addArrowStarOverloads() {
5443 for (BuiltinCandidateTypeSet::iterator
5444 Ptr = CandidateTypes[0].pointer_begin(),
5445 PtrEnd = CandidateTypes[0].pointer_end();
5446 Ptr != PtrEnd; ++Ptr) {
5447 QualType C1Ty = (*Ptr);
5448 QualType C1;
5449 QualifierCollector Q1;
5450 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5451 if (!isa<RecordType>(C1))
5452 continue;
5453 // heuristic to reduce number of builtin candidates in the set.
5454 // Add volatile/restrict version only if there are conversions to a
5455 // volatile/restrict type.
5456 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5457 continue;
5458 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5459 continue;
5460 for (BuiltinCandidateTypeSet::iterator
5461 MemPtr = CandidateTypes[1].member_pointer_begin(),
5462 MemPtrEnd = CandidateTypes[1].member_pointer_end();
5463 MemPtr != MemPtrEnd; ++MemPtr) {
5464 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5465 QualType C2 = QualType(mptr->getClass(), 0);
5466 C2 = C2.getUnqualifiedType();
5467 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
5468 break;
5469 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5470 // build CV12 T&
5471 QualType T = mptr->getPointeeType();
5472 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5473 T.isVolatileQualified())
5474 continue;
5475 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5476 T.isRestrictQualified())
5477 continue;
5478 T = Q1.apply(S.Context, T);
5479 QualType ResultTy = S.Context.getLValueReferenceType(T);
5480 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5481 }
5482 }
5483 }
5484
5485 // Note that we don't consider the first argument, since it has been
5486 // contextually converted to bool long ago. The candidates below are
5487 // therefore added as binary.
5488 //
5489 // C++ [over.built]p25:
5490 // For every type T, where T is a pointer, pointer-to-member, or scoped
5491 // enumeration type, there exist candidate operator functions of the form
5492 //
5493 // T operator?(bool, T, T);
5494 //
5495 void addConditionalOperatorOverloads() {
5496 /// Set of (canonical) types that we've already handled.
5497 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5498
5499 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5500 for (BuiltinCandidateTypeSet::iterator
5501 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5502 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5503 Ptr != PtrEnd; ++Ptr) {
5504 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5505 continue;
5506
5507 QualType ParamTypes[2] = { *Ptr, *Ptr };
5508 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5509 }
5510
5511 for (BuiltinCandidateTypeSet::iterator
5512 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5513 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5514 MemPtr != MemPtrEnd; ++MemPtr) {
5515 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5516 continue;
5517
5518 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5519 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
5520 }
5521
5522 if (S.getLangOptions().CPlusPlus0x) {
5523 for (BuiltinCandidateTypeSet::iterator
5524 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5525 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5526 Enum != EnumEnd; ++Enum) {
5527 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
5528 continue;
5529
5530 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5531 continue;
5532
5533 QualType ParamTypes[2] = { *Enum, *Enum };
5534 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
5535 }
5536 }
5537 }
5538 }
5539};
5540
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005541} // end anonymous namespace
5542
5543/// AddBuiltinOperatorCandidates - Add the appropriate built-in
5544/// operator overloads to the candidate set (C++ [over.built]), based
5545/// on the operator @p Op and the arguments given. For example, if the
5546/// operator is a binary '+', this routine might add "int
5547/// operator+(int, int)" to cover integer addition.
5548void
5549Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
5550 SourceLocation OpLoc,
5551 Expr **Args, unsigned NumArgs,
5552 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005553 // Find all of the types that the arguments can convert to, but only
5554 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00005555 // that make use of these types. Also record whether we encounter non-record
5556 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005557 Qualifiers VisibleTypeConversionsQuals;
5558 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00005559 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5560 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00005561
5562 bool HasNonRecordCandidateType = false;
5563 bool HasArithmeticOrEnumeralCandidateType = false;
Douglas Gregorfec56e72010-11-03 17:00:07 +00005564 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
5565 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5566 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
5567 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
5568 OpLoc,
5569 true,
5570 (Op == OO_Exclaim ||
5571 Op == OO_AmpAmp ||
5572 Op == OO_PipePipe),
5573 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00005574 HasNonRecordCandidateType = HasNonRecordCandidateType ||
5575 CandidateTypes[ArgIdx].hasNonRecordTypes();
5576 HasArithmeticOrEnumeralCandidateType =
5577 HasArithmeticOrEnumeralCandidateType ||
5578 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00005579 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005580
Chandler Carruth6a577462010-12-13 01:44:01 +00005581 // Exit early when no non-record types have been added to the candidate set
5582 // for any of the arguments to the operator.
5583 if (!HasNonRecordCandidateType)
5584 return;
5585
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005586 // Setup an object to manage the common state for building overloads.
5587 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
5588 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00005589 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005590 CandidateTypes, CandidateSet);
5591
5592 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005593 switch (Op) {
5594 case OO_None:
5595 case NUM_OVERLOADED_OPERATORS:
5596 assert(false && "Expected an overloaded operator");
5597 break;
5598
Chandler Carruthabb71842010-12-12 08:51:33 +00005599 case OO_New:
5600 case OO_Delete:
5601 case OO_Array_New:
5602 case OO_Array_Delete:
5603 case OO_Call:
5604 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
5605 break;
5606
5607 case OO_Comma:
5608 case OO_Arrow:
5609 // C++ [over.match.oper]p3:
5610 // -- For the operator ',', the unary operator '&', or the
5611 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00005612 break;
5613
5614 case OO_Plus: // '+' is either unary or binary
Chandler Carruth32fe0d02010-12-12 08:41:34 +00005615 if (NumArgs == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005616 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00005617 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00005618
5619 case OO_Minus: // '-' is either unary or binary
Chandler Carruthfe622742010-12-12 08:39:38 +00005620 if (NumArgs == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005621 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00005622 } else {
5623 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
5624 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5625 }
Douglas Gregor74253732008-11-19 15:42:04 +00005626 break;
5627
Chandler Carruthabb71842010-12-12 08:51:33 +00005628 case OO_Star: // '*' is either unary or binary
Douglas Gregor74253732008-11-19 15:42:04 +00005629 if (NumArgs == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00005630 OpBuilder.addUnaryStarPointerOverloads();
5631 else
5632 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5633 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005634
Chandler Carruthabb71842010-12-12 08:51:33 +00005635 case OO_Slash:
5636 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00005637 break;
Douglas Gregor74253732008-11-19 15:42:04 +00005638
5639 case OO_PlusPlus:
5640 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005641 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
5642 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00005643 break;
5644
Douglas Gregor19b7b152009-08-24 13:43:27 +00005645 case OO_EqualEqual:
5646 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005647 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00005648 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00005649
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005650 case OO_Less:
5651 case OO_Greater:
5652 case OO_LessEqual:
5653 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00005654 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00005655 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
5656 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005657
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005658 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005659 case OO_Caret:
5660 case OO_Pipe:
5661 case OO_LessLess:
5662 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005663 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005664 break;
5665
Chandler Carruthabb71842010-12-12 08:51:33 +00005666 case OO_Amp: // '&' is either unary or binary
5667 if (NumArgs == 1)
5668 // C++ [over.match.oper]p3:
5669 // -- For the operator ',', the unary operator '&', or the
5670 // operator '->', the built-in candidates set is empty.
5671 break;
5672
5673 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
5674 break;
5675
5676 case OO_Tilde:
5677 OpBuilder.addUnaryTildePromotedIntegralOverloads();
5678 break;
5679
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005680 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005681 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00005682 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005683
5684 case OO_PlusEqual:
5685 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005686 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005687 // Fall through.
5688
5689 case OO_StarEqual:
5690 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005691 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005692 break;
5693
5694 case OO_PercentEqual:
5695 case OO_LessLessEqual:
5696 case OO_GreaterGreaterEqual:
5697 case OO_AmpEqual:
5698 case OO_CaretEqual:
5699 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005700 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005701 break;
5702
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005703 case OO_Exclaim:
5704 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00005705 break;
Douglas Gregor74253732008-11-19 15:42:04 +00005706
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005707 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005708 case OO_PipePipe:
5709 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005710 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005711
5712 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005713 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005714 break;
5715
5716 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005717 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005718 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005719
5720 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005721 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00005722 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5723 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005724 }
5725}
5726
Douglas Gregorfa047642009-02-04 00:32:51 +00005727/// \brief Add function candidates found via argument-dependent lookup
5728/// to the set of overloading candidates.
5729///
5730/// This routine performs argument-dependent name lookup based on the
5731/// given function name (which may also be an operator name) and adds
5732/// all of the overload candidates found by ADL to the overload
5733/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00005734void
Douglas Gregorfa047642009-02-04 00:32:51 +00005735Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00005736 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00005737 Expr **Args, unsigned NumArgs,
John McCalld5532b62009-11-23 01:53:49 +00005738 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005739 OverloadCandidateSet& CandidateSet,
5740 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00005741 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00005742
John McCalla113e722010-01-26 06:04:06 +00005743 // FIXME: This approach for uniquing ADL results (and removing
5744 // redundant candidates from the set) relies on pointer-equality,
5745 // which means we need to key off the canonical decl. However,
5746 // always going back to the canonical decl might not get us the
5747 // right set of default arguments. What default arguments are
5748 // we supposed to consider on ADL candidates, anyway?
5749
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005750 // FIXME: Pass in the explicit template arguments?
John McCall7edb5fd2010-01-26 07:16:45 +00005751 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00005752
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005753 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005754 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5755 CandEnd = CandidateSet.end();
5756 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00005757 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00005758 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00005759 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00005760 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00005761 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005762
5763 // For each of the ADL candidates we found, add it to the overload
5764 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00005765 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00005766 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00005767 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00005768 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005769 continue;
5770
John McCall9aa472c2010-03-19 07:35:19 +00005771 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00005772 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005773 } else
John McCall6e266892010-01-26 03:27:55 +00005774 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00005775 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00005776 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00005777 }
Douglas Gregorfa047642009-02-04 00:32:51 +00005778}
5779
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005780/// isBetterOverloadCandidate - Determines whether the first overload
5781/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00005782bool
John McCall120d63c2010-08-24 20:38:10 +00005783isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00005784 const OverloadCandidate &Cand1,
5785 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005786 SourceLocation Loc,
5787 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005788 // Define viable functions to be better candidates than non-viable
5789 // functions.
5790 if (!Cand2.Viable)
5791 return Cand1.Viable;
5792 else if (!Cand1.Viable)
5793 return false;
5794
Douglas Gregor88a35142008-12-22 05:46:06 +00005795 // C++ [over.match.best]p1:
5796 //
5797 // -- if F is a static member function, ICS1(F) is defined such
5798 // that ICS1(F) is neither better nor worse than ICS1(G) for
5799 // any function G, and, symmetrically, ICS1(G) is neither
5800 // better nor worse than ICS1(F).
5801 unsigned StartArg = 0;
5802 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5803 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005804
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005805 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00005806 // A viable function F1 is defined to be a better function than another
5807 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005808 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005809 unsigned NumArgs = Cand1.Conversions.size();
5810 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5811 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005812 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00005813 switch (CompareImplicitConversionSequences(S,
5814 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005815 Cand2.Conversions[ArgIdx])) {
5816 case ImplicitConversionSequence::Better:
5817 // Cand1 has a better conversion sequence.
5818 HasBetterConversion = true;
5819 break;
5820
5821 case ImplicitConversionSequence::Worse:
5822 // Cand1 can't be better than Cand2.
5823 return false;
5824
5825 case ImplicitConversionSequence::Indistinguishable:
5826 // Do nothing.
5827 break;
5828 }
5829 }
5830
Mike Stump1eb44332009-09-09 15:08:12 +00005831 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005832 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005833 if (HasBetterConversion)
5834 return true;
5835
Mike Stump1eb44332009-09-09 15:08:12 +00005836 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005837 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00005838 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005839 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5840 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005841
5842 // -- F1 and F2 are function template specializations, and the function
5843 // template for F1 is more specialized than the template for F2
5844 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005845 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00005846 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5847 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005848 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00005849 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5850 Cand2.Function->getPrimaryTemplate(),
5851 Loc,
Douglas Gregor5d7d3752009-09-14 23:02:14 +00005852 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5853 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005854 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005855
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005856 // -- the context is an initialization by user-defined conversion
5857 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5858 // from the return type of F1 to the destination type (i.e.,
5859 // the type of the entity being initialized) is a better
5860 // conversion sequence than the standard conversion sequence
5861 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005862 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00005863 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005864 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall120d63c2010-08-24 20:38:10 +00005865 switch (CompareStandardConversionSequences(S,
5866 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005867 Cand2.FinalConversion)) {
5868 case ImplicitConversionSequence::Better:
5869 // Cand1 has a better conversion sequence.
5870 return true;
5871
5872 case ImplicitConversionSequence::Worse:
5873 // Cand1 can't be better than Cand2.
5874 return false;
5875
5876 case ImplicitConversionSequence::Indistinguishable:
5877 // Do nothing
5878 break;
5879 }
5880 }
5881
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005882 return false;
5883}
5884
Mike Stump1eb44332009-09-09 15:08:12 +00005885/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00005886/// within an overload candidate set.
5887///
5888/// \param CandidateSet the set of candidate functions.
5889///
5890/// \param Loc the location of the function name (or operator symbol) for
5891/// which overload resolution occurs.
5892///
Mike Stump1eb44332009-09-09 15:08:12 +00005893/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00005894/// function, Best points to the candidate function found.
5895///
5896/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00005897OverloadingResult
5898OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00005899 iterator &Best,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005900 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005901 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00005902 Best = end();
5903 for (iterator Cand = begin(); Cand != end(); ++Cand) {
5904 if (Cand->Viable)
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005905 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
5906 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005907 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005908 }
5909
5910 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00005911 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005912 return OR_No_Viable_Function;
5913
5914 // Make sure that this function is better than every other viable
5915 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00005916 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00005917 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005918 Cand != Best &&
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005919 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
5920 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00005921 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005922 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005923 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005924 }
Mike Stump1eb44332009-09-09 15:08:12 +00005925
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005926 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005927 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00005928 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005929 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005930 return OR_Deleted;
5931
Douglas Gregore0762c92009-06-19 23:52:42 +00005932 // C++ [basic.def.odr]p2:
5933 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00005934 // when referred to from a potentially-evaluated expression. [Note: this
5935 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00005936 // (clause 13), user-defined conversions (12.3.2), allocation function for
5937 // placement new (5.3.4), as well as non-default initialization (8.5).
5938 if (Best->Function)
John McCall120d63c2010-08-24 20:38:10 +00005939 S.MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor9b623632010-10-12 23:32:35 +00005940
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005941 return OR_Success;
5942}
5943
John McCall3c80f572010-01-12 02:15:36 +00005944namespace {
5945
5946enum OverloadCandidateKind {
5947 oc_function,
5948 oc_method,
5949 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00005950 oc_function_template,
5951 oc_method_template,
5952 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00005953 oc_implicit_default_constructor,
5954 oc_implicit_copy_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00005955 oc_implicit_copy_assignment
John McCall3c80f572010-01-12 02:15:36 +00005956};
5957
John McCall220ccbf2010-01-13 00:25:19 +00005958OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5959 FunctionDecl *Fn,
5960 std::string &Description) {
5961 bool isTemplate = false;
5962
5963 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5964 isTemplate = true;
5965 Description = S.getTemplateArgumentBindingsText(
5966 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5967 }
John McCallb1622a12010-01-06 09:43:14 +00005968
5969 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00005970 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00005971 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00005972
John McCall3c80f572010-01-12 02:15:36 +00005973 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5974 : oc_implicit_default_constructor;
John McCallb1622a12010-01-06 09:43:14 +00005975 }
5976
5977 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5978 // This actually gets spelled 'candidate function' for now, but
5979 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00005980 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00005981 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00005982
Douglas Gregor3e9438b2010-09-27 22:37:28 +00005983 assert(Meth->isCopyAssignmentOperator()
John McCallb1622a12010-01-06 09:43:14 +00005984 && "implicit method is not copy assignment operator?");
John McCall3c80f572010-01-12 02:15:36 +00005985 return oc_implicit_copy_assignment;
5986 }
5987
John McCall220ccbf2010-01-13 00:25:19 +00005988 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00005989}
5990
5991} // end anonymous namespace
5992
5993// Notes the location of an overload candidate.
5994void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCall220ccbf2010-01-13 00:25:19 +00005995 std::string FnDesc;
5996 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5997 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5998 << (unsigned) K << FnDesc;
John McCallb1622a12010-01-06 09:43:14 +00005999}
6000
John McCall1d318332010-01-12 00:44:57 +00006001/// Diagnoses an ambiguous conversion. The partial diagnostic is the
6002/// "lead" diagnostic; it will be given two arguments, the source and
6003/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00006004void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6005 Sema &S,
6006 SourceLocation CaretLoc,
6007 const PartialDiagnostic &PDiag) const {
6008 S.Diag(CaretLoc, PDiag)
6009 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall1d318332010-01-12 00:44:57 +00006010 for (AmbiguousConversionSequence::const_iterator
John McCall120d63c2010-08-24 20:38:10 +00006011 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6012 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00006013 }
John McCall81201622010-01-08 04:41:39 +00006014}
6015
John McCall1d318332010-01-12 00:44:57 +00006016namespace {
6017
John McCalladbb8f82010-01-13 09:16:55 +00006018void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6019 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6020 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00006021 assert(Cand->Function && "for now, candidate must be a function");
6022 FunctionDecl *Fn = Cand->Function;
6023
6024 // There's a conversion slot for the object argument if this is a
6025 // non-constructor method. Note that 'I' corresponds the
6026 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00006027 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00006028 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00006029 if (I == 0)
6030 isObjectArgument = true;
6031 else
6032 I--;
John McCall220ccbf2010-01-13 00:25:19 +00006033 }
6034
John McCall220ccbf2010-01-13 00:25:19 +00006035 std::string FnDesc;
6036 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6037
John McCalladbb8f82010-01-13 09:16:55 +00006038 Expr *FromExpr = Conv.Bad.FromExpr;
6039 QualType FromTy = Conv.Bad.getFromType();
6040 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00006041
John McCall5920dbb2010-02-02 02:42:52 +00006042 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00006043 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00006044 Expr *E = FromExpr->IgnoreParens();
6045 if (isa<UnaryOperator>(E))
6046 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00006047 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00006048
6049 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6050 << (unsigned) FnKind << FnDesc
6051 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6052 << ToTy << Name << I+1;
6053 return;
6054 }
6055
John McCall258b2032010-01-23 08:10:49 +00006056 // Do some hand-waving analysis to see if the non-viability is due
6057 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00006058 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6059 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6060 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6061 CToTy = RT->getPointeeType();
6062 else {
6063 // TODO: detect and diagnose the full richness of const mismatches.
6064 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6065 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6066 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6067 }
6068
6069 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6070 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6071 // It is dumb that we have to do this here.
6072 while (isa<ArrayType>(CFromTy))
6073 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6074 while (isa<ArrayType>(CToTy))
6075 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6076
6077 Qualifiers FromQs = CFromTy.getQualifiers();
6078 Qualifiers ToQs = CToTy.getQualifiers();
6079
6080 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6081 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6082 << (unsigned) FnKind << FnDesc
6083 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6084 << FromTy
6085 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6086 << (unsigned) isObjectArgument << I+1;
6087 return;
6088 }
6089
6090 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6091 assert(CVR && "unexpected qualifiers mismatch");
6092
6093 if (isObjectArgument) {
6094 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6095 << (unsigned) FnKind << FnDesc
6096 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6097 << FromTy << (CVR - 1);
6098 } else {
6099 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6100 << (unsigned) FnKind << FnDesc
6101 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6102 << FromTy << (CVR - 1) << I+1;
6103 }
6104 return;
6105 }
6106
John McCall258b2032010-01-23 08:10:49 +00006107 // Diagnose references or pointers to incomplete types differently,
6108 // since it's far from impossible that the incompleteness triggered
6109 // the failure.
6110 QualType TempFromTy = FromTy.getNonReferenceType();
6111 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6112 TempFromTy = PTy->getPointeeType();
6113 if (TempFromTy->isIncompleteType()) {
6114 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6115 << (unsigned) FnKind << FnDesc
6116 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6117 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
6118 return;
6119 }
6120
Douglas Gregor85789812010-06-30 23:01:39 +00006121 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006122 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00006123 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
6124 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
6125 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6126 FromPtrTy->getPointeeType()) &&
6127 !FromPtrTy->getPointeeType()->isIncompleteType() &&
6128 !ToPtrTy->getPointeeType()->isIncompleteType() &&
6129 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
6130 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006131 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00006132 }
6133 } else if (const ObjCObjectPointerType *FromPtrTy
6134 = FromTy->getAs<ObjCObjectPointerType>()) {
6135 if (const ObjCObjectPointerType *ToPtrTy
6136 = ToTy->getAs<ObjCObjectPointerType>())
6137 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
6138 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
6139 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6140 FromPtrTy->getPointeeType()) &&
6141 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006142 BaseToDerivedConversion = 2;
6143 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
6144 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
6145 !FromTy->isIncompleteType() &&
6146 !ToRefTy->getPointeeType()->isIncompleteType() &&
6147 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
6148 BaseToDerivedConversion = 3;
6149 }
6150
6151 if (BaseToDerivedConversion) {
Douglas Gregor85789812010-06-30 23:01:39 +00006152 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006153 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00006154 << (unsigned) FnKind << FnDesc
6155 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00006156 << (BaseToDerivedConversion - 1)
Douglas Gregor85789812010-06-30 23:01:39 +00006157 << FromTy << ToTy << I+1;
6158 return;
6159 }
6160
John McCall651f3ee2010-01-14 03:28:57 +00006161 // TODO: specialize more based on the kind of mismatch
John McCall220ccbf2010-01-13 00:25:19 +00006162 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
6163 << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00006164 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalle81e15e2010-01-14 00:56:20 +00006165 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCalladbb8f82010-01-13 09:16:55 +00006166}
6167
6168void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
6169 unsigned NumFormalArgs) {
6170 // TODO: treat calls to a missing default constructor as a special case
6171
6172 FunctionDecl *Fn = Cand->Function;
6173 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
6174
6175 unsigned MinParams = Fn->getMinRequiredArguments();
6176
6177 // at least / at most / exactly
Douglas Gregora18592e2010-05-08 18:13:28 +00006178 // FIXME: variadic templates "at most" should account for parameter packs
John McCalladbb8f82010-01-13 09:16:55 +00006179 unsigned mode, modeCount;
6180 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00006181 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
6182 (Cand->FailureKind == ovl_fail_bad_deduction &&
6183 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCalladbb8f82010-01-13 09:16:55 +00006184 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
6185 mode = 0; // "at least"
6186 else
6187 mode = 2; // "exactly"
6188 modeCount = MinParams;
6189 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00006190 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
6191 (Cand->FailureKind == ovl_fail_bad_deduction &&
6192 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00006193 if (MinParams != FnTy->getNumArgs())
6194 mode = 1; // "at most"
6195 else
6196 mode = 2; // "exactly"
6197 modeCount = FnTy->getNumArgs();
6198 }
6199
6200 std::string Description;
6201 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6202
6203 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregora18592e2010-05-08 18:13:28 +00006204 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
6205 << modeCount << NumFormalArgs;
John McCall220ccbf2010-01-13 00:25:19 +00006206}
6207
John McCall342fec42010-02-01 18:53:26 +00006208/// Diagnose a failed template-argument deduction.
6209void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6210 Expr **Args, unsigned NumArgs) {
6211 FunctionDecl *Fn = Cand->Function; // pattern
6212
Douglas Gregora9333192010-05-08 17:41:32 +00006213 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00006214 NamedDecl *ParamD;
6215 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
6216 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
6217 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00006218 switch (Cand->DeductionFailure.Result) {
6219 case Sema::TDK_Success:
6220 llvm_unreachable("TDK_success while diagnosing bad deduction");
6221
6222 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00006223 assert(ParamD && "no parameter found for incomplete deduction result");
6224 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
6225 << ParamD->getDeclName();
6226 return;
6227 }
6228
John McCall57e97782010-08-05 09:05:08 +00006229 case Sema::TDK_Underqualified: {
6230 assert(ParamD && "no parameter found for bad qualifiers deduction result");
6231 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
6232
6233 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
6234
6235 // Param will have been canonicalized, but it should just be a
6236 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00006237 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00006238 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00006239 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00006240 assert(S.Context.hasSameType(Param, NonCanonParam));
6241
6242 // Arg has also been canonicalized, but there's nothing we can do
6243 // about that. It also doesn't matter as much, because it won't
6244 // have any template parameters in it (because deduction isn't
6245 // done on dependent types).
6246 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
6247
6248 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
6249 << ParamD->getDeclName() << Arg << NonCanonParam;
6250 return;
6251 }
6252
6253 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00006254 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00006255 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00006256 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00006257 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00006258 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00006259 which = 1;
6260 else {
Douglas Gregora9333192010-05-08 17:41:32 +00006261 which = 2;
6262 }
6263
6264 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
6265 << which << ParamD->getDeclName()
6266 << *Cand->DeductionFailure.getFirstArg()
6267 << *Cand->DeductionFailure.getSecondArg();
6268 return;
6269 }
Douglas Gregora18592e2010-05-08 18:13:28 +00006270
Douglas Gregorf1a84452010-05-08 19:15:54 +00006271 case Sema::TDK_InvalidExplicitArguments:
6272 assert(ParamD && "no parameter found for invalid explicit arguments");
6273 if (ParamD->getDeclName())
6274 S.Diag(Fn->getLocation(),
6275 diag::note_ovl_candidate_explicit_arg_mismatch_named)
6276 << ParamD->getDeclName();
6277 else {
6278 int index = 0;
6279 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
6280 index = TTP->getIndex();
6281 else if (NonTypeTemplateParmDecl *NTTP
6282 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
6283 index = NTTP->getIndex();
6284 else
6285 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
6286 S.Diag(Fn->getLocation(),
6287 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
6288 << (index + 1);
6289 }
6290 return;
6291
Douglas Gregora18592e2010-05-08 18:13:28 +00006292 case Sema::TDK_TooManyArguments:
6293 case Sema::TDK_TooFewArguments:
6294 DiagnoseArityMismatch(S, Cand, NumArgs);
6295 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00006296
6297 case Sema::TDK_InstantiationDepth:
6298 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
6299 return;
6300
6301 case Sema::TDK_SubstitutionFailure: {
6302 std::string ArgString;
6303 if (TemplateArgumentList *Args
6304 = Cand->DeductionFailure.getTemplateArgumentList())
6305 ArgString = S.getTemplateArgumentBindingsText(
6306 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
6307 *Args);
6308 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
6309 << ArgString;
6310 return;
6311 }
Douglas Gregora9333192010-05-08 17:41:32 +00006312
John McCall342fec42010-02-01 18:53:26 +00006313 // TODO: diagnose these individually, then kill off
6314 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00006315 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00006316 case Sema::TDK_FailedOverloadResolution:
6317 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
6318 return;
6319 }
6320}
6321
6322/// Generates a 'note' diagnostic for an overload candidate. We've
6323/// already generated a primary error at the call site.
6324///
6325/// It really does need to be a single diagnostic with its caret
6326/// pointed at the candidate declaration. Yes, this creates some
6327/// major challenges of technical writing. Yes, this makes pointing
6328/// out problems with specific arguments quite awkward. It's still
6329/// better than generating twenty screens of text for every failed
6330/// overload.
6331///
6332/// It would be great to be able to express per-candidate problems
6333/// more richly for those diagnostic clients that cared, but we'd
6334/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00006335void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
6336 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00006337 FunctionDecl *Fn = Cand->Function;
6338
John McCall81201622010-01-08 04:41:39 +00006339 // Note deleted candidates, but only if they're viable.
John McCall3c80f572010-01-12 02:15:36 +00006340 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCall220ccbf2010-01-13 00:25:19 +00006341 std::string FnDesc;
6342 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00006343
6344 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00006345 << FnKind << FnDesc << Fn->isDeleted();
John McCalla1d7d622010-01-08 00:58:21 +00006346 return;
John McCall81201622010-01-08 04:41:39 +00006347 }
6348
John McCall220ccbf2010-01-13 00:25:19 +00006349 // We don't really have anything else to say about viable candidates.
6350 if (Cand->Viable) {
6351 S.NoteOverloadCandidate(Fn);
6352 return;
6353 }
John McCall1d318332010-01-12 00:44:57 +00006354
John McCalladbb8f82010-01-13 09:16:55 +00006355 switch (Cand->FailureKind) {
6356 case ovl_fail_too_many_arguments:
6357 case ovl_fail_too_few_arguments:
6358 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00006359
John McCalladbb8f82010-01-13 09:16:55 +00006360 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00006361 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
6362
John McCall717e8912010-01-23 05:17:32 +00006363 case ovl_fail_trivial_conversion:
6364 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00006365 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00006366 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00006367
John McCallb1bdc622010-02-25 01:37:24 +00006368 case ovl_fail_bad_conversion: {
6369 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
6370 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00006371 if (Cand->Conversions[I].isBad())
6372 return DiagnoseBadConversion(S, Cand, I);
6373
6374 // FIXME: this currently happens when we're called from SemaInit
6375 // when user-conversion overload fails. Figure out how to handle
6376 // those conditions and diagnose them well.
6377 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00006378 }
John McCallb1bdc622010-02-25 01:37:24 +00006379 }
John McCalla1d7d622010-01-08 00:58:21 +00006380}
6381
6382void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
6383 // Desugar the type of the surrogate down to a function type,
6384 // retaining as many typedefs as possible while still showing
6385 // the function type (and, therefore, its parameter types).
6386 QualType FnType = Cand->Surrogate->getConversionType();
6387 bool isLValueReference = false;
6388 bool isRValueReference = false;
6389 bool isPointer = false;
6390 if (const LValueReferenceType *FnTypeRef =
6391 FnType->getAs<LValueReferenceType>()) {
6392 FnType = FnTypeRef->getPointeeType();
6393 isLValueReference = true;
6394 } else if (const RValueReferenceType *FnTypeRef =
6395 FnType->getAs<RValueReferenceType>()) {
6396 FnType = FnTypeRef->getPointeeType();
6397 isRValueReference = true;
6398 }
6399 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
6400 FnType = FnTypePtr->getPointeeType();
6401 isPointer = true;
6402 }
6403 // Desugar down to a function type.
6404 FnType = QualType(FnType->getAs<FunctionType>(), 0);
6405 // Reconstruct the pointer/reference as appropriate.
6406 if (isPointer) FnType = S.Context.getPointerType(FnType);
6407 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
6408 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
6409
6410 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
6411 << FnType;
6412}
6413
6414void NoteBuiltinOperatorCandidate(Sema &S,
6415 const char *Opc,
6416 SourceLocation OpLoc,
6417 OverloadCandidate *Cand) {
6418 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
6419 std::string TypeStr("operator");
6420 TypeStr += Opc;
6421 TypeStr += "(";
6422 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6423 if (Cand->Conversions.size() == 1) {
6424 TypeStr += ")";
6425 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6426 } else {
6427 TypeStr += ", ";
6428 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6429 TypeStr += ")";
6430 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
6431 }
6432}
6433
6434void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
6435 OverloadCandidate *Cand) {
6436 unsigned NoOperands = Cand->Conversions.size();
6437 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
6438 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00006439 if (ICS.isBad()) break; // all meaningless after first invalid
6440 if (!ICS.isAmbiguous()) continue;
6441
John McCall120d63c2010-08-24 20:38:10 +00006442 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006443 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00006444 }
6445}
6446
John McCall1b77e732010-01-15 23:32:50 +00006447SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
6448 if (Cand->Function)
6449 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00006450 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00006451 return Cand->Surrogate->getLocation();
6452 return SourceLocation();
6453}
6454
John McCallbf65c0b2010-01-12 00:48:53 +00006455struct CompareOverloadCandidatesForDisplay {
6456 Sema &S;
6457 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00006458
6459 bool operator()(const OverloadCandidate *L,
6460 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00006461 // Fast-path this check.
6462 if (L == R) return false;
6463
John McCall81201622010-01-08 04:41:39 +00006464 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00006465 if (L->Viable) {
6466 if (!R->Viable) return true;
6467
6468 // TODO: introduce a tri-valued comparison for overload
6469 // candidates. Would be more worthwhile if we had a sort
6470 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00006471 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6472 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00006473 } else if (R->Viable)
6474 return false;
John McCall81201622010-01-08 04:41:39 +00006475
John McCall1b77e732010-01-15 23:32:50 +00006476 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00006477
John McCall1b77e732010-01-15 23:32:50 +00006478 // Criteria by which we can sort non-viable candidates:
6479 if (!L->Viable) {
6480 // 1. Arity mismatches come after other candidates.
6481 if (L->FailureKind == ovl_fail_too_many_arguments ||
6482 L->FailureKind == ovl_fail_too_few_arguments)
6483 return false;
6484 if (R->FailureKind == ovl_fail_too_many_arguments ||
6485 R->FailureKind == ovl_fail_too_few_arguments)
6486 return true;
John McCall81201622010-01-08 04:41:39 +00006487
John McCall717e8912010-01-23 05:17:32 +00006488 // 2. Bad conversions come first and are ordered by the number
6489 // of bad conversions and quality of good conversions.
6490 if (L->FailureKind == ovl_fail_bad_conversion) {
6491 if (R->FailureKind != ovl_fail_bad_conversion)
6492 return true;
6493
6494 // If there's any ordering between the defined conversions...
6495 // FIXME: this might not be transitive.
6496 assert(L->Conversions.size() == R->Conversions.size());
6497
6498 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00006499 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6500 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00006501 switch (CompareImplicitConversionSequences(S,
6502 L->Conversions[I],
6503 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00006504 case ImplicitConversionSequence::Better:
6505 leftBetter++;
6506 break;
6507
6508 case ImplicitConversionSequence::Worse:
6509 leftBetter--;
6510 break;
6511
6512 case ImplicitConversionSequence::Indistinguishable:
6513 break;
6514 }
6515 }
6516 if (leftBetter > 0) return true;
6517 if (leftBetter < 0) return false;
6518
6519 } else if (R->FailureKind == ovl_fail_bad_conversion)
6520 return false;
6521
John McCall1b77e732010-01-15 23:32:50 +00006522 // TODO: others?
6523 }
6524
6525 // Sort everything else by location.
6526 SourceLocation LLoc = GetLocationForCandidate(L);
6527 SourceLocation RLoc = GetLocationForCandidate(R);
6528
6529 // Put candidates without locations (e.g. builtins) at the end.
6530 if (LLoc.isInvalid()) return false;
6531 if (RLoc.isInvalid()) return true;
6532
6533 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00006534 }
6535};
6536
John McCall717e8912010-01-23 05:17:32 +00006537/// CompleteNonViableCandidate - Normally, overload resolution only
6538/// computes up to the first
6539void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6540 Expr **Args, unsigned NumArgs) {
6541 assert(!Cand->Viable);
6542
6543 // Don't do anything on failures other than bad conversion.
6544 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6545
6546 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00006547 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCall717e8912010-01-23 05:17:32 +00006548 unsigned ConvCount = Cand->Conversions.size();
6549 while (true) {
6550 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6551 ConvIdx++;
6552 if (Cand->Conversions[ConvIdx - 1].isBad())
6553 break;
6554 }
6555
6556 if (ConvIdx == ConvCount)
6557 return;
6558
John McCallb1bdc622010-02-25 01:37:24 +00006559 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6560 "remaining conversion is initialized?");
6561
Douglas Gregor23ef6c02010-04-16 17:45:54 +00006562 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00006563 // operation somehow.
6564 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00006565
6566 const FunctionProtoType* Proto;
6567 unsigned ArgIdx = ConvIdx;
6568
6569 if (Cand->IsSurrogate) {
6570 QualType ConvType
6571 = Cand->Surrogate->getConversionType().getNonReferenceType();
6572 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6573 ConvType = ConvPtrType->getPointeeType();
6574 Proto = ConvType->getAs<FunctionProtoType>();
6575 ArgIdx--;
6576 } else if (Cand->Function) {
6577 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6578 if (isa<CXXMethodDecl>(Cand->Function) &&
6579 !isa<CXXConstructorDecl>(Cand->Function))
6580 ArgIdx--;
6581 } else {
6582 // Builtin binary operator with a bad first conversion.
6583 assert(ConvCount <= 3);
6584 for (; ConvIdx != ConvCount; ++ConvIdx)
6585 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006586 = TryCopyInitialization(S, Args[ConvIdx],
6587 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6588 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00006589 /*InOverloadResolution*/ true);
John McCall717e8912010-01-23 05:17:32 +00006590 return;
6591 }
6592
6593 // Fill in the rest of the conversions.
6594 unsigned NumArgsInProto = Proto->getNumArgs();
6595 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6596 if (ArgIdx < NumArgsInProto)
6597 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006598 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6599 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00006600 /*InOverloadResolution=*/true);
John McCall717e8912010-01-23 05:17:32 +00006601 else
6602 Cand->Conversions[ConvIdx].setEllipsis();
6603 }
6604}
6605
John McCalla1d7d622010-01-08 00:58:21 +00006606} // end anonymous namespace
6607
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006608/// PrintOverloadCandidates - When overload resolution fails, prints
6609/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00006610/// set.
John McCall120d63c2010-08-24 20:38:10 +00006611void OverloadCandidateSet::NoteCandidates(Sema &S,
6612 OverloadCandidateDisplayKind OCD,
6613 Expr **Args, unsigned NumArgs,
6614 const char *Opc,
6615 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00006616 // Sort the candidates by viability and position. Sorting directly would
6617 // be prohibitive, so we make a set of pointers and sort those.
6618 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00006619 if (OCD == OCD_AllCandidates) Cands.reserve(size());
6620 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00006621 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00006622 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00006623 else if (OCD == OCD_AllCandidates) {
John McCall120d63c2010-08-24 20:38:10 +00006624 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006625 if (Cand->Function || Cand->IsSurrogate)
6626 Cands.push_back(Cand);
6627 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6628 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00006629 }
6630 }
6631
John McCallbf65c0b2010-01-12 00:48:53 +00006632 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00006633 CompareOverloadCandidatesForDisplay(S));
John McCall81201622010-01-08 04:41:39 +00006634
John McCall1d318332010-01-12 00:44:57 +00006635 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00006636
John McCall81201622010-01-08 04:41:39 +00006637 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall120d63c2010-08-24 20:38:10 +00006638 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006639 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00006640 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6641 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00006642
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006643 // Set an arbitrary limit on the number of candidate functions we'll spam
6644 // the user with. FIXME: This limit should depend on details of the
6645 // candidate list.
6646 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6647 break;
6648 }
6649 ++CandsShown;
6650
John McCalla1d7d622010-01-08 00:58:21 +00006651 if (Cand->Function)
John McCall120d63c2010-08-24 20:38:10 +00006652 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00006653 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00006654 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006655 else {
6656 assert(Cand->Viable &&
6657 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00006658 // Generally we only see ambiguities including viable builtin
6659 // operators if overload resolution got screwed up by an
6660 // ambiguous user-defined conversion.
6661 //
6662 // FIXME: It's quite possible for different conversions to see
6663 // different ambiguities, though.
6664 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00006665 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00006666 ReportedAmbiguousConversions = true;
6667 }
John McCalla1d7d622010-01-08 00:58:21 +00006668
John McCall1d318332010-01-12 00:44:57 +00006669 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00006670 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006671 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006672 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006673
6674 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00006675 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006676}
6677
John McCall9aa472c2010-03-19 07:35:19 +00006678static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCallc373d482010-01-27 01:50:18 +00006679 if (isa<UnresolvedLookupExpr>(E))
John McCall9aa472c2010-03-19 07:35:19 +00006680 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00006681
John McCall9aa472c2010-03-19 07:35:19 +00006682 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00006683}
6684
Douglas Gregor904eed32008-11-10 20:40:00 +00006685/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6686/// an overloaded function (C++ [over.over]), where @p From is an
6687/// expression with overloaded function type and @p ToType is the type
6688/// we're trying to resolve to. For example:
6689///
6690/// @code
6691/// int f(double);
6692/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00006693///
Douglas Gregor904eed32008-11-10 20:40:00 +00006694/// int (*pfd)(double) = f; // selects f(double)
6695/// @endcode
6696///
6697/// This routine returns the resulting FunctionDecl if it could be
6698/// resolved, and NULL otherwise. When @p Complain is true, this
6699/// routine will emit diagnostics if there is an error.
6700FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00006701Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall6bb80172010-03-30 21:47:33 +00006702 bool Complain,
6703 DeclAccessPair &FoundResult) {
Douglas Gregor904eed32008-11-10 20:40:00 +00006704 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00006705 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00006706 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00006707 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00006708 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00006709 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00006710 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00006711 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00006712 FunctionType = MemTypePtr->getPointeeType();
6713 IsMember = true;
6714 }
Douglas Gregor904eed32008-11-10 20:40:00 +00006715
Douglas Gregor904eed32008-11-10 20:40:00 +00006716 // C++ [over.over]p1:
6717 // [...] [Note: any redundant set of parentheses surrounding the
6718 // overloaded function name is ignored (5.1). ]
Douglas Gregor904eed32008-11-10 20:40:00 +00006719 // C++ [over.over]p1:
6720 // [...] The overloaded function name can be preceded by the &
6721 // operator.
John McCallc988fab2010-08-24 23:26:21 +00006722 // However, remember whether the expression has member-pointer form:
6723 // C++ [expr.unary.op]p4:
6724 // A pointer to member is only formed when an explicit & is used
6725 // and its operand is a qualified-id not enclosed in
6726 // parentheses.
John McCall9c72c602010-08-27 09:08:28 +00006727 OverloadExpr::FindResult Ovl = OverloadExpr::find(From);
6728 OverloadExpr *OvlExpr = Ovl.Expression;
John McCallc988fab2010-08-24 23:26:21 +00006729
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006730 // We expect a pointer or reference to function, or a function pointer.
6731 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6732 if (!FunctionType->isFunctionType()) {
6733 if (Complain)
6734 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6735 << OvlExpr->getName() << ToType;
6736
6737 return 0;
6738 }
6739
John McCallfb97e752010-08-24 22:52:39 +00006740 // If the overload expression doesn't have the form of a pointer to
John McCallc988fab2010-08-24 23:26:21 +00006741 // member, don't try to convert it to a pointer-to-member type.
John McCall9c72c602010-08-27 09:08:28 +00006742 if (IsMember && !Ovl.HasFormOfMemberPointer) {
John McCallfb97e752010-08-24 22:52:39 +00006743 if (!Complain) return 0;
6744
6745 // TODO: Should we condition this on whether any functions might
6746 // have matched, or is it more appropriate to do that in callers?
6747 // TODO: a fixit wouldn't hurt.
6748 Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
6749 << ToType << OvlExpr->getSourceRange();
6750 return 0;
6751 }
6752
6753 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6754 if (OvlExpr->hasExplicitTemplateArgs()) {
6755 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6756 ExplicitTemplateArgs = &ETABuffer;
6757 }
6758
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006759 assert(From->getType() == Context.OverloadTy);
Douglas Gregor904eed32008-11-10 20:40:00 +00006760
Douglas Gregor904eed32008-11-10 20:40:00 +00006761 // Look through all of the overloaded functions, searching for one
6762 // whose type matches exactly.
John McCall9aa472c2010-03-19 07:35:19 +00006763 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb7a09262010-04-01 18:32:35 +00006764 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
Douglas Gregor9b623632010-10-12 23:32:35 +00006765
Douglas Gregor00aeb522009-07-08 23:33:52 +00006766 bool FoundNonTemplateFunction = false;
John McCall7bb12da2010-02-02 06:20:04 +00006767 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6768 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00006769 // Look through any using declarations to find the underlying function.
6770 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6771
Douglas Gregor904eed32008-11-10 20:40:00 +00006772 // C++ [over.over]p3:
6773 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00006774 // targets of type "pointer-to-function" or "reference-to-function."
6775 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00006776 // type "pointer-to-member-function."
6777 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00006778
Mike Stump1eb44332009-09-09 15:08:12 +00006779 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthbd647292009-12-29 06:17:27 +00006780 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006781 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00006782 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00006783 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00006784 // static when converting to member pointer.
6785 if (Method->isStatic() == IsMember)
6786 continue;
6787 } else if (IsMember)
6788 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00006789
Douglas Gregor00aeb522009-07-08 23:33:52 +00006790 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00006791 // If the name is a function template, template argument deduction is
6792 // done (14.8.2.2), and if the argument deduction succeeds, the
6793 // resulting template argument list is used to generate a single
6794 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00006795 // overloaded functions considered.
Douglas Gregor83314aa2009-07-08 20:55:45 +00006796 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00006797 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor83314aa2009-07-08 20:55:45 +00006798 if (TemplateDeductionResult Result
John McCall7bb12da2010-02-02 06:20:04 +00006799 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00006800 FunctionType, Specialization, Info)) {
6801 // FIXME: make a note of the failed deduction for diagnostics.
6802 (void)Result;
6803 } else {
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00006804 // Template argument deduction ensures that we have an exact match.
6805 // This function template specicalization works.
Douglas Gregor9b623632010-10-12 23:32:35 +00006806 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006807 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00006808 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor9b623632010-10-12 23:32:35 +00006809 Matches.push_back(std::make_pair(I.getPair(), Specialization));
Douglas Gregor83314aa2009-07-08 20:55:45 +00006810 }
John McCallba135432009-11-21 08:51:07 +00006811
6812 continue;
Douglas Gregor83314aa2009-07-08 20:55:45 +00006813 }
Mike Stump1eb44332009-09-09 15:08:12 +00006814
Chandler Carruthbd647292009-12-29 06:17:27 +00006815 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00006816 // Skip non-static functions when converting to pointer, and static
6817 // when converting to member pointer.
6818 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00006819 continue;
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006820
6821 // If we have explicit template arguments, skip non-templates.
John McCall7bb12da2010-02-02 06:20:04 +00006822 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006823 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00006824 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00006825 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00006826
Chandler Carruthbd647292009-12-29 06:17:27 +00006827 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00006828 QualType ResultTy;
6829 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6830 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6831 ResultTy)) {
John McCall9aa472c2010-03-19 07:35:19 +00006832 Matches.push_back(std::make_pair(I.getPair(),
6833 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00006834 FoundNonTemplateFunction = true;
6835 }
Mike Stump1eb44332009-09-09 15:08:12 +00006836 }
Douglas Gregor904eed32008-11-10 20:40:00 +00006837 }
6838
Douglas Gregor00aeb522009-07-08 23:33:52 +00006839 // If there were 0 or 1 matches, we're done.
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006840 if (Matches.empty()) {
6841 if (Complain) {
6842 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6843 << OvlExpr->getName() << FunctionType;
6844 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6845 E = OvlExpr->decls_end();
6846 I != E; ++I)
6847 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6848 NoteOverloadCandidate(F);
6849 }
6850
Douglas Gregor00aeb522009-07-08 23:33:52 +00006851 return 0;
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006852 } else if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00006853 FunctionDecl *Result = Matches[0].second;
Douglas Gregor9b623632010-10-12 23:32:35 +00006854 FoundResult = Matches[0].first;
Sebastian Redl07ab2022009-10-17 21:12:09 +00006855 MarkDeclarationReferenced(From->getLocStart(), Result);
Douglas Gregor9b623632010-10-12 23:32:35 +00006856 if (Complain) {
John McCall6bb80172010-03-30 21:47:33 +00006857 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Douglas Gregor9b623632010-10-12 23:32:35 +00006858 }
Sebastian Redl07ab2022009-10-17 21:12:09 +00006859 return Result;
6860 }
Douglas Gregor00aeb522009-07-08 23:33:52 +00006861
6862 // C++ [over.over]p4:
6863 // If more than one function is selected, [...]
Douglas Gregor312a2022009-09-26 03:56:17 +00006864 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006865 // [...] and any given function template specialization F1 is
6866 // eliminated if the set contains a second function template
6867 // specialization whose function template is more specialized
6868 // than the function template of F1 according to the partial
6869 // ordering rules of 14.5.5.2.
6870
6871 // The algorithm specified above is quadratic. We instead use a
6872 // two-pass algorithm (similar to the one used to identify the
6873 // best viable function in an overload set) that identifies the
6874 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00006875
6876 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6877 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6878 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCallc373d482010-01-27 01:50:18 +00006879
6880 UnresolvedSetIterator Result =
John McCall9aa472c2010-03-19 07:35:19 +00006881 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redl07ab2022009-10-17 21:12:09 +00006882 TPOC_Other, From->getLocStart(),
6883 PDiag(),
6884 PDiag(diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00006885 << Matches[0].second->getDeclName(),
John McCall220ccbf2010-01-13 00:25:19 +00006886 PDiag(diag::note_ovl_candidate)
6887 << (unsigned) oc_function_template);
Douglas Gregor78c057e2010-09-12 08:16:09 +00006888 if (Result == MatchesCopy.end())
6889 return 0;
6890
John McCallc373d482010-01-27 01:50:18 +00006891 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall6bb80172010-03-30 21:47:33 +00006892 FoundResult = Matches[Result - MatchesCopy.begin()].first;
Douglas Gregor9b623632010-10-12 23:32:35 +00006893 if (Complain)
John McCall6bb80172010-03-30 21:47:33 +00006894 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCallc373d482010-01-27 01:50:18 +00006895 return cast<FunctionDecl>(*Result);
Douglas Gregor00aeb522009-07-08 23:33:52 +00006896 }
Mike Stump1eb44332009-09-09 15:08:12 +00006897
Douglas Gregor312a2022009-09-26 03:56:17 +00006898 // [...] any function template specializations in the set are
6899 // eliminated if the set also contains a non-template function, [...]
John McCallc373d482010-01-27 01:50:18 +00006900 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCall9aa472c2010-03-19 07:35:19 +00006901 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCallc373d482010-01-27 01:50:18 +00006902 ++I;
6903 else {
John McCall9aa472c2010-03-19 07:35:19 +00006904 Matches[I] = Matches[--N];
6905 Matches.set_size(N);
John McCallc373d482010-01-27 01:50:18 +00006906 }
6907 }
Douglas Gregor312a2022009-09-26 03:56:17 +00006908
Mike Stump1eb44332009-09-09 15:08:12 +00006909 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00006910 // selected function.
John McCallc373d482010-01-27 01:50:18 +00006911 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00006912 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall6bb80172010-03-30 21:47:33 +00006913 FoundResult = Matches[0].first;
Douglas Gregor9b623632010-10-12 23:32:35 +00006914 if (Complain)
John McCall9aa472c2010-03-19 07:35:19 +00006915 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
6916 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redl07ab2022009-10-17 21:12:09 +00006917 }
Mike Stump1eb44332009-09-09 15:08:12 +00006918
Douglas Gregor00aeb522009-07-08 23:33:52 +00006919 // FIXME: We should probably return the same thing that BestViableFunction
6920 // returns (even if we issue the diagnostics here).
Douglas Gregor8e960432010-11-08 03:40:48 +00006921 if (Complain) {
6922 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
6923 << Matches[0].second->getDeclName();
6924 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6925 NoteOverloadCandidate(Matches[I].second);
6926 }
6927
Douglas Gregor904eed32008-11-10 20:40:00 +00006928 return 0;
6929}
6930
Douglas Gregor4b52e252009-12-21 23:17:24 +00006931/// \brief Given an expression that refers to an overloaded function, try to
6932/// resolve that overloaded function expression down to a single function.
6933///
6934/// This routine can only resolve template-ids that refer to a single function
6935/// template, where that template-id refers to a single template whose template
6936/// arguments are either provided by the template-id or have defaults,
6937/// as described in C++0x [temp.arg.explicit]p3.
6938FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6939 // C++ [over.over]p1:
6940 // [...] [Note: any redundant set of parentheses surrounding the
6941 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00006942 // C++ [over.over]p1:
6943 // [...] The overloaded function name can be preceded by the &
6944 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00006945
6946 if (From->getType() != Context.OverloadTy)
6947 return 0;
6948
John McCall9c72c602010-08-27 09:08:28 +00006949 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
Douglas Gregor4b52e252009-12-21 23:17:24 +00006950
6951 // If we didn't actually find any template-ids, we're done.
John McCall7bb12da2010-02-02 06:20:04 +00006952 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00006953 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00006954
6955 TemplateArgumentListInfo ExplicitTemplateArgs;
6956 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor4b52e252009-12-21 23:17:24 +00006957
6958 // Look through all of the overloaded functions, searching for one
6959 // whose type matches exactly.
6960 FunctionDecl *Matched = 0;
John McCall7bb12da2010-02-02 06:20:04 +00006961 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6962 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00006963 // C++0x [temp.arg.explicit]p3:
6964 // [...] In contexts where deduction is done and fails, or in contexts
6965 // where deduction is not done, if a template argument list is
6966 // specified and it, along with any default template arguments,
6967 // identifies a single function template specialization, then the
6968 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00006969 FunctionTemplateDecl *FunctionTemplate
6970 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor4b52e252009-12-21 23:17:24 +00006971
6972 // C++ [over.over]p2:
6973 // If the name is a function template, template argument deduction is
6974 // done (14.8.2.2), and if the argument deduction succeeds, the
6975 // resulting template argument list is used to generate a single
6976 // function template specialization, which is added to the set of
6977 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00006978 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00006979 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00006980 if (TemplateDeductionResult Result
6981 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6982 Specialization, Info)) {
6983 // FIXME: make a note of the failed deduction for diagnostics.
6984 (void)Result;
6985 continue;
6986 }
6987
6988 // Multiple matches; we can't resolve to a single declaration.
6989 if (Matched)
6990 return 0;
6991
6992 Matched = Specialization;
6993 }
Douglas Gregor9b623632010-10-12 23:32:35 +00006994
Douglas Gregor4b52e252009-12-21 23:17:24 +00006995 return Matched;
6996}
6997
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006998/// \brief Add a single candidate to the overload set.
6999static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00007000 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00007001 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007002 Expr **Args, unsigned NumArgs,
7003 OverloadCandidateSet &CandidateSet,
7004 bool PartialOverloading) {
John McCall9aa472c2010-03-19 07:35:19 +00007005 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00007006 if (isa<UsingShadowDecl>(Callee))
7007 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
7008
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007009 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00007010 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCall9aa472c2010-03-19 07:35:19 +00007011 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00007012 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007013 return;
John McCallba135432009-11-21 08:51:07 +00007014 }
7015
7016 if (FunctionTemplateDecl *FuncTemplate
7017 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00007018 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
7019 ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00007020 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00007021 return;
7022 }
7023
7024 assert(false && "unhandled case in overloaded call candidate");
7025
7026 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007027}
7028
7029/// \brief Add the overload candidates named by callee and/or found by argument
7030/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00007031void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007032 Expr **Args, unsigned NumArgs,
7033 OverloadCandidateSet &CandidateSet,
7034 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00007035
7036#ifndef NDEBUG
7037 // Verify that ArgumentDependentLookup is consistent with the rules
7038 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007039 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007040 // Let X be the lookup set produced by unqualified lookup (3.4.1)
7041 // and let Y be the lookup set produced by argument dependent
7042 // lookup (defined as follows). If X contains
7043 //
7044 // -- a declaration of a class member, or
7045 //
7046 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00007047 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007048 //
7049 // -- a declaration that is neither a function or a function
7050 // template
7051 //
7052 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00007053
John McCall3b4294e2009-12-16 12:17:52 +00007054 if (ULE->requiresADL()) {
7055 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7056 E = ULE->decls_end(); I != E; ++I) {
7057 assert(!(*I)->getDeclContext()->isRecord());
7058 assert(isa<UsingShadowDecl>(*I) ||
7059 !(*I)->getDeclContext()->isFunctionOrMethod());
7060 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00007061 }
7062 }
7063#endif
7064
John McCall3b4294e2009-12-16 12:17:52 +00007065 // It would be nice to avoid this copy.
7066 TemplateArgumentListInfo TABuffer;
7067 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7068 if (ULE->hasExplicitTemplateArgs()) {
7069 ULE->copyTemplateArgumentsInto(TABuffer);
7070 ExplicitTemplateArgs = &TABuffer;
7071 }
7072
7073 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7074 E = ULE->decls_end(); I != E; ++I)
John McCall9aa472c2010-03-19 07:35:19 +00007075 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00007076 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007077 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00007078
John McCall3b4294e2009-12-16 12:17:52 +00007079 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00007080 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
7081 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007082 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00007083 CandidateSet,
7084 PartialOverloading);
7085}
John McCall578b69b2009-12-16 08:11:27 +00007086
7087/// Attempts to recover from a call where no functions were found.
7088///
7089/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00007090static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00007091BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00007092 UnresolvedLookupExpr *ULE,
7093 SourceLocation LParenLoc,
7094 Expr **Args, unsigned NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00007095 SourceLocation RParenLoc) {
John McCall578b69b2009-12-16 08:11:27 +00007096
7097 CXXScopeSpec SS;
7098 if (ULE->getQualifier()) {
7099 SS.setScopeRep(ULE->getQualifier());
7100 SS.setRange(ULE->getQualifierRange());
7101 }
7102
John McCall3b4294e2009-12-16 12:17:52 +00007103 TemplateArgumentListInfo TABuffer;
7104 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7105 if (ULE->hasExplicitTemplateArgs()) {
7106 ULE->copyTemplateArgumentsInto(TABuffer);
7107 ExplicitTemplateArgs = &TABuffer;
7108 }
7109
John McCall578b69b2009-12-16 08:11:27 +00007110 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
7111 Sema::LookupOrdinaryName);
Douglas Gregor91f7ac72010-05-18 16:14:23 +00007112 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCallf312b1e2010-08-26 23:41:50 +00007113 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00007114
John McCall3b4294e2009-12-16 12:17:52 +00007115 assert(!R.empty() && "lookup results empty despite recovery");
7116
7117 // Build an implicit member call if appropriate. Just drop the
7118 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00007119 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00007120 if ((*R.begin())->isCXXClassMember())
Chandler Carruth6df868e2010-12-12 08:17:55 +00007121 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
7122 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00007123 else if (ExplicitTemplateArgs)
7124 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
7125 else
7126 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
7127
7128 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00007129 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00007130
7131 // This shouldn't cause an infinite loop because we're giving it
7132 // an expression with non-empty lookup results, which should never
7133 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00007134 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +00007135 MultiExprArg(Args, NumArgs), RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00007136}
Douglas Gregord7a95972010-06-08 17:35:15 +00007137
Douglas Gregorf6b89692008-11-26 05:54:23 +00007138/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00007139/// (which eventually refers to the declaration Func) and the call
7140/// arguments Args/NumArgs, attempt to resolve the function call down
7141/// to a specific function. If overload resolution succeeds, returns
7142/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00007143/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00007144/// arguments and Fn, and returns NULL.
John McCall60d7b3a2010-08-24 06:29:42 +00007145ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00007146Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00007147 SourceLocation LParenLoc,
7148 Expr **Args, unsigned NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00007149 SourceLocation RParenLoc) {
7150#ifndef NDEBUG
7151 if (ULE->requiresADL()) {
7152 // To do ADL, we must have found an unqualified name.
7153 assert(!ULE->getQualifier() && "qualified name with ADL");
7154
7155 // We don't perform ADL for implicit declarations of builtins.
7156 // Verify that this was correctly set up.
7157 FunctionDecl *F;
7158 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
7159 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
7160 F->getBuiltinID() && F->isImplicit())
7161 assert(0 && "performing ADL for builtin");
7162
7163 // We don't perform ADL in C.
7164 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
7165 }
7166#endif
7167
John McCall5769d612010-02-08 23:07:23 +00007168 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00007169
John McCall3b4294e2009-12-16 12:17:52 +00007170 // Add the functions denoted by the callee to the set of candidate
7171 // functions, including those from argument-dependent lookup.
7172 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00007173
7174 // If we found nothing, try to recover.
7175 // AddRecoveryCallCandidates diagnoses the error itself, so we just
7176 // bailout out if it fails.
John McCall3b4294e2009-12-16 12:17:52 +00007177 if (CandidateSet.empty())
Douglas Gregor1aae80b2010-04-14 20:27:54 +00007178 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00007179 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00007180
Douglas Gregorf6b89692008-11-26 05:54:23 +00007181 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007182 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00007183 case OR_Success: {
7184 FunctionDecl *FDecl = Best->Function;
John McCall9aa472c2010-03-19 07:35:19 +00007185 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007186 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
7187 ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00007188 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Chandler Carruth6df868e2010-12-12 08:17:55 +00007189 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
7190 RParenLoc);
John McCall3b4294e2009-12-16 12:17:52 +00007191 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00007192
7193 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00007194 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00007195 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00007196 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007197 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00007198 break;
7199
7200 case OR_Ambiguous:
7201 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00007202 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007203 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00007204 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007205
7206 case OR_Deleted:
7207 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
7208 << Best->Function->isDeleted()
John McCall3b4294e2009-12-16 12:17:52 +00007209 << ULE->getName()
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007210 << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007211 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007212 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00007213 }
7214
Douglas Gregorff331c12010-07-25 18:17:45 +00007215 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00007216 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00007217}
7218
John McCall6e266892010-01-26 03:27:55 +00007219static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00007220 return Functions.size() > 1 ||
7221 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
7222}
7223
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007224/// \brief Create a unary operation that may resolve to an overloaded
7225/// operator.
7226///
7227/// \param OpLoc The location of the operator itself (e.g., '*').
7228///
7229/// \param OpcIn The UnaryOperator::Opcode that describes this
7230/// operator.
7231///
7232/// \param Functions The set of non-member functions that will be
7233/// considered by overload resolution. The caller needs to build this
7234/// set based on the context using, e.g.,
7235/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7236/// set should not contain any member functions; those will be added
7237/// by CreateOverloadedUnaryOp().
7238///
7239/// \param input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +00007240ExprResult
John McCall6e266892010-01-26 03:27:55 +00007241Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
7242 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +00007243 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007244 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007245
7246 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
7247 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
7248 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00007249 // TODO: provide better source location info.
7250 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007251
John McCall0e800c92010-12-04 08:14:53 +00007252 if (Input->getObjectKind() == OK_ObjCProperty)
7253 ConvertPropertyForRValue(Input);
7254
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007255 Expr *Args[2] = { Input, 0 };
7256 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00007257
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007258 // For post-increment and post-decrement, add the implicit '0' as
7259 // the second argument, so that we know this is a post-increment or
7260 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +00007261 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007262 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007263 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
7264 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007265 NumArgs = 2;
7266 }
7267
7268 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00007269 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +00007270 return Owned(new (Context) UnaryOperator(Input,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00007271 Opc,
7272 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00007273 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00007274 OpLoc));
7275
John McCallc373d482010-01-27 01:50:18 +00007276 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00007277 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00007278 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00007279 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00007280 /*ADL*/ true, IsOverloaded(Fns),
7281 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007282 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
7283 &Args[0], NumArgs,
7284 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00007285 VK_RValue,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007286 OpLoc));
7287 }
7288
7289 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00007290 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007291
7292 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00007293 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007294
7295 // Add operator candidates that are member functions.
7296 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
7297
John McCall6e266892010-01-26 03:27:55 +00007298 // Add candidates from ADL.
7299 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregordc81c882010-02-05 05:15:43 +00007300 Args, NumArgs,
John McCall6e266892010-01-26 03:27:55 +00007301 /*ExplicitTemplateArgs*/ 0,
7302 CandidateSet);
7303
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007304 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00007305 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007306
7307 // Perform overload resolution.
7308 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007309 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007310 case OR_Success: {
7311 // We found a built-in operator or an overloaded operator.
7312 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00007313
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007314 if (FnDecl) {
7315 // We matched an overloaded operator. Build a call to that
7316 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00007317
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007318 // Convert the arguments.
7319 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00007320 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00007321
John McCall6bb80172010-03-30 21:47:33 +00007322 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
7323 Best->FoundDecl, Method))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007324 return ExprError();
7325 } else {
7326 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00007327 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +00007328 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007329 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +00007330 FnDecl->getParamDecl(0)),
Douglas Gregore1a5c172009-12-23 17:40:29 +00007331 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +00007332 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +00007333 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007334 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00007335 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007336 }
7337
John McCallb697e082010-05-06 18:15:07 +00007338 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7339
John McCallf89e55a2010-11-18 06:31:45 +00007340 // Determine the result type.
7341 QualType ResultTy = FnDecl->getResultType();
7342 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7343 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00007344
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007345 // Build the actual expression node.
John McCallf89e55a2010-11-18 06:31:45 +00007346 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00007347
Eli Friedman4c3b8962009-11-18 03:58:17 +00007348 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +00007349 CallExpr *TheCall =
Anders Carlsson26a2a072009-10-13 21:19:37 +00007350 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCallf89e55a2010-11-18 06:31:45 +00007351 Args, NumArgs, ResultTy, VK, OpLoc);
John McCallb697e082010-05-06 18:15:07 +00007352
John McCall9ae2f072010-08-23 23:25:46 +00007353 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +00007354 FnDecl))
7355 return ExprError();
7356
John McCall9ae2f072010-08-23 23:25:46 +00007357 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007358 } else {
7359 // We matched a built-in operator. Convert the arguments, then
7360 // break out so that we will build the appropriate built-in
7361 // operator node.
7362 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00007363 Best->Conversions[0], AA_Passing))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007364 return ExprError();
7365
7366 break;
7367 }
7368 }
7369
7370 case OR_No_Viable_Function:
7371 // No viable function; fall through to handling this as a
7372 // built-in operator, which will produce an error message for us.
7373 break;
7374
7375 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00007376 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007377 << UnaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +00007378 << Input->getType()
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007379 << Input->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007380 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
7381 Args, NumArgs,
7382 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007383 return ExprError();
7384
7385 case OR_Deleted:
7386 Diag(OpLoc, diag::err_ovl_deleted_oper)
7387 << Best->Function->isDeleted()
7388 << UnaryOperator::getOpcodeStr(Opc)
7389 << Input->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007390 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007391 return ExprError();
7392 }
7393
7394 // Either we found no viable overloaded operator or we matched a
7395 // built-in operator. In either case, fall through to trying to
7396 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +00007397 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007398}
7399
Douglas Gregor063daf62009-03-13 18:40:31 +00007400/// \brief Create a binary operation that may resolve to an overloaded
7401/// operator.
7402///
7403/// \param OpLoc The location of the operator itself (e.g., '+').
7404///
7405/// \param OpcIn The BinaryOperator::Opcode that describes this
7406/// operator.
7407///
7408/// \param Functions The set of non-member functions that will be
7409/// considered by overload resolution. The caller needs to build this
7410/// set based on the context using, e.g.,
7411/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7412/// set should not contain any member functions; those will be added
7413/// by CreateOverloadedBinOp().
7414///
7415/// \param LHS Left-hand argument.
7416/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +00007417ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00007418Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00007419 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00007420 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00007421 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00007422 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007423 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00007424
7425 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
7426 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
7427 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7428
7429 // If either side is type-dependent, create an appropriate dependent
7430 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007431 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00007432 if (Fns.empty()) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007433 // If there are no functions to store, just build a dependent
7434 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +00007435 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007436 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +00007437 Context.DependentTy,
7438 VK_RValue, OK_Ordinary,
7439 OpLoc));
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007440
7441 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
7442 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00007443 VK_LValue,
7444 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007445 Context.DependentTy,
7446 Context.DependentTy,
7447 OpLoc));
7448 }
John McCall6e266892010-01-26 03:27:55 +00007449
7450 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00007451 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00007452 // TODO: provide better source location info in DNLoc component.
7453 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +00007454 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00007455 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00007456 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00007457 /*ADL*/ true, IsOverloaded(Fns),
7458 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00007459 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00007460 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00007461 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00007462 VK_RValue,
Douglas Gregor063daf62009-03-13 18:40:31 +00007463 OpLoc));
7464 }
7465
John McCall0e800c92010-12-04 08:14:53 +00007466 // Always do property rvalue conversions on the RHS.
7467 if (Args[1]->getObjectKind() == OK_ObjCProperty)
7468 ConvertPropertyForRValue(Args[1]);
7469
7470 // The LHS is more complicated.
7471 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
7472
7473 // There's a tension for assignment operators between primitive
7474 // property assignment and the overloaded operators.
7475 if (BinaryOperator::isAssignmentOp(Opc)) {
7476 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7477
7478 // Is the property "logically" settable?
7479 bool Settable = (PRE->isExplicitProperty() ||
7480 PRE->getImplicitPropertySetter());
7481
7482 // To avoid gratuitously inventing semantics, use the primitive
7483 // unless it isn't. Thoughts in case we ever really care:
7484 // - If the property isn't logically settable, we have to
7485 // load and hope.
7486 // - If the property is settable and this is simple assignment,
7487 // we really should use the primitive.
7488 // - If the property is settable, then we could try overloading
7489 // on a generic lvalue of the appropriate type; if it works
7490 // out to a builtin candidate, we would do that same operation
7491 // on the property, and otherwise just error.
7492 if (Settable)
7493 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7494 }
7495
7496 ConvertPropertyForRValue(Args[0]);
7497 }
Douglas Gregor063daf62009-03-13 18:40:31 +00007498
Sebastian Redl275c2b42009-11-18 23:10:33 +00007499 // If this is the assignment operator, we only perform overload resolution
7500 // if the left-hand side is a class or enumeration type. This is actually
7501 // a hack. The standard requires that we do overload resolution between the
7502 // various built-in candidates, but as DR507 points out, this can lead to
7503 // problems. So we do it this way, which pretty much follows what GCC does.
7504 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +00007505 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007506 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00007507
John McCall0e800c92010-12-04 08:14:53 +00007508 // If this is the .* operator, which is not overloadable, just
7509 // create a built-in binary operator.
7510 if (Opc == BO_PtrMemD)
7511 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7512
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007513 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00007514 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00007515
7516 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00007517 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00007518
7519 // Add operator candidates that are member functions.
7520 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
7521
John McCall6e266892010-01-26 03:27:55 +00007522 // Add candidates from ADL.
7523 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
7524 Args, 2,
7525 /*ExplicitTemplateArgs*/ 0,
7526 CandidateSet);
7527
Douglas Gregor063daf62009-03-13 18:40:31 +00007528 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00007529 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00007530
7531 // Perform overload resolution.
7532 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007533 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007534 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00007535 // We found a built-in operator or an overloaded operator.
7536 FunctionDecl *FnDecl = Best->Function;
7537
7538 if (FnDecl) {
7539 // We matched an overloaded operator. Build a call to that
7540 // operator.
7541
7542 // Convert the arguments.
7543 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00007544 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +00007545 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00007546
Chandler Carruth6df868e2010-12-12 08:17:55 +00007547 ExprResult Arg1 =
7548 PerformCopyInitialization(
7549 InitializedEntity::InitializeParameter(Context,
7550 FnDecl->getParamDecl(0)),
7551 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007552 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00007553 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007554
Douglas Gregor5fccd362010-03-03 23:55:11 +00007555 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007556 Best->FoundDecl, Method))
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007557 return ExprError();
7558
7559 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00007560 } else {
7561 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +00007562 ExprResult Arg0 = PerformCopyInitialization(
7563 InitializedEntity::InitializeParameter(Context,
7564 FnDecl->getParamDecl(0)),
7565 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007566 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00007567 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007568
Chandler Carruth6df868e2010-12-12 08:17:55 +00007569 ExprResult Arg1 =
7570 PerformCopyInitialization(
7571 InitializedEntity::InitializeParameter(Context,
7572 FnDecl->getParamDecl(1)),
7573 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007574 if (Arg1.isInvalid())
7575 return ExprError();
7576 Args[0] = LHS = Arg0.takeAs<Expr>();
7577 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00007578 }
7579
John McCallb697e082010-05-06 18:15:07 +00007580 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7581
John McCallf89e55a2010-11-18 06:31:45 +00007582 // Determine the result type.
7583 QualType ResultTy = FnDecl->getResultType();
7584 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7585 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +00007586
7587 // Build the actual expression node.
John McCallf89e55a2010-11-18 06:31:45 +00007588 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00007589
John McCall9ae2f072010-08-23 23:25:46 +00007590 CXXOperatorCallExpr *TheCall =
7591 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCallf89e55a2010-11-18 06:31:45 +00007592 Args, 2, ResultTy, VK, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +00007593
John McCall9ae2f072010-08-23 23:25:46 +00007594 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00007595 FnDecl))
7596 return ExprError();
7597
John McCall9ae2f072010-08-23 23:25:46 +00007598 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +00007599 } else {
7600 // We matched a built-in operator. Convert the arguments, then
7601 // break out so that we will build the appropriate built-in
7602 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007603 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00007604 Best->Conversions[0], AA_Passing) ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007605 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00007606 Best->Conversions[1], AA_Passing))
Douglas Gregor063daf62009-03-13 18:40:31 +00007607 return ExprError();
7608
7609 break;
7610 }
7611 }
7612
Douglas Gregor33074752009-09-30 21:46:01 +00007613 case OR_No_Viable_Function: {
7614 // C++ [over.match.oper]p9:
7615 // If the operator is the operator , [...] and there are no
7616 // viable functions, then the operator is assumed to be the
7617 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +00007618 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +00007619 break;
7620
Chandler Carruth6df868e2010-12-12 08:17:55 +00007621 // For class as left operand for assignment or compound assigment
7622 // operator do not fall through to handling in built-in, but report that
7623 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +00007624 ExprResult Result = ExprError();
Douglas Gregor33074752009-09-30 21:46:01 +00007625 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +00007626 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00007627 Diag(OpLoc, diag::err_ovl_no_viable_oper)
7628 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007629 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00007630 } else {
7631 // No viable function; try to create a built-in operation, which will
7632 // produce an error. Then, show the non-viable candidates.
7633 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00007634 }
Douglas Gregor33074752009-09-30 21:46:01 +00007635 assert(Result.isInvalid() &&
7636 "C++ binary operator overloading is missing candidates!");
7637 if (Result.isInvalid())
John McCall120d63c2010-08-24 20:38:10 +00007638 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7639 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00007640 return move(Result);
7641 }
Douglas Gregor063daf62009-03-13 18:40:31 +00007642
7643 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00007644 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +00007645 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +00007646 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007647 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007648 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7649 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00007650 return ExprError();
7651
7652 case OR_Deleted:
7653 Diag(OpLoc, diag::err_ovl_deleted_oper)
7654 << Best->Function->isDeleted()
7655 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007656 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007657 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor063daf62009-03-13 18:40:31 +00007658 return ExprError();
John McCall1d318332010-01-12 00:44:57 +00007659 }
Douglas Gregor063daf62009-03-13 18:40:31 +00007660
Douglas Gregor33074752009-09-30 21:46:01 +00007661 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007662 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00007663}
7664
John McCall60d7b3a2010-08-24 06:29:42 +00007665ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +00007666Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7667 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +00007668 Expr *Base, Expr *Idx) {
7669 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +00007670 DeclarationName OpName =
7671 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7672
7673 // If either side is type-dependent, create an appropriate dependent
7674 // expression.
7675 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7676
John McCallc373d482010-01-27 01:50:18 +00007677 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00007678 // CHECKME: no 'operator' keyword?
7679 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7680 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +00007681 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00007682 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00007683 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00007684 /*ADL*/ true, /*Overloaded*/ false,
7685 UnresolvedSetIterator(),
7686 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +00007687 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00007688
Sebastian Redlf322ed62009-10-29 20:17:01 +00007689 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7690 Args, 2,
7691 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00007692 VK_RValue,
Sebastian Redlf322ed62009-10-29 20:17:01 +00007693 RLoc));
7694 }
7695
John McCall0e800c92010-12-04 08:14:53 +00007696 if (Args[0]->getObjectKind() == OK_ObjCProperty)
7697 ConvertPropertyForRValue(Args[0]);
7698 if (Args[1]->getObjectKind() == OK_ObjCProperty)
7699 ConvertPropertyForRValue(Args[1]);
7700
Sebastian Redlf322ed62009-10-29 20:17:01 +00007701 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00007702 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007703
7704 // Subscript can only be overloaded as a member function.
7705
7706 // Add operator candidates that are member functions.
7707 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7708
7709 // Add builtin operator candidates.
7710 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7711
7712 // Perform overload resolution.
7713 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007714 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00007715 case OR_Success: {
7716 // We found a built-in operator or an overloaded operator.
7717 FunctionDecl *FnDecl = Best->Function;
7718
7719 if (FnDecl) {
7720 // We matched an overloaded operator. Build a call to that
7721 // operator.
7722
John McCall9aa472c2010-03-19 07:35:19 +00007723 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007724 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +00007725
Sebastian Redlf322ed62009-10-29 20:17:01 +00007726 // Convert the arguments.
7727 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007728 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007729 Best->FoundDecl, Method))
Sebastian Redlf322ed62009-10-29 20:17:01 +00007730 return ExprError();
7731
Anders Carlsson38f88ab2010-01-29 18:37:50 +00007732 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00007733 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +00007734 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007735 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +00007736 FnDecl->getParamDecl(0)),
7737 SourceLocation(),
7738 Owned(Args[1]));
7739 if (InputInit.isInvalid())
7740 return ExprError();
7741
7742 Args[1] = InputInit.takeAs<Expr>();
7743
Sebastian Redlf322ed62009-10-29 20:17:01 +00007744 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +00007745 QualType ResultTy = FnDecl->getResultType();
7746 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7747 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007748
7749 // Build the actual expression node.
John McCallf89e55a2010-11-18 06:31:45 +00007750 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007751
John McCall9ae2f072010-08-23 23:25:46 +00007752 CXXOperatorCallExpr *TheCall =
7753 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7754 FnExpr, Args, 2,
John McCallf89e55a2010-11-18 06:31:45 +00007755 ResultTy, VK, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007756
John McCall9ae2f072010-08-23 23:25:46 +00007757 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +00007758 FnDecl))
7759 return ExprError();
7760
John McCall9ae2f072010-08-23 23:25:46 +00007761 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007762 } else {
7763 // We matched a built-in operator. Convert the arguments, then
7764 // break out so that we will build the appropriate built-in
7765 // operator node.
7766 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00007767 Best->Conversions[0], AA_Passing) ||
Sebastian Redlf322ed62009-10-29 20:17:01 +00007768 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00007769 Best->Conversions[1], AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00007770 return ExprError();
7771
7772 break;
7773 }
7774 }
7775
7776 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00007777 if (CandidateSet.empty())
7778 Diag(LLoc, diag::err_ovl_no_oper)
7779 << Args[0]->getType() << /*subscript*/ 0
7780 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7781 else
7782 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7783 << Args[0]->getType()
7784 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007785 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7786 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +00007787 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00007788 }
7789
7790 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00007791 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
7792 << "[]"
7793 << Args[0]->getType() << Args[1]->getType()
7794 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007795 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7796 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007797 return ExprError();
7798
7799 case OR_Deleted:
7800 Diag(LLoc, diag::err_ovl_deleted_oper)
7801 << Best->Function->isDeleted() << "[]"
7802 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007803 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7804 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007805 return ExprError();
7806 }
7807
7808 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +00007809 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007810}
7811
Douglas Gregor88a35142008-12-22 05:46:06 +00007812/// BuildCallToMemberFunction - Build a call to a member
7813/// function. MemExpr is the expression that refers to the member
7814/// function (and includes the object parameter), Args/NumArgs are the
7815/// arguments to the function call (not including the object
7816/// parameter). The caller needs to validate that the member
7817/// expression refers to a member function or an overloaded member
7818/// function.
John McCall60d7b3a2010-08-24 06:29:42 +00007819ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00007820Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7821 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +00007822 unsigned NumArgs, SourceLocation RParenLoc) {
Douglas Gregor88a35142008-12-22 05:46:06 +00007823 // Dig out the member expression. This holds both the object
7824 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00007825 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7826
John McCall129e2df2009-11-30 22:42:35 +00007827 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00007828 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +00007829 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007830 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +00007831 if (isa<MemberExpr>(NakedMemExpr)) {
7832 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00007833 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +00007834 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +00007835 Qualifier = MemExpr->getQualifier();
John McCall129e2df2009-11-30 22:42:35 +00007836 } else {
7837 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007838 Qualifier = UnresExpr->getQualifier();
7839
John McCall701c89e2009-12-03 04:06:58 +00007840 QualType ObjectType = UnresExpr->getBaseType();
John McCall129e2df2009-11-30 22:42:35 +00007841
Douglas Gregor88a35142008-12-22 05:46:06 +00007842 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +00007843 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00007844
John McCallaa81e162009-12-01 22:10:20 +00007845 // FIXME: avoid copy.
7846 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7847 if (UnresExpr->hasExplicitTemplateArgs()) {
7848 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7849 TemplateArgs = &TemplateArgsBuffer;
7850 }
7851
John McCall129e2df2009-11-30 22:42:35 +00007852 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7853 E = UnresExpr->decls_end(); I != E; ++I) {
7854
John McCall701c89e2009-12-03 04:06:58 +00007855 NamedDecl *Func = *I;
7856 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7857 if (isa<UsingShadowDecl>(Func))
7858 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7859
John McCall129e2df2009-11-30 22:42:35 +00007860 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00007861 // If explicit template arguments were provided, we can't call a
7862 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00007863 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00007864 continue;
7865
John McCall9aa472c2010-03-19 07:35:19 +00007866 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCall86820f52010-01-26 01:37:31 +00007867 Args, NumArgs,
John McCall701c89e2009-12-03 04:06:58 +00007868 CandidateSet, /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00007869 } else {
John McCall129e2df2009-11-30 22:42:35 +00007870 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +00007871 I.getPair(), ActingDC, TemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00007872 ObjectType, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00007873 CandidateSet,
7874 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00007875 }
Douglas Gregordec06662009-08-21 18:42:58 +00007876 }
Mike Stump1eb44332009-09-09 15:08:12 +00007877
John McCall129e2df2009-11-30 22:42:35 +00007878 DeclarationName DeclName = UnresExpr->getMemberName();
7879
Douglas Gregor88a35142008-12-22 05:46:06 +00007880 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007881 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +00007882 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00007883 case OR_Success:
7884 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00007885 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +00007886 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007887 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +00007888 break;
7889
7890 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00007891 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00007892 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00007893 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007894 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00007895 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007896 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007897
7898 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00007899 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00007900 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007901 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00007902 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007903 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007904
7905 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00007906 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007907 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00007908 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007909 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007910 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007911 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007912 }
7913
John McCall6bb80172010-03-30 21:47:33 +00007914 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +00007915
John McCallaa81e162009-12-01 22:10:20 +00007916 // If overload resolution picked a static member, build a
7917 // non-member call based on that function.
7918 if (Method->isStatic()) {
7919 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7920 Args, NumArgs, RParenLoc);
7921 }
7922
John McCall129e2df2009-11-30 22:42:35 +00007923 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00007924 }
7925
John McCallf89e55a2010-11-18 06:31:45 +00007926 QualType ResultType = Method->getResultType();
7927 ExprValueKind VK = Expr::getValueKindForType(ResultType);
7928 ResultType = ResultType.getNonLValueExprType(Context);
7929
Douglas Gregor88a35142008-12-22 05:46:06 +00007930 assert(Method && "Member call to something that isn't a method?");
John McCall9ae2f072010-08-23 23:25:46 +00007931 CXXMemberCallExpr *TheCall =
7932 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCallf89e55a2010-11-18 06:31:45 +00007933 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +00007934
Anders Carlssoneed3e692009-10-10 00:06:20 +00007935 // Check for a valid return type.
7936 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +00007937 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +00007938 return ExprError();
Anders Carlssoneed3e692009-10-10 00:06:20 +00007939
Douglas Gregor88a35142008-12-22 05:46:06 +00007940 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +00007941 // We only need to do this if there was actually an overload; otherwise
7942 // it was done at lookup.
John McCallaa81e162009-12-01 22:10:20 +00007943 Expr *ObjectArg = MemExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00007944 if (!Method->isStatic() &&
John McCall6bb80172010-03-30 21:47:33 +00007945 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7946 FoundDecl, Method))
John McCallaa81e162009-12-01 22:10:20 +00007947 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007948 MemExpr->setBase(ObjectArg);
7949
7950 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +00007951 const FunctionProtoType *Proto =
7952 Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +00007953 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00007954 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00007955 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007956
John McCall9ae2f072010-08-23 23:25:46 +00007957 if (CheckFunctionCall(Method, TheCall))
John McCallaa81e162009-12-01 22:10:20 +00007958 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00007959
John McCall9ae2f072010-08-23 23:25:46 +00007960 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +00007961}
7962
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007963/// BuildCallToObjectOfClassType - Build a call to an object of class
7964/// type (C++ [over.call.object]), which can end up invoking an
7965/// overloaded function call operator (@c operator()) or performing a
7966/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +00007967ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00007968Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00007969 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007970 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007971 SourceLocation RParenLoc) {
John McCall0e800c92010-12-04 08:14:53 +00007972 if (Object->getObjectKind() == OK_ObjCProperty)
7973 ConvertPropertyForRValue(Object);
7974
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007975 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00007976 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00007977
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007978 // C++ [over.call.object]p1:
7979 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00007980 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007981 // candidate functions includes at least the function call
7982 // operators of T. The function call operators of T are obtained by
7983 // ordinary lookup of the name operator() in the context of
7984 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +00007985 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00007986 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00007987
7988 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007989 PDiag(diag::err_incomplete_object_call)
Douglas Gregor593564b2009-11-15 07:48:03 +00007990 << Object->getSourceRange()))
7991 return true;
7992
John McCalla24dc2e2009-11-17 02:14:36 +00007993 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7994 LookupQualifiedName(R, Record->getDecl());
7995 R.suppressDiagnostics();
7996
Douglas Gregor593564b2009-11-15 07:48:03 +00007997 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00007998 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00007999 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCall86820f52010-01-26 01:37:31 +00008000 Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00008001 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00008002 }
Douglas Gregor4a27d702009-10-21 06:18:39 +00008003
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008004 // C++ [over.call.object]p2:
8005 // In addition, for each conversion function declared in T of the
8006 // form
8007 //
8008 // operator conversion-type-id () cv-qualifier;
8009 //
8010 // where cv-qualifier is the same cv-qualification as, or a
8011 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00008012 // denotes the type "pointer to function of (P1,...,Pn) returning
8013 // R", or the type "reference to pointer to function of
8014 // (P1,...,Pn) returning R", or the type "reference to function
8015 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008016 // is also considered as a candidate function. Similarly,
8017 // surrogate call functions are added to the set of candidate
8018 // functions for each conversion function declared in an
8019 // accessible base class provided the function is not hidden
8020 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +00008021 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00008022 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00008023 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00008024 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00008025 NamedDecl *D = *I;
8026 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
8027 if (isa<UsingShadowDecl>(D))
8028 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8029
Douglas Gregor4a27d702009-10-21 06:18:39 +00008030 // Skip over templated conversion functions; they aren't
8031 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00008032 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00008033 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00008034
John McCall701c89e2009-12-03 04:06:58 +00008035 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCallba135432009-11-21 08:51:07 +00008036
Douglas Gregor4a27d702009-10-21 06:18:39 +00008037 // Strip the reference type (if any) and then the pointer type (if
8038 // any) to get down to what might be a function type.
8039 QualType ConvType = Conv->getConversionType().getNonReferenceType();
8040 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8041 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008042
Douglas Gregor4a27d702009-10-21 06:18:39 +00008043 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall9aa472c2010-03-19 07:35:19 +00008044 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall701c89e2009-12-03 04:06:58 +00008045 Object->getType(), Args, NumArgs,
8046 CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008047 }
Mike Stump1eb44332009-09-09 15:08:12 +00008048
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008049 // Perform overload resolution.
8050 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00008051 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
8052 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008053 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008054 // Overload resolution succeeded; we'll build the appropriate call
8055 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008056 break;
8057
8058 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00008059 if (CandidateSet.empty())
8060 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
8061 << Object->getType() << /*call*/ 1
8062 << Object->getSourceRange();
8063 else
8064 Diag(Object->getSourceRange().getBegin(),
8065 diag::err_ovl_no_viable_object_call)
8066 << Object->getType() << Object->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008067 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008068 break;
8069
8070 case OR_Ambiguous:
8071 Diag(Object->getSourceRange().getBegin(),
8072 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00008073 << Object->getType() << Object->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008074 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008075 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008076
8077 case OR_Deleted:
8078 Diag(Object->getSourceRange().getBegin(),
8079 diag::err_ovl_deleted_object_call)
8080 << Best->Function->isDeleted()
8081 << Object->getType() << Object->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008082 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008083 break;
Mike Stump1eb44332009-09-09 15:08:12 +00008084 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008085
Douglas Gregorff331c12010-07-25 18:17:45 +00008086 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008087 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008088
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008089 if (Best->Function == 0) {
8090 // Since there is no function declaration, this is one of the
8091 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00008092 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008093 = cast<CXXConversionDecl>(
8094 Best->Conversions[0].UserDefined.ConversionFunction);
8095
John McCall9aa472c2010-03-19 07:35:19 +00008096 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00008097 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00008098
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008099 // We selected one of the surrogate functions that converts the
8100 // object parameter to a function pointer. Perform the conversion
8101 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00008102
8103 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00008104 // and then call it.
John McCall6bb80172010-03-30 21:47:33 +00008105 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
8106 Conv);
Fariborz Jahanianb7400232009-09-28 23:23:40 +00008107
John McCallf312b1e2010-08-26 23:41:50 +00008108 return ActOnCallExpr(S, CE, LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00008109 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008110 }
8111
John McCall9aa472c2010-03-19 07:35:19 +00008112 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00008113 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00008114
Douglas Gregor106c6eb2008-11-19 22:57:39 +00008115 // We found an overloaded operator(). Build a CXXOperatorCallExpr
8116 // that calls this method, using Object for the implicit object
8117 // parameter and passing along the remaining arguments.
8118 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth6df868e2010-12-12 08:17:55 +00008119 const FunctionProtoType *Proto =
8120 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008121
8122 unsigned NumArgsInProto = Proto->getNumArgs();
8123 unsigned NumArgsToCheck = NumArgs;
8124
8125 // Build the full argument list for the method call (the
8126 // implicit object parameter is placed at the beginning of the
8127 // list).
8128 Expr **MethodArgs;
8129 if (NumArgs < NumArgsInProto) {
8130 NumArgsToCheck = NumArgsInProto;
8131 MethodArgs = new Expr*[NumArgsInProto + 1];
8132 } else {
8133 MethodArgs = new Expr*[NumArgs + 1];
8134 }
8135 MethodArgs[0] = Object;
8136 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
8137 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00008138
John McCallf89e55a2010-11-18 06:31:45 +00008139 Expr *NewFn = CreateFunctionRefExpr(*this, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008140
8141 // Once we've built TheCall, all of the expressions are properly
8142 // owned.
John McCallf89e55a2010-11-18 06:31:45 +00008143 QualType ResultTy = Method->getResultType();
8144 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8145 ResultTy = ResultTy.getNonLValueExprType(Context);
8146
John McCall9ae2f072010-08-23 23:25:46 +00008147 CXXOperatorCallExpr *TheCall =
8148 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
8149 MethodArgs, NumArgs + 1,
John McCallf89e55a2010-11-18 06:31:45 +00008150 ResultTy, VK, RParenLoc);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008151 delete [] MethodArgs;
8152
John McCall9ae2f072010-08-23 23:25:46 +00008153 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +00008154 Method))
8155 return true;
8156
Douglas Gregor518fda12009-01-13 05:10:00 +00008157 // We may have default arguments. If so, we need to allocate more
8158 // slots in the call for them.
8159 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00008160 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00008161 else if (NumArgs > NumArgsInProto)
8162 NumArgsToCheck = NumArgsInProto;
8163
Chris Lattner312531a2009-04-12 08:11:20 +00008164 bool IsError = false;
8165
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008166 // Initialize the implicit object parameter.
Douglas Gregor5fccd362010-03-03 23:55:11 +00008167 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00008168 Best->FoundDecl, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008169 TheCall->setArg(0, Object);
8170
Chris Lattner312531a2009-04-12 08:11:20 +00008171
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008172 // Check the argument types.
8173 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008174 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00008175 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008176 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00008177
Douglas Gregor518fda12009-01-13 05:10:00 +00008178 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +00008179
John McCall60d7b3a2010-08-24 06:29:42 +00008180 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +00008181 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00008182 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +00008183 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +00008184 SourceLocation(), Arg);
Anders Carlsson3faa4862010-01-29 18:43:53 +00008185
8186 IsError |= InputInit.isInvalid();
8187 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00008188 } else {
John McCall60d7b3a2010-08-24 06:29:42 +00008189 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +00008190 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
8191 if (DefArg.isInvalid()) {
8192 IsError = true;
8193 break;
8194 }
8195
8196 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00008197 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008198
8199 TheCall->setArg(i + 1, Arg);
8200 }
8201
8202 // If this is a variadic call, handle args passed through "...".
8203 if (Proto->isVariadic()) {
8204 // Promote the arguments (C99 6.5.2.2p7).
8205 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
8206 Expr *Arg = Args[i];
Chris Lattner40378332010-05-16 04:01:30 +00008207 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008208 TheCall->setArg(i + 1, Arg);
8209 }
8210 }
8211
Chris Lattner312531a2009-04-12 08:11:20 +00008212 if (IsError) return true;
8213
John McCall9ae2f072010-08-23 23:25:46 +00008214 if (CheckFunctionCall(Method, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00008215 return true;
8216
John McCall182f7092010-08-24 06:09:16 +00008217 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00008218}
8219
Douglas Gregor8ba10742008-11-20 16:27:02 +00008220/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00008221/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00008222/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +00008223ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00008224Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +00008225 assert(Base->getType()->isRecordType() &&
8226 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00008227
John McCall0e800c92010-12-04 08:14:53 +00008228 if (Base->getObjectKind() == OK_ObjCProperty)
8229 ConvertPropertyForRValue(Base);
8230
John McCall5769d612010-02-08 23:07:23 +00008231 SourceLocation Loc = Base->getExprLoc();
8232
Douglas Gregor8ba10742008-11-20 16:27:02 +00008233 // C++ [over.ref]p1:
8234 //
8235 // [...] An expression x->m is interpreted as (x.operator->())->m
8236 // for a class object x of type T if T::operator->() exists and if
8237 // the operator is selected as the best match function by the
8238 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +00008239 DeclarationName OpName =
8240 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +00008241 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +00008242 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008243
John McCall5769d612010-02-08 23:07:23 +00008244 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +00008245 PDiag(diag::err_typecheck_incomplete_tag)
8246 << Base->getSourceRange()))
8247 return ExprError();
8248
John McCalla24dc2e2009-11-17 02:14:36 +00008249 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
8250 LookupQualifiedName(R, BaseRecord->getDecl());
8251 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00008252
8253 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00008254 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00008255 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00008256 /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00008257 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00008258
8259 // Perform overload resolution.
8260 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00008261 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00008262 case OR_Success:
8263 // Overload resolution succeeded; we'll build the call below.
8264 break;
8265
8266 case OR_No_Viable_Function:
8267 if (CandidateSet.empty())
8268 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008269 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00008270 else
8271 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008272 << "operator->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008273 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008274 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00008275
8276 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00008277 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8278 << "->" << Base->getType() << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008279 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008280 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008281
8282 case OR_Deleted:
8283 Diag(OpLoc, diag::err_ovl_deleted_oper)
8284 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00008285 << "->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008286 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008287 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00008288 }
8289
John McCall9aa472c2010-03-19 07:35:19 +00008290 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00008291 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +00008292
Douglas Gregor8ba10742008-11-20 16:27:02 +00008293 // Convert the object parameter.
8294 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00008295 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
8296 Best->FoundDecl, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008297 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00008298
Douglas Gregor8ba10742008-11-20 16:27:02 +00008299 // Build the operator call.
John McCallf89e55a2010-11-18 06:31:45 +00008300 Expr *FnExpr = CreateFunctionRefExpr(*this, Method);
Anders Carlsson15ea3782009-10-13 22:43:21 +00008301
John McCallf89e55a2010-11-18 06:31:45 +00008302 QualType ResultTy = Method->getResultType();
8303 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8304 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +00008305 CXXOperatorCallExpr *TheCall =
8306 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
John McCallf89e55a2010-11-18 06:31:45 +00008307 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +00008308
John McCall9ae2f072010-08-23 23:25:46 +00008309 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00008310 Method))
8311 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00008312 return Owned(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00008313}
8314
Douglas Gregor904eed32008-11-10 20:40:00 +00008315/// FixOverloadedFunctionReference - E is an expression that refers to
8316/// a C++ overloaded function (possibly with some parentheses and
8317/// perhaps a '&' around it). We have resolved the overloaded function
8318/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00008319/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +00008320Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +00008321 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00008322 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00008323 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
8324 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00008325 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00008326 return PE;
Douglas Gregor699ee522009-11-20 19:42:02 +00008327
8328 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
8329 }
8330
8331 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00008332 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
8333 Found, Fn);
Douglas Gregor097bfb12009-10-23 22:18:25 +00008334 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00008335 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00008336 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +00008337 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +00008338 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00008339 return ICE;
Douglas Gregor699ee522009-11-20 19:42:02 +00008340
John McCallf871d0c2010-08-07 06:22:56 +00008341 return ImplicitCastExpr::Create(Context, ICE->getType(),
8342 ICE->getCastKind(),
8343 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +00008344 ICE->getValueKind());
Douglas Gregor699ee522009-11-20 19:42:02 +00008345 }
8346
8347 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00008348 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00008349 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00008350 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8351 if (Method->isStatic()) {
8352 // Do nothing: static member functions aren't any different
8353 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00008354 } else {
John McCallf7a1a742009-11-24 19:00:30 +00008355 // Fix the sub expression, which really has to be an
8356 // UnresolvedLookupExpr holding an overloaded member function
8357 // or template.
John McCall6bb80172010-03-30 21:47:33 +00008358 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8359 Found, Fn);
John McCallba135432009-11-21 08:51:07 +00008360 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00008361 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +00008362
John McCallba135432009-11-21 08:51:07 +00008363 assert(isa<DeclRefExpr>(SubExpr)
8364 && "fixed to something other than a decl ref");
8365 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
8366 && "fixed to a member ref with no nested name qualifier");
8367
8368 // We have taken the address of a pointer to member
8369 // function. Perform the computation here so that we get the
8370 // appropriate pointer to member type.
8371 QualType ClassType
8372 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
8373 QualType MemPtrType
8374 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
8375
John McCallf89e55a2010-11-18 06:31:45 +00008376 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
8377 VK_RValue, OK_Ordinary,
8378 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00008379 }
8380 }
John McCall6bb80172010-03-30 21:47:33 +00008381 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8382 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00008383 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00008384 return UnOp;
Anders Carlsson96ad5332009-10-21 17:16:23 +00008385
John McCall2de56d12010-08-25 11:45:40 +00008386 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +00008387 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00008388 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +00008389 UnOp->getOperatorLoc());
Douglas Gregor699ee522009-11-20 19:42:02 +00008390 }
John McCallba135432009-11-21 08:51:07 +00008391
8392 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00008393 // FIXME: avoid copy.
8394 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00008395 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00008396 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
8397 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00008398 }
8399
John McCallba135432009-11-21 08:51:07 +00008400 return DeclRefExpr::Create(Context,
8401 ULE->getQualifier(),
8402 ULE->getQualifierRange(),
8403 Fn,
8404 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00008405 Fn->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00008406 VK_LValue,
John McCallaa81e162009-12-01 22:10:20 +00008407 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00008408 }
8409
John McCall129e2df2009-11-30 22:42:35 +00008410 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00008411 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00008412 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8413 if (MemExpr->hasExplicitTemplateArgs()) {
8414 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8415 TemplateArgs = &TemplateArgsBuffer;
8416 }
John McCalld5532b62009-11-23 01:53:49 +00008417
John McCallaa81e162009-12-01 22:10:20 +00008418 Expr *Base;
8419
John McCallf89e55a2010-11-18 06:31:45 +00008420 // If we're filling in a static method where we used to have an
8421 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +00008422 if (MemExpr->isImplicitAccess()) {
8423 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
8424 return DeclRefExpr::Create(Context,
8425 MemExpr->getQualifier(),
8426 MemExpr->getQualifierRange(),
8427 Fn,
8428 MemExpr->getMemberLoc(),
8429 Fn->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00008430 VK_LValue,
John McCallaa81e162009-12-01 22:10:20 +00008431 TemplateArgs);
Douglas Gregor828a1972010-01-07 23:12:05 +00008432 } else {
8433 SourceLocation Loc = MemExpr->getMemberLoc();
8434 if (MemExpr->getQualifier())
8435 Loc = MemExpr->getQualifierRange().getBegin();
8436 Base = new (Context) CXXThisExpr(Loc,
8437 MemExpr->getBaseType(),
8438 /*isImplicit=*/true);
8439 }
John McCallaa81e162009-12-01 22:10:20 +00008440 } else
John McCall3fa5cae2010-10-26 07:05:15 +00008441 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +00008442
8443 return MemberExpr::Create(Context, Base,
Douglas Gregor699ee522009-11-20 19:42:02 +00008444 MemExpr->isArrow(),
8445 MemExpr->getQualifier(),
8446 MemExpr->getQualifierRange(),
8447 Fn,
John McCall6bb80172010-03-30 21:47:33 +00008448 Found,
Abramo Bagnara25777432010-08-11 22:01:17 +00008449 MemExpr->getMemberNameInfo(),
John McCallaa81e162009-12-01 22:10:20 +00008450 TemplateArgs,
John McCallf89e55a2010-11-18 06:31:45 +00008451 Fn->getType(),
8452 cast<CXXMethodDecl>(Fn)->isStatic()
8453 ? VK_LValue : VK_RValue,
8454 OK_Ordinary);
Douglas Gregor699ee522009-11-20 19:42:02 +00008455 }
8456
John McCall3fa5cae2010-10-26 07:05:15 +00008457 llvm_unreachable("Invalid reference to overloaded function");
8458 return E;
Douglas Gregor904eed32008-11-10 20:40:00 +00008459}
8460
John McCall60d7b3a2010-08-24 06:29:42 +00008461ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
8462 DeclAccessPair Found,
8463 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +00008464 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +00008465}
8466
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008467} // end namespace clang