blob: 8f653d1df086c22854c1e628eb00e23d454ba1df [file] [log] [blame]
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCall7cd088e2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000021#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000024#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000026#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000027#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor661b4932010-09-12 04:28:07 +000028#include "llvm/ADT/DenseSet.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000029#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000030#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000031#include <algorithm>
32
33namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000034using namespace sema;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000035
John McCall120d63c2010-08-24 20:38:10 +000036static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
37 bool InOverloadResolution,
38 StandardConversionSequence &SCS);
39static OverloadingResult
40IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
41 UserDefinedConversionSequence& User,
42 OverloadCandidateSet& Conversions,
43 bool AllowExplicit);
44
45
46static ImplicitConversionSequence::CompareKind
47CompareStandardConversionSequences(Sema &S,
48 const StandardConversionSequence& SCS1,
49 const StandardConversionSequence& SCS2);
50
51static ImplicitConversionSequence::CompareKind
52CompareQualificationConversions(Sema &S,
53 const StandardConversionSequence& SCS1,
54 const StandardConversionSequence& SCS2);
55
56static ImplicitConversionSequence::CompareKind
57CompareDerivedToBaseConversions(Sema &S,
58 const StandardConversionSequence& SCS1,
59 const StandardConversionSequence& SCS2);
60
61
62
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000063/// GetConversionCategory - Retrieve the implicit conversion
64/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000065ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000066GetConversionCategory(ImplicitConversionKind Kind) {
67 static const ImplicitConversionCategory
68 Category[(int)ICK_Num_Conversion_Kinds] = {
69 ICC_Identity,
70 ICC_Lvalue_Transformation,
71 ICC_Lvalue_Transformation,
72 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +000073 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000074 ICC_Qualification_Adjustment,
75 ICC_Promotion,
76 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000077 ICC_Promotion,
78 ICC_Conversion,
79 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000080 ICC_Conversion,
81 ICC_Conversion,
82 ICC_Conversion,
83 ICC_Conversion,
84 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000085 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000086 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +000087 ICC_Conversion,
88 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000089 ICC_Conversion
90 };
91 return Category[(int)Kind];
92}
93
94/// GetConversionRank - Retrieve the implicit conversion rank
95/// corresponding to the given implicit conversion kind.
96ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
97 static const ImplicitConversionRank
98 Rank[(int)ICK_Num_Conversion_Kinds] = {
99 ICR_Exact_Match,
100 ICR_Exact_Match,
101 ICR_Exact_Match,
102 ICR_Exact_Match,
103 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000104 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000105 ICR_Promotion,
106 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000107 ICR_Promotion,
108 ICR_Conversion,
109 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000110 ICR_Conversion,
111 ICR_Conversion,
112 ICR_Conversion,
113 ICR_Conversion,
114 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000115 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000116 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000117 ICR_Conversion,
118 ICR_Conversion,
Chandler Carruth23a370f2010-02-25 07:20:54 +0000119 ICR_Complex_Real_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000120 };
121 return Rank[(int)Kind];
122}
123
124/// GetImplicitConversionName - Return the name of this kind of
125/// implicit conversion.
126const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +0000127 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000128 "No conversion",
129 "Lvalue-to-rvalue",
130 "Array-to-pointer",
131 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000132 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000133 "Qualification",
134 "Integral promotion",
135 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000136 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000137 "Integral conversion",
138 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000139 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000140 "Floating-integral conversion",
141 "Pointer conversion",
142 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000143 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000144 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000145 "Derived-to-base conversion",
146 "Vector conversion",
147 "Vector splat",
148 "Complex-real conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000149 };
150 return Name[Kind];
151}
152
Douglas Gregor60d62c22008-10-31 16:23:19 +0000153/// StandardConversionSequence - Set the standard conversion
154/// sequence to the identity conversion.
155void StandardConversionSequence::setAsIdentityConversion() {
156 First = ICK_Identity;
157 Second = ICK_Identity;
158 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000159 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000160 ReferenceBinding = false;
161 DirectBinding = false;
Sebastian Redl85002392009-03-29 22:46:24 +0000162 RRefBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000163 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000164}
165
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000166/// getRank - Retrieve the rank of this standard conversion sequence
167/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
168/// implicit conversions.
169ImplicitConversionRank StandardConversionSequence::getRank() const {
170 ImplicitConversionRank Rank = ICR_Exact_Match;
171 if (GetConversionRank(First) > Rank)
172 Rank = GetConversionRank(First);
173 if (GetConversionRank(Second) > Rank)
174 Rank = GetConversionRank(Second);
175 if (GetConversionRank(Third) > Rank)
176 Rank = GetConversionRank(Third);
177 return Rank;
178}
179
180/// isPointerConversionToBool - Determines whether this conversion is
181/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000182/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000183/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000184bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000185 // Note that FromType has not necessarily been transformed by the
186 // array-to-pointer or function-to-pointer implicit conversions, so
187 // check for their presence as well as checking whether FromType is
188 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000189 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000190 (getFromType()->isPointerType() ||
191 getFromType()->isObjCObjectPointerType() ||
192 getFromType()->isBlockPointerType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000193 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
194 return true;
195
196 return false;
197}
198
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000199/// isPointerConversionToVoidPointer - Determines whether this
200/// conversion is a conversion of a pointer to a void pointer. This is
201/// used as part of the ranking of standard conversion sequences (C++
202/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000203bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000204StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000205isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000206 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000207 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000208
209 // Note that FromType has not necessarily been transformed by the
210 // array-to-pointer implicit conversion, so check for its presence
211 // and redo the conversion to get a pointer.
212 if (First == ICK_Array_To_Pointer)
213 FromType = Context.getArrayDecayedType(FromType);
214
Douglas Gregor01919692009-12-13 21:37:05 +0000215 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000216 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000217 return ToPtrType->getPointeeType()->isVoidType();
218
219 return false;
220}
221
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000222/// DebugPrint - Print this standard conversion sequence to standard
223/// error. Useful for debugging overloading issues.
224void StandardConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000225 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000226 bool PrintedSomething = false;
227 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000228 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000229 PrintedSomething = true;
230 }
231
232 if (Second != ICK_Identity) {
233 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000234 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000235 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000236 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000237
238 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000239 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000240 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000241 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000242 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000243 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000244 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000245 PrintedSomething = true;
246 }
247
248 if (Third != ICK_Identity) {
249 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000250 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000251 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000252 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000253 PrintedSomething = true;
254 }
255
256 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000257 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000258 }
259}
260
261/// DebugPrint - Print this user-defined conversion sequence to standard
262/// error. Useful for debugging overloading issues.
263void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000264 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000265 if (Before.First || Before.Second || Before.Third) {
266 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000267 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000268 }
Benjamin Kramer900fc632010-04-17 09:33:03 +0000269 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000270 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000271 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000272 After.DebugPrint();
273 }
274}
275
276/// DebugPrint - Print this implicit conversion sequence to standard
277/// error. Useful for debugging overloading issues.
278void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000279 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000280 switch (ConversionKind) {
281 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000282 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000283 Standard.DebugPrint();
284 break;
285 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000286 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000287 UserDefined.DebugPrint();
288 break;
289 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000290 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000291 break;
John McCall1d318332010-01-12 00:44:57 +0000292 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000293 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000294 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000295 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000296 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000297 break;
298 }
299
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000300 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000301}
302
John McCall1d318332010-01-12 00:44:57 +0000303void AmbiguousConversionSequence::construct() {
304 new (&conversions()) ConversionSet();
305}
306
307void AmbiguousConversionSequence::destruct() {
308 conversions().~ConversionSet();
309}
310
311void
312AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
313 FromTypePtr = O.FromTypePtr;
314 ToTypePtr = O.ToTypePtr;
315 new (&conversions()) ConversionSet(O.conversions());
316}
317
Douglas Gregora9333192010-05-08 17:41:32 +0000318namespace {
319 // Structure used by OverloadCandidate::DeductionFailureInfo to store
320 // template parameter and template argument information.
321 struct DFIParamWithArguments {
322 TemplateParameter Param;
323 TemplateArgument FirstArg;
324 TemplateArgument SecondArg;
325 };
326}
327
328/// \brief Convert from Sema's representation of template deduction information
329/// to the form used in overload-candidate information.
330OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000331static MakeDeductionFailureInfo(ASTContext &Context,
332 Sema::TemplateDeductionResult TDK,
John McCall2a7fb272010-08-25 05:32:35 +0000333 TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000334 OverloadCandidate::DeductionFailureInfo Result;
335 Result.Result = static_cast<unsigned>(TDK);
336 Result.Data = 0;
337 switch (TDK) {
338 case Sema::TDK_Success:
339 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000340 case Sema::TDK_TooManyArguments:
341 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000342 break;
343
344 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000345 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000346 Result.Data = Info.Param.getOpaqueValue();
347 break;
348
Douglas Gregora9333192010-05-08 17:41:32 +0000349 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000350 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000351 // FIXME: Should allocate from normal heap so that we can free this later.
352 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000353 Saved->Param = Info.Param;
354 Saved->FirstArg = Info.FirstArg;
355 Saved->SecondArg = Info.SecondArg;
356 Result.Data = Saved;
357 break;
358 }
359
360 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000361 Result.Data = Info.take();
362 break;
363
Douglas Gregora9333192010-05-08 17:41:32 +0000364 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000365 case Sema::TDK_FailedOverloadResolution:
366 break;
367 }
368
369 return Result;
370}
John McCall1d318332010-01-12 00:44:57 +0000371
Douglas Gregora9333192010-05-08 17:41:32 +0000372void OverloadCandidate::DeductionFailureInfo::Destroy() {
373 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
374 case Sema::TDK_Success:
375 case Sema::TDK_InstantiationDepth:
376 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000377 case Sema::TDK_TooManyArguments:
378 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000379 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000380 break;
381
Douglas Gregora9333192010-05-08 17:41:32 +0000382 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000383 case Sema::TDK_Underqualified:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000384 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000385 Data = 0;
386 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000387
388 case Sema::TDK_SubstitutionFailure:
389 // FIXME: Destroy the template arugment list?
390 Data = 0;
391 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000392
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000393 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000394 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000395 case Sema::TDK_FailedOverloadResolution:
396 break;
397 }
398}
399
400TemplateParameter
401OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
402 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
403 case Sema::TDK_Success:
404 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000405 case Sema::TDK_TooManyArguments:
406 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000407 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000408 return TemplateParameter();
409
410 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000411 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000412 return TemplateParameter::getFromOpaqueValue(Data);
413
414 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000415 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000416 return static_cast<DFIParamWithArguments*>(Data)->Param;
417
418 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000419 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000420 case Sema::TDK_FailedOverloadResolution:
421 break;
422 }
423
424 return TemplateParameter();
425}
Douglas Gregorec20f462010-05-08 20:07:26 +0000426
427TemplateArgumentList *
428OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
429 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
430 case Sema::TDK_Success:
431 case Sema::TDK_InstantiationDepth:
432 case Sema::TDK_TooManyArguments:
433 case Sema::TDK_TooFewArguments:
434 case Sema::TDK_Incomplete:
435 case Sema::TDK_InvalidExplicitArguments:
436 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000437 case Sema::TDK_Underqualified:
Douglas Gregorec20f462010-05-08 20:07:26 +0000438 return 0;
439
440 case Sema::TDK_SubstitutionFailure:
441 return static_cast<TemplateArgumentList*>(Data);
442
443 // Unhandled
444 case Sema::TDK_NonDeducedMismatch:
445 case Sema::TDK_FailedOverloadResolution:
446 break;
447 }
448
449 return 0;
450}
451
Douglas Gregora9333192010-05-08 17:41:32 +0000452const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
453 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
454 case Sema::TDK_Success:
455 case Sema::TDK_InstantiationDepth:
456 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000457 case Sema::TDK_TooManyArguments:
458 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000459 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000460 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000461 return 0;
462
Douglas Gregora9333192010-05-08 17:41:32 +0000463 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000464 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000465 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
466
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000467 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000468 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000469 case Sema::TDK_FailedOverloadResolution:
470 break;
471 }
472
473 return 0;
474}
475
476const TemplateArgument *
477OverloadCandidate::DeductionFailureInfo::getSecondArg() {
478 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
479 case Sema::TDK_Success:
480 case Sema::TDK_InstantiationDepth:
481 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000482 case Sema::TDK_TooManyArguments:
483 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000484 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000485 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000486 return 0;
487
Douglas Gregora9333192010-05-08 17:41:32 +0000488 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000489 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000490 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
491
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000492 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000493 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000494 case Sema::TDK_FailedOverloadResolution:
495 break;
496 }
497
498 return 0;
499}
500
501void OverloadCandidateSet::clear() {
Douglas Gregora9333192010-05-08 17:41:32 +0000502 inherited::clear();
503 Functions.clear();
504}
505
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000506// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000507// overload of the declarations in Old. This routine returns false if
508// New and Old cannot be overloaded, e.g., if New has the same
509// signature as some function in Old (C++ 1.3.10) or if the Old
510// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000511// it does return false, MatchedDecl will point to the decl that New
512// cannot be overloaded with. This decl may be a UsingShadowDecl on
513// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000514//
515// Example: Given the following input:
516//
517// void f(int, float); // #1
518// void f(int, int); // #2
519// int f(int, int); // #3
520//
521// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000522// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000523//
John McCall51fa86f2009-12-02 08:47:38 +0000524// When we process #2, Old contains only the FunctionDecl for #1. By
525// comparing the parameter types, we see that #1 and #2 are overloaded
526// (since they have different signatures), so this routine returns
527// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000528//
John McCall51fa86f2009-12-02 08:47:38 +0000529// When we process #3, Old is an overload set containing #1 and #2. We
530// compare the signatures of #3 to #1 (they're overloaded, so we do
531// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
532// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000533// signature), IsOverload returns false and MatchedDecl will be set to
534// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000535//
536// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
537// into a class by a using declaration. The rules for whether to hide
538// shadow declarations ignore some properties which otherwise figure
539// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000540Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000541Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
542 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000543 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000544 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000545 NamedDecl *OldD = *I;
546
547 bool OldIsUsingDecl = false;
548 if (isa<UsingShadowDecl>(OldD)) {
549 OldIsUsingDecl = true;
550
551 // We can always introduce two using declarations into the same
552 // context, even if they have identical signatures.
553 if (NewIsUsingDecl) continue;
554
555 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
556 }
557
558 // If either declaration was introduced by a using declaration,
559 // we'll need to use slightly different rules for matching.
560 // Essentially, these rules are the normal rules, except that
561 // function templates hide function templates with different
562 // return types or template parameter lists.
563 bool UseMemberUsingDeclRules =
564 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
565
John McCall51fa86f2009-12-02 08:47:38 +0000566 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000567 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
568 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
569 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
570 continue;
571 }
572
John McCall871b2e72009-12-09 03:35:25 +0000573 Match = *I;
574 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000575 }
John McCall51fa86f2009-12-02 08:47:38 +0000576 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000577 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
578 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
579 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
580 continue;
581 }
582
John McCall871b2e72009-12-09 03:35:25 +0000583 Match = *I;
584 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000585 }
John McCall9f54ad42009-12-10 09:41:52 +0000586 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
587 // We can overload with these, which can show up when doing
588 // redeclaration checks for UsingDecls.
589 assert(Old.getLookupKind() == LookupUsingDeclName);
590 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
591 // Optimistically assume that an unresolved using decl will
592 // overload; if it doesn't, we'll have to diagnose during
593 // template instantiation.
594 } else {
John McCall68263142009-11-18 22:49:29 +0000595 // (C++ 13p1):
596 // Only function declarations can be overloaded; object and type
597 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000598 Match = *I;
599 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000600 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000601 }
John McCall68263142009-11-18 22:49:29 +0000602
John McCall871b2e72009-12-09 03:35:25 +0000603 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000604}
605
John McCallad00b772010-06-16 08:42:20 +0000606bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
607 bool UseUsingDeclRules) {
John McCall7b492022010-08-12 07:09:11 +0000608 // If both of the functions are extern "C", then they are not
609 // overloads.
610 if (Old->isExternC() && New->isExternC())
611 return false;
612
John McCall68263142009-11-18 22:49:29 +0000613 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
614 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
615
616 // C++ [temp.fct]p2:
617 // A function template can be overloaded with other function templates
618 // and with normal (non-template) functions.
619 if ((OldTemplate == 0) != (NewTemplate == 0))
620 return true;
621
622 // Is the function New an overload of the function Old?
623 QualType OldQType = Context.getCanonicalType(Old->getType());
624 QualType NewQType = Context.getCanonicalType(New->getType());
625
626 // Compare the signatures (C++ 1.3.10) of the two functions to
627 // determine whether they are overloads. If we find any mismatch
628 // in the signature, they are overloads.
629
630 // If either of these functions is a K&R-style function (no
631 // prototype), then we consider them to have matching signatures.
632 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
633 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
634 return false;
635
636 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
637 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
638
639 // The signature of a function includes the types of its
640 // parameters (C++ 1.3.10), which includes the presence or absence
641 // of the ellipsis; see C++ DR 357).
642 if (OldQType != NewQType &&
643 (OldType->getNumArgs() != NewType->getNumArgs() ||
644 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000645 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000646 return true;
647
648 // C++ [temp.over.link]p4:
649 // The signature of a function template consists of its function
650 // signature, its return type and its template parameter list. The names
651 // of the template parameters are significant only for establishing the
652 // relationship between the template parameters and the rest of the
653 // signature.
654 //
655 // We check the return type and template parameter lists for function
656 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +0000657 //
658 // However, we don't consider either of these when deciding whether
659 // a member introduced by a shadow declaration is hidden.
660 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +0000661 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
662 OldTemplate->getTemplateParameters(),
663 false, TPL_TemplateMatch) ||
664 OldType->getResultType() != NewType->getResultType()))
665 return true;
666
667 // If the function is a class member, its signature includes the
668 // cv-qualifiers (if any) on the function itself.
669 //
670 // As part of this, also check whether one of the member functions
671 // is static, in which case they are not overloads (C++
672 // 13.1p2). While not part of the definition of the signature,
673 // this check is important to determine whether these functions
674 // can be overloaded.
675 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
676 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
677 if (OldMethod && NewMethod &&
678 !OldMethod->isStatic() && !NewMethod->isStatic() &&
679 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
680 return true;
681
682 // The signatures match; this is not an overload.
683 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000684}
685
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000686/// TryImplicitConversion - Attempt to perform an implicit conversion
687/// from the given expression (Expr) to the given type (ToType). This
688/// function returns an implicit conversion sequence that can be used
689/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000690///
691/// void f(float f);
692/// void g(int i) { f(i); }
693///
694/// this routine would produce an implicit conversion sequence to
695/// describe the initialization of f from i, which will be a standard
696/// conversion sequence containing an lvalue-to-rvalue conversion (C++
697/// 4.1) followed by a floating-integral conversion (C++ 4.9).
698//
699/// Note that this routine only determines how the conversion can be
700/// performed; it does not actually perform the conversion. As such,
701/// it will not produce any diagnostics if no conversion is available,
702/// but will instead return an implicit conversion sequence of kind
703/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000704///
705/// If @p SuppressUserConversions, then user-defined conversions are
706/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000707/// If @p AllowExplicit, then explicit user-defined conversions are
708/// permitted.
John McCall120d63c2010-08-24 20:38:10 +0000709static ImplicitConversionSequence
710TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
711 bool SuppressUserConversions,
712 bool AllowExplicit,
713 bool InOverloadResolution) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000714 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +0000715 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
716 ICS.Standard)) {
John McCall1d318332010-01-12 00:44:57 +0000717 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +0000718 return ICS;
719 }
720
John McCall120d63c2010-08-24 20:38:10 +0000721 if (!S.getLangOptions().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +0000722 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +0000723 return ICS;
724 }
725
Douglas Gregor604eb652010-08-11 02:15:33 +0000726 // C++ [over.ics.user]p4:
727 // A conversion of an expression of class type to the same class
728 // type is given Exact Match rank, and a conversion of an
729 // expression of class type to a base class of that type is
730 // given Conversion rank, in spite of the fact that a copy/move
731 // constructor (i.e., a user-defined conversion function) is
732 // called for those cases.
733 QualType FromType = From->getType();
734 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +0000735 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
736 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000737 ICS.setStandard();
738 ICS.Standard.setAsIdentityConversion();
739 ICS.Standard.setFromType(FromType);
740 ICS.Standard.setAllToTypes(ToType);
741
742 // We don't actually check at this point whether there is a valid
743 // copy/move constructor, since overloading just assumes that it
744 // exists. When we actually perform initialization, we'll find the
745 // appropriate constructor to copy the returned object, if needed.
746 ICS.Standard.CopyConstructor = 0;
Douglas Gregor604eb652010-08-11 02:15:33 +0000747
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000748 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +0000749 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000750 ICS.Standard.Second = ICK_Derived_To_Base;
Douglas Gregor604eb652010-08-11 02:15:33 +0000751
752 return ICS;
753 }
754
755 if (SuppressUserConversions) {
756 // We're not in the case above, so there is no conversion that
757 // we can perform.
758 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000759 return ICS;
760 }
761
762 // Attempt user-defined conversion.
John McCall5769d612010-02-08 23:07:23 +0000763 OverloadCandidateSet Conversions(From->getExprLoc());
764 OverloadingResult UserDefResult
John McCall120d63c2010-08-24 20:38:10 +0000765 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000766 AllowExplicit);
John McCall5769d612010-02-08 23:07:23 +0000767
768 if (UserDefResult == OR_Success) {
John McCall1d318332010-01-12 00:44:57 +0000769 ICS.setUserDefined();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000770 // C++ [over.ics.user]p4:
771 // A conversion of an expression of class type to the same class
772 // type is given Exact Match rank, and a conversion of an
773 // expression of class type to a base class of that type is
774 // given Conversion rank, in spite of the fact that a copy
775 // constructor (i.e., a user-defined conversion function) is
776 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000777 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000778 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000779 QualType FromCanon
John McCall120d63c2010-08-24 20:38:10 +0000780 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
781 QualType ToCanon
782 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor9e9199d2009-12-22 00:34:07 +0000783 if (Constructor->isCopyConstructor() &&
John McCall120d63c2010-08-24 20:38:10 +0000784 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000785 // Turn this into a "standard" conversion sequence, so that it
786 // gets ranked with standard conversion sequences.
John McCall1d318332010-01-12 00:44:57 +0000787 ICS.setStandard();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000788 ICS.Standard.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +0000789 ICS.Standard.setFromType(From->getType());
Douglas Gregorad323a82010-01-27 03:51:04 +0000790 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000791 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000792 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000793 ICS.Standard.Second = ICK_Derived_To_Base;
794 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000795 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000796
797 // C++ [over.best.ics]p4:
798 // However, when considering the argument of a user-defined
799 // conversion function that is a candidate by 13.3.1.3 when
800 // invoked for the copying of the temporary in the second step
801 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
802 // 13.3.1.6 in all cases, only standard conversion sequences and
803 // ellipsis conversion sequences are allowed.
John McCalladbb8f82010-01-13 09:16:55 +0000804 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCallb1bdc622010-02-25 01:37:24 +0000805 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCalladbb8f82010-01-13 09:16:55 +0000806 }
John McCallcefd3ad2010-01-13 22:30:33 +0000807 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall1d318332010-01-12 00:44:57 +0000808 ICS.setAmbiguous();
809 ICS.Ambiguous.setFromType(From->getType());
810 ICS.Ambiguous.setToType(ToType);
811 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
812 Cand != Conversions.end(); ++Cand)
813 if (Cand->Viable)
814 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000815 } else {
John McCallb1bdc622010-02-25 01:37:24 +0000816 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000817 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000818
819 return ICS;
820}
821
John McCall120d63c2010-08-24 20:38:10 +0000822bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
823 const InitializedEntity &Entity,
824 Expr *Initializer,
825 bool SuppressUserConversions,
826 bool AllowExplicitConversions,
827 bool InOverloadResolution) {
828 ImplicitConversionSequence ICS
829 = clang::TryImplicitConversion(*this, Initializer, Entity.getType(),
830 SuppressUserConversions,
831 AllowExplicitConversions,
832 InOverloadResolution);
833 if (ICS.isBad()) return true;
834
835 // Perform the actual conversion.
836 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
837 return false;
838}
839
Douglas Gregor575c63a2010-04-16 22:27:05 +0000840/// PerformImplicitConversion - Perform an implicit conversion of the
841/// expression From to the type ToType. Returns true if there was an
842/// error, false otherwise. The expression From is replaced with the
843/// converted expression. Flavor is the kind of conversion we're
844/// performing, used in the error message. If @p AllowExplicit,
845/// explicit user-defined conversions are permitted.
846bool
847Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
848 AssignmentAction Action, bool AllowExplicit) {
849 ImplicitConversionSequence ICS;
850 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
851}
852
853bool
854Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
855 AssignmentAction Action, bool AllowExplicit,
856 ImplicitConversionSequence& ICS) {
John McCall120d63c2010-08-24 20:38:10 +0000857 ICS = clang::TryImplicitConversion(*this, From, ToType,
858 /*SuppressUserConversions=*/false,
859 AllowExplicit,
860 /*InOverloadResolution=*/false);
Douglas Gregor575c63a2010-04-16 22:27:05 +0000861 return PerformImplicitConversion(From, ToType, ICS, Action);
862}
863
Douglas Gregor43c79c22009-12-09 00:47:37 +0000864/// \brief Determine whether the conversion from FromType to ToType is a valid
865/// conversion that strips "noreturn" off the nested function type.
866static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
867 QualType ToType, QualType &ResultTy) {
868 if (Context.hasSameUnqualifiedType(FromType, ToType))
869 return false;
870
871 // Strip the noreturn off the type we're converting from; noreturn can
872 // safely be removed.
873 FromType = Context.getNoReturnType(FromType, false);
874 if (!Context.hasSameUnqualifiedType(FromType, ToType))
875 return false;
876
877 ResultTy = FromType;
878 return true;
879}
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000880
881/// \brief Determine whether the conversion from FromType to ToType is a valid
882/// vector conversion.
883///
884/// \param ICK Will be set to the vector conversion kind, if this is a vector
885/// conversion.
886static bool IsVectorConversion(ASTContext &Context, QualType FromType,
887 QualType ToType, ImplicitConversionKind &ICK) {
888 // We need at least one of these types to be a vector type to have a vector
889 // conversion.
890 if (!ToType->isVectorType() && !FromType->isVectorType())
891 return false;
892
893 // Identical types require no conversions.
894 if (Context.hasSameUnqualifiedType(FromType, ToType))
895 return false;
896
897 // There are no conversions between extended vector types, only identity.
898 if (ToType->isExtVectorType()) {
899 // There are no conversions between extended vector types other than the
900 // identity conversion.
901 if (FromType->isExtVectorType())
902 return false;
903
904 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +0000905 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000906 ICK = ICK_Vector_Splat;
907 return true;
908 }
909 }
Douglas Gregor255210e2010-08-06 10:14:59 +0000910
911 // We can perform the conversion between vector types in the following cases:
912 // 1)vector types are equivalent AltiVec and GCC vector types
913 // 2)lax vector conversions are permitted and the vector types are of the
914 // same size
915 if (ToType->isVectorType() && FromType->isVectorType()) {
916 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruthc45eb9c2010-08-08 05:02:51 +0000917 (Context.getLangOptions().LaxVectorConversions &&
918 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +0000919 ICK = ICK_Vector_Conversion;
920 return true;
921 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000922 }
Douglas Gregor255210e2010-08-06 10:14:59 +0000923
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000924 return false;
925}
Douglas Gregor43c79c22009-12-09 00:47:37 +0000926
Douglas Gregor60d62c22008-10-31 16:23:19 +0000927/// IsStandardConversion - Determines whether there is a standard
928/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
929/// expression From to the type ToType. Standard conversion sequences
930/// only consider non-class types; for conversions that involve class
931/// types, use TryImplicitConversion. If a conversion exists, SCS will
932/// contain the standard conversion sequence required to perform this
933/// conversion and this routine will return true. Otherwise, this
934/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +0000935static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
936 bool InOverloadResolution,
937 StandardConversionSequence &SCS) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000938 QualType FromType = From->getType();
John McCall120d63c2010-08-24 20:38:10 +0000939
Douglas Gregor60d62c22008-10-31 16:23:19 +0000940 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000941 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +0000942 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000943 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +0000944 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000945 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000946
Douglas Gregorf9201e02009-02-11 23:02:49 +0000947 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +0000948 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +0000949 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall120d63c2010-08-24 20:38:10 +0000950 if (S.getLangOptions().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000951 return false;
952
Mike Stump1eb44332009-09-09 15:08:12 +0000953 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000954 }
955
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000956 // The first conversion can be an lvalue-to-rvalue conversion,
957 // array-to-pointer conversion, or function-to-pointer conversion
958 // (C++ 4p1).
959
John McCall120d63c2010-08-24 20:38:10 +0000960 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000961 DeclAccessPair AccessPair;
962 if (FunctionDecl *Fn
John McCall120d63c2010-08-24 20:38:10 +0000963 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
964 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000965 // We were able to resolve the address of the overloaded function,
966 // so we can convert to the type of that function.
967 FromType = Fn->getType();
968 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
969 if (!Method->isStatic()) {
970 Type *ClassType
John McCall120d63c2010-08-24 20:38:10 +0000971 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
972 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000973 }
974 }
975
976 // If the "from" expression takes the address of the overloaded
977 // function, update the type of the resulting expression accordingly.
978 if (FromType->getAs<FunctionType>())
979 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
John McCall2de56d12010-08-25 11:45:40 +0000980 if (UnOp->getOpcode() == UO_AddrOf)
John McCall120d63c2010-08-24 20:38:10 +0000981 FromType = S.Context.getPointerType(FromType);
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000982
983 // Check that we've computed the proper type after overload resolution.
John McCall120d63c2010-08-24 20:38:10 +0000984 assert(S.Context.hasSameType(FromType,
985 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000986 } else {
987 return false;
988 }
989 }
Mike Stump1eb44332009-09-09 15:08:12 +0000990 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000991 // An lvalue (3.10) of a non-function, non-array type T can be
992 // converted to an rvalue.
John McCall120d63c2010-08-24 20:38:10 +0000993 Expr::isLvalueResult argIsLvalue = From->isLvalue(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000994 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000995 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +0000996 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000997 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000998
999 // If T is a non-class type, the type of the rvalue is the
1000 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001001 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1002 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001003 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001004 } else if (FromType->isArrayType()) {
1005 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001006 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001007
1008 // An lvalue or rvalue of type "array of N T" or "array of unknown
1009 // bound of T" can be converted to an rvalue of type "pointer to
1010 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001011 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001012
John McCall120d63c2010-08-24 20:38:10 +00001013 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001014 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001015 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001016
1017 // For the purpose of ranking in overload resolution
1018 // (13.3.3.1.1), this conversion is considered an
1019 // array-to-pointer conversion followed by a qualification
1020 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001021 SCS.Second = ICK_Identity;
1022 SCS.Third = ICK_Qualification;
Douglas Gregorad323a82010-01-27 03:51:04 +00001023 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001024 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001025 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001026 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
1027 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001028 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001029
1030 // An lvalue of function type T can be converted to an rvalue of
1031 // type "pointer to T." The result is a pointer to the
1032 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001033 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001034 } else {
1035 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001036 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001037 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001038 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001039
1040 // The second conversion can be an integral promotion, floating
1041 // point promotion, integral conversion, floating point conversion,
1042 // floating-integral conversion, pointer conversion,
1043 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001044 // For overloading in C, this can also be a "compatible-type"
1045 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001046 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001047 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001048 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001049 // The unqualified versions of the types are the same: there's no
1050 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001051 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001052 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001053 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001054 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001055 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001056 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001057 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001058 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001059 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001060 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001061 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001062 SCS.Second = ICK_Complex_Promotion;
1063 FromType = ToType.getUnqualifiedType();
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001064 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001065 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001066 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001067 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001068 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001069 } else if (FromType->isComplexType() && ToType->isComplexType()) {
1070 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001071 SCS.Second = ICK_Complex_Conversion;
1072 FromType = ToType.getUnqualifiedType();
Chandler Carruth23a370f2010-02-25 07:20:54 +00001073 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
1074 (ToType->isComplexType() && FromType->isArithmeticType())) {
1075 // Complex-real conversions (C99 6.3.1.7)
1076 SCS.Second = ICK_Complex_Real;
1077 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001078 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001079 // Floating point conversions (C++ 4.8).
1080 SCS.Second = ICK_Floating_Conversion;
1081 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001082 } else if ((FromType->isRealFloatingType() &&
John McCall120d63c2010-08-24 20:38:10 +00001083 ToType->isIntegralType(S.Context) && !ToType->isBooleanType()) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001084 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001085 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001086 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001087 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001088 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001089 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1090 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001091 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001092 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001093 SCS.IncompatibleObjC = IncompatibleObjC;
John McCall120d63c2010-08-24 20:38:10 +00001094 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1095 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001096 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001097 SCS.Second = ICK_Pointer_Member;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001098 } else if (ToType->isBooleanType() &&
1099 (FromType->isArithmeticType() ||
Fariborz Jahanian1f7711d2009-12-11 21:23:13 +00001100 FromType->isAnyPointerType() ||
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001101 FromType->isBlockPointerType() ||
1102 FromType->isMemberPointerType() ||
Douglas Gregor00619622010-06-22 23:41:02 +00001103 FromType->isNullPtrType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001104 // Boolean conversions (C++ 4.12).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001105 SCS.Second = ICK_Boolean_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001106 FromType = S.Context.BoolTy;
1107 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001108 SCS.Second = SecondICK;
1109 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001110 } else if (!S.getLangOptions().CPlusPlus &&
1111 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001112 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001113 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001114 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001115 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001116 // Treat a conversion that strips "noreturn" as an identity conversion.
1117 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001118 } else {
1119 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001120 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001121 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001122 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001123
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001124 QualType CanonFrom;
1125 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001126 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall120d63c2010-08-24 20:38:10 +00001127 if (S.IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001128 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001129 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001130 CanonFrom = S.Context.getCanonicalType(FromType);
1131 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001132 } else {
1133 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001134 SCS.Third = ICK_Identity;
1135
Mike Stump1eb44332009-09-09 15:08:12 +00001136 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001137 // [...] Any difference in top-level cv-qualification is
1138 // subsumed by the initialization itself and does not constitute
1139 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001140 CanonFrom = S.Context.getCanonicalType(FromType);
1141 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00001142 if (CanonFrom.getLocalUnqualifiedType()
1143 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001144 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1145 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001146 FromType = ToType;
1147 CanonFrom = CanonTo;
1148 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001149 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001150 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001151
1152 // If we have not converted the argument type to the parameter type,
1153 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001154 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001155 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001156
Douglas Gregor60d62c22008-10-31 16:23:19 +00001157 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001158}
1159
1160/// IsIntegralPromotion - Determines whether the conversion from the
1161/// expression From (whose potentially-adjusted type is FromType) to
1162/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1163/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001164bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001165 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001166 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001167 if (!To) {
1168 return false;
1169 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001170
1171 // An rvalue of type char, signed char, unsigned char, short int, or
1172 // unsigned short int can be converted to an rvalue of type int if
1173 // int can represent all the values of the source type; otherwise,
1174 // the source rvalue can be converted to an rvalue of type unsigned
1175 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001176 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1177 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001178 if (// We can promote any signed, promotable integer type to an int
1179 (FromType->isSignedIntegerType() ||
1180 // We can promote any unsigned integer type whose size is
1181 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001182 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001183 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001184 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001185 }
1186
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001187 return To->getKind() == BuiltinType::UInt;
1188 }
1189
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001190 // C++0x [conv.prom]p3:
1191 // A prvalue of an unscoped enumeration type whose underlying type is not
1192 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1193 // following types that can represent all the values of the enumeration
1194 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1195 // unsigned int, long int, unsigned long int, long long int, or unsigned
1196 // long long int. If none of the types in that list can represent all the
1197 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1198 // type can be converted to an rvalue a prvalue of the extended integer type
1199 // with lowest integer conversion rank (4.13) greater than the rank of long
1200 // long in which all the values of the enumeration can be represented. If
1201 // there are two such extended types, the signed one is chosen.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001202 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1203 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1204 // provided for a scoped enumeration.
1205 if (FromEnumType->getDecl()->isScoped())
1206 return false;
1207
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001208 // We have already pre-calculated the promotion type, so this is trivial.
Douglas Gregor5dde1602010-09-12 03:38:25 +00001209 if (ToType->isIntegerType() &&
1210 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall842aef82009-12-09 09:09:27 +00001211 return Context.hasSameUnqualifiedType(ToType,
1212 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001213 }
John McCall842aef82009-12-09 09:09:27 +00001214
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001215 // C++0x [conv.prom]p2:
1216 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1217 // to an rvalue a prvalue of the first of the following types that can
1218 // represent all the values of its underlying type: int, unsigned int,
1219 // long int, unsigned long int, long long int, or unsigned long long int.
1220 // If none of the types in that list can represent all the values of its
1221 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
1222 // or wchar_t can be converted to an rvalue a prvalue of its underlying
1223 // type.
1224 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1225 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001226 // Determine whether the type we're converting from is signed or
1227 // unsigned.
1228 bool FromIsSigned;
1229 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall842aef82009-12-09 09:09:27 +00001230
1231 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1232 FromIsSigned = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001233
1234 // The types we'll try to promote to, in the appropriate
1235 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001236 QualType PromoteTypes[6] = {
1237 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001238 Context.LongTy, Context.UnsignedLongTy ,
1239 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001240 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001241 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001242 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1243 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001244 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001245 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1246 // We found the type that we can promote to. If this is the
1247 // type we wanted, we have a promotion. Otherwise, no
1248 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001249 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001250 }
1251 }
1252 }
1253
1254 // An rvalue for an integral bit-field (9.6) can be converted to an
1255 // rvalue of type int if int can represent all the values of the
1256 // bit-field; otherwise, it can be converted to unsigned int if
1257 // unsigned int can represent all the values of the bit-field. If
1258 // the bit-field is larger yet, no integral promotion applies to
1259 // it. If the bit-field has an enumerated type, it is treated as any
1260 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001261 // FIXME: We should delay checking of bit-fields until we actually perform the
1262 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001263 using llvm::APSInt;
1264 if (From)
1265 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001266 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001267 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001268 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1269 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1270 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001271
Douglas Gregor86f19402008-12-20 23:49:58 +00001272 // Are we promoting to an int from a bitfield that fits in an int?
1273 if (BitWidth < ToSize ||
1274 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1275 return To->getKind() == BuiltinType::Int;
1276 }
Mike Stump1eb44332009-09-09 15:08:12 +00001277
Douglas Gregor86f19402008-12-20 23:49:58 +00001278 // Are we promoting to an unsigned int from an unsigned bitfield
1279 // that fits into an unsigned int?
1280 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1281 return To->getKind() == BuiltinType::UInt;
1282 }
Mike Stump1eb44332009-09-09 15:08:12 +00001283
Douglas Gregor86f19402008-12-20 23:49:58 +00001284 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001285 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001286 }
Mike Stump1eb44332009-09-09 15:08:12 +00001287
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001288 // An rvalue of type bool can be converted to an rvalue of type int,
1289 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001290 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001291 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001292 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001293
1294 return false;
1295}
1296
1297/// IsFloatingPointPromotion - Determines whether the conversion from
1298/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1299/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001300bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001301 /// An rvalue of type float can be converted to an rvalue of type
1302 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +00001303 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1304 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001305 if (FromBuiltin->getKind() == BuiltinType::Float &&
1306 ToBuiltin->getKind() == BuiltinType::Double)
1307 return true;
1308
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001309 // C99 6.3.1.5p1:
1310 // When a float is promoted to double or long double, or a
1311 // double is promoted to long double [...].
1312 if (!getLangOptions().CPlusPlus &&
1313 (FromBuiltin->getKind() == BuiltinType::Float ||
1314 FromBuiltin->getKind() == BuiltinType::Double) &&
1315 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1316 return true;
1317 }
1318
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001319 return false;
1320}
1321
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001322/// \brief Determine if a conversion is a complex promotion.
1323///
1324/// A complex promotion is defined as a complex -> complex conversion
1325/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001326/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001327bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001328 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001329 if (!FromComplex)
1330 return false;
1331
John McCall183700f2009-09-21 23:43:11 +00001332 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001333 if (!ToComplex)
1334 return false;
1335
1336 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001337 ToComplex->getElementType()) ||
1338 IsIntegralPromotion(0, FromComplex->getElementType(),
1339 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001340}
1341
Douglas Gregorcb7de522008-11-26 23:31:11 +00001342/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1343/// the pointer type FromPtr to a pointer to type ToPointee, with the
1344/// same type qualifiers as FromPtr has on its pointee type. ToType,
1345/// if non-empty, will be a pointer to ToType that may or may not have
1346/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +00001347static QualType
1348BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001349 QualType ToPointee, QualType ToType,
1350 ASTContext &Context) {
1351 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1352 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001353 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001354
1355 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001356 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001357 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001358 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001359 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001360
1361 // Build a pointer to ToPointee. It has the right qualifiers
1362 // already.
1363 return Context.getPointerType(ToPointee);
1364 }
1365
1366 // Just build a canonical type that has the right qualifiers.
John McCall0953e762009-09-24 19:53:00 +00001367 return Context.getPointerType(
Douglas Gregora4923eb2009-11-16 21:35:15 +00001368 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1369 Quals));
Douglas Gregorcb7de522008-11-26 23:31:11 +00001370}
1371
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001372/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1373/// the FromType, which is an objective-c pointer, to ToType, which may or may
1374/// not have the right set of qualifiers.
1375static QualType
1376BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1377 QualType ToType,
1378 ASTContext &Context) {
1379 QualType CanonFromType = Context.getCanonicalType(FromType);
1380 QualType CanonToType = Context.getCanonicalType(ToType);
1381 Qualifiers Quals = CanonFromType.getQualifiers();
1382
1383 // Exact qualifier match -> return the pointer type we're converting to.
1384 if (CanonToType.getLocalQualifiers() == Quals)
1385 return ToType;
1386
1387 // Just build a canonical type that has the right qualifiers.
1388 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1389}
1390
Mike Stump1eb44332009-09-09 15:08:12 +00001391static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001392 bool InOverloadResolution,
1393 ASTContext &Context) {
1394 // Handle value-dependent integral null pointer constants correctly.
1395 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1396 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001397 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001398 return !InOverloadResolution;
1399
Douglas Gregorce940492009-09-25 04:25:58 +00001400 return Expr->isNullPointerConstant(Context,
1401 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1402 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001403}
Mike Stump1eb44332009-09-09 15:08:12 +00001404
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001405/// IsPointerConversion - Determines whether the conversion of the
1406/// expression From, which has the (possibly adjusted) type FromType,
1407/// can be converted to the type ToType via a pointer conversion (C++
1408/// 4.10). If so, returns true and places the converted type (that
1409/// might differ from ToType in its cv-qualifiers at some level) into
1410/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001411///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001412/// This routine also supports conversions to and from block pointers
1413/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1414/// pointers to interfaces. FIXME: Once we've determined the
1415/// appropriate overloading rules for Objective-C, we may want to
1416/// split the Objective-C checks into a different routine; however,
1417/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001418/// conversions, so for now they live here. IncompatibleObjC will be
1419/// set if the conversion is an allowed Objective-C conversion that
1420/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001421bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001422 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001423 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001424 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001425 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +00001426 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1427 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001428
Mike Stump1eb44332009-09-09 15:08:12 +00001429 // Conversion from a null pointer constant to any Objective-C pointer type.
1430 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001431 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001432 ConvertedType = ToType;
1433 return true;
1434 }
1435
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001436 // Blocks: Block pointers can be converted to void*.
1437 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001438 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001439 ConvertedType = ToType;
1440 return true;
1441 }
1442 // Blocks: A null pointer constant can be converted to a block
1443 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001444 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001445 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001446 ConvertedType = ToType;
1447 return true;
1448 }
1449
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001450 // If the left-hand-side is nullptr_t, the right side can be a null
1451 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001452 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001453 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001454 ConvertedType = ToType;
1455 return true;
1456 }
1457
Ted Kremenek6217b802009-07-29 21:53:49 +00001458 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001459 if (!ToTypePtr)
1460 return false;
1461
1462 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001463 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001464 ConvertedType = ToType;
1465 return true;
1466 }
Sebastian Redl07779722008-10-31 14:43:28 +00001467
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001468 // Beyond this point, both types need to be pointers
1469 // , including objective-c pointers.
1470 QualType ToPointeeType = ToTypePtr->getPointeeType();
1471 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1472 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1473 ToType, Context);
1474 return true;
1475
1476 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001477 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001478 if (!FromTypePtr)
1479 return false;
1480
1481 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001482
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00001483 // If the unqualified pointee types are the same, this can't be a
1484 // pointer conversion, so don't do all of the work below.
1485 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1486 return false;
1487
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001488 // An rvalue of type "pointer to cv T," where T is an object type,
1489 // can be converted to an rvalue of type "pointer to cv void" (C++
1490 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00001491 if (FromPointeeType->isIncompleteOrObjectType() &&
1492 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001493 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001494 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001495 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001496 return true;
1497 }
1498
Douglas Gregorf9201e02009-02-11 23:02:49 +00001499 // When we're overloading in C, we allow a special kind of pointer
1500 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001501 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001502 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001503 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001504 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001505 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001506 return true;
1507 }
1508
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001509 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001510 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001511 // An rvalue of type "pointer to cv D," where D is a class type,
1512 // can be converted to an rvalue of type "pointer to cv B," where
1513 // B is a base class (clause 10) of D. If B is an inaccessible
1514 // (clause 11) or ambiguous (10.2) base class of D, a program that
1515 // necessitates this conversion is ill-formed. The result of the
1516 // conversion is a pointer to the base class sub-object of the
1517 // derived class object. The null pointer value is converted to
1518 // the null pointer value of the destination type.
1519 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001520 // Note that we do not check for ambiguity or inaccessibility
1521 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001522 if (getLangOptions().CPlusPlus &&
1523 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001524 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001525 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001526 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001527 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001528 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001529 ToType, Context);
1530 return true;
1531 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001532
Douglas Gregorc7887512008-12-19 19:13:09 +00001533 return false;
1534}
1535
1536/// isObjCPointerConversion - Determines whether this is an
1537/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1538/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001539bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001540 QualType& ConvertedType,
1541 bool &IncompatibleObjC) {
1542 if (!getLangOptions().ObjC1)
1543 return false;
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001544
Steve Naroff14108da2009-07-10 23:34:53 +00001545 // First, we handle all conversions on ObjC object pointer types.
John McCall183700f2009-09-21 23:43:11 +00001546 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001547 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001548 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001549
Steve Naroff14108da2009-07-10 23:34:53 +00001550 if (ToObjCPtr && FromObjCPtr) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00001551 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001552 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001553 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001554 ConvertedType = ToType;
1555 return true;
1556 }
1557 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001558 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001559 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001560 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001561 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001562 ConvertedType = ToType;
1563 return true;
1564 }
1565 // Objective C++: We're able to convert from a pointer to an
1566 // interface to a pointer to a different interface.
1567 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00001568 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1569 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1570 if (getLangOptions().CPlusPlus && LHS && RHS &&
1571 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1572 FromObjCPtr->getPointeeType()))
1573 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00001574 ConvertedType = ToType;
1575 return true;
1576 }
1577
1578 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1579 // Okay: this is some kind of implicit downcast of Objective-C
1580 // interfaces, which is permitted. However, we're going to
1581 // complain about it.
1582 IncompatibleObjC = true;
1583 ConvertedType = FromType;
1584 return true;
1585 }
Mike Stump1eb44332009-09-09 15:08:12 +00001586 }
Steve Naroff14108da2009-07-10 23:34:53 +00001587 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001588 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001589 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001590 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001591 else if (const BlockPointerType *ToBlockPtr =
1592 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00001593 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001594 // to a block pointer type.
1595 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1596 ConvertedType = ToType;
1597 return true;
1598 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001599 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001600 }
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001601 else if (FromType->getAs<BlockPointerType>() &&
1602 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1603 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00001604 // pointer to any object.
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001605 ConvertedType = ToType;
1606 return true;
1607 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001608 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001609 return false;
1610
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001611 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001612 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001613 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001614 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001615 FromPointeeType = FromBlockPtr->getPointeeType();
1616 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001617 return false;
1618
Douglas Gregorc7887512008-12-19 19:13:09 +00001619 // If we have pointers to pointers, recursively check whether this
1620 // is an Objective-C conversion.
1621 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1622 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1623 IncompatibleObjC)) {
1624 // We always complain about this conversion.
1625 IncompatibleObjC = true;
1626 ConvertedType = ToType;
1627 return true;
1628 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001629 // Allow conversion of pointee being objective-c pointer to another one;
1630 // as in I* to id.
1631 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1632 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1633 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1634 IncompatibleObjC)) {
1635 ConvertedType = ToType;
1636 return true;
1637 }
1638
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001639 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001640 // differences in the argument and result types are in Objective-C
1641 // pointer conversions. If so, we permit the conversion (but
1642 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001643 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001644 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001645 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001646 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001647 if (FromFunctionType && ToFunctionType) {
1648 // If the function types are exactly the same, this isn't an
1649 // Objective-C pointer conversion.
1650 if (Context.getCanonicalType(FromPointeeType)
1651 == Context.getCanonicalType(ToPointeeType))
1652 return false;
1653
1654 // Perform the quick checks that will tell us whether these
1655 // function types are obviously different.
1656 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1657 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1658 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1659 return false;
1660
1661 bool HasObjCConversion = false;
1662 if (Context.getCanonicalType(FromFunctionType->getResultType())
1663 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1664 // Okay, the types match exactly. Nothing to do.
1665 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1666 ToFunctionType->getResultType(),
1667 ConvertedType, IncompatibleObjC)) {
1668 // Okay, we have an Objective-C pointer conversion.
1669 HasObjCConversion = true;
1670 } else {
1671 // Function types are too different. Abort.
1672 return false;
1673 }
Mike Stump1eb44332009-09-09 15:08:12 +00001674
Douglas Gregorc7887512008-12-19 19:13:09 +00001675 // Check argument types.
1676 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1677 ArgIdx != NumArgs; ++ArgIdx) {
1678 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1679 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1680 if (Context.getCanonicalType(FromArgType)
1681 == Context.getCanonicalType(ToArgType)) {
1682 // Okay, the types match exactly. Nothing to do.
1683 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1684 ConvertedType, IncompatibleObjC)) {
1685 // Okay, we have an Objective-C pointer conversion.
1686 HasObjCConversion = true;
1687 } else {
1688 // Argument types are too different. Abort.
1689 return false;
1690 }
1691 }
1692
1693 if (HasObjCConversion) {
1694 // We had an Objective-C conversion. Allow this pointer
1695 // conversion, but complain about it.
1696 ConvertedType = ToType;
1697 IncompatibleObjC = true;
1698 return true;
1699 }
1700 }
1701
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001702 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001703}
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001704
1705/// FunctionArgTypesAreEqual - This routine checks two function proto types
1706/// for equlity of their argument types. Caller has already checked that
1707/// they have same number of arguments. This routine assumes that Objective-C
1708/// pointer types which only differ in their protocol qualifiers are equal.
1709bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1710 FunctionProtoType* NewType){
1711 if (!getLangOptions().ObjC1)
1712 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1713 NewType->arg_type_begin());
1714
1715 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1716 N = NewType->arg_type_begin(),
1717 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1718 QualType ToType = (*O);
1719 QualType FromType = (*N);
1720 if (ToType != FromType) {
1721 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1722 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00001723 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1724 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1725 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1726 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001727 continue;
1728 }
John McCallc12c5bb2010-05-15 11:32:37 +00001729 else if (const ObjCObjectPointerType *PTTo =
1730 ToType->getAs<ObjCObjectPointerType>()) {
1731 if (const ObjCObjectPointerType *PTFr =
1732 FromType->getAs<ObjCObjectPointerType>())
1733 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1734 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001735 }
1736 return false;
1737 }
1738 }
1739 return true;
1740}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001741
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001742/// CheckPointerConversion - Check the pointer conversion from the
1743/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001744/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001745/// conversions for which IsPointerConversion has already returned
1746/// true. It returns true and produces a diagnostic if there was an
1747/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001748bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00001749 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001750 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001751 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001752 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00001753 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001754
Douglas Gregord7a95972010-06-08 17:35:15 +00001755 if (CXXBoolLiteralExpr* LitBool
1756 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00001757 if (!IsCStyleOrFunctionalCast && LitBool->getValue() == false)
Douglas Gregord7a95972010-06-08 17:35:15 +00001758 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1759 << ToType;
1760
Ted Kremenek6217b802009-07-29 21:53:49 +00001761 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1762 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001763 QualType FromPointeeType = FromPtrType->getPointeeType(),
1764 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001765
Douglas Gregor5fccd362010-03-03 23:55:11 +00001766 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1767 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001768 // We must have a derived-to-base conversion. Check an
1769 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001770 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1771 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001772 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001773 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001774 return true;
1775
1776 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00001777 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001778 }
1779 }
Mike Stump1eb44332009-09-09 15:08:12 +00001780 if (const ObjCObjectPointerType *FromPtrType =
John McCall183700f2009-09-21 23:43:11 +00001781 FromType->getAs<ObjCObjectPointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001782 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00001783 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001784 // Objective-C++ conversions are always okay.
1785 // FIXME: We should have a different class of conversions for the
1786 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001787 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001788 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001789
Steve Naroff14108da2009-07-10 23:34:53 +00001790 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001791 return false;
1792}
1793
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001794/// IsMemberPointerConversion - Determines whether the conversion of the
1795/// expression From, which has the (possibly adjusted) type FromType, can be
1796/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1797/// If so, returns true and places the converted type (that might differ from
1798/// ToType in its cv-qualifiers at some level) into ConvertedType.
1799bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregorce940492009-09-25 04:25:58 +00001800 QualType ToType,
1801 bool InOverloadResolution,
1802 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001803 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001804 if (!ToTypePtr)
1805 return false;
1806
1807 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00001808 if (From->isNullPointerConstant(Context,
1809 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1810 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001811 ConvertedType = ToType;
1812 return true;
1813 }
1814
1815 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001816 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001817 if (!FromTypePtr)
1818 return false;
1819
1820 // A pointer to member of B can be converted to a pointer to member of D,
1821 // where D is derived from B (C++ 4.11p2).
1822 QualType FromClass(FromTypePtr->getClass(), 0);
1823 QualType ToClass(ToTypePtr->getClass(), 0);
1824 // FIXME: What happens when these are dependent? Is this function even called?
1825
1826 if (IsDerivedFrom(ToClass, FromClass)) {
1827 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1828 ToClass.getTypePtr());
1829 return true;
1830 }
1831
1832 return false;
1833}
Douglas Gregor43c79c22009-12-09 00:47:37 +00001834
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001835/// CheckMemberPointerConversion - Check the member pointer conversion from the
1836/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00001837/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001838/// for which IsMemberPointerConversion has already returned true. It returns
1839/// true and produces a diagnostic if there was an error, or returns false
1840/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001841bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00001842 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001843 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001844 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001845 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001846 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001847 if (!FromPtrType) {
1848 // This must be a null pointer to member pointer conversion
Douglas Gregorce940492009-09-25 04:25:58 +00001849 assert(From->isNullPointerConstant(Context,
1850 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001851 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00001852 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001853 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001854 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001855
Ted Kremenek6217b802009-07-29 21:53:49 +00001856 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001857 assert(ToPtrType && "No member pointer cast has a target type "
1858 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001859
Sebastian Redl21593ac2009-01-28 18:33:18 +00001860 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1861 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001862
Sebastian Redl21593ac2009-01-28 18:33:18 +00001863 // FIXME: What about dependent types?
1864 assert(FromClass->isRecordType() && "Pointer into non-class.");
1865 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001866
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001867 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001868 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00001869 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1870 assert(DerivationOkay &&
1871 "Should not have been called if derivation isn't OK.");
1872 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001873
Sebastian Redl21593ac2009-01-28 18:33:18 +00001874 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1875 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001876 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1877 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1878 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1879 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001880 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001881
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001882 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001883 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1884 << FromClass << ToClass << QualType(VBase, 0)
1885 << From->getSourceRange();
1886 return true;
1887 }
1888
John McCall6b2accb2010-02-10 09:31:12 +00001889 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00001890 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1891 Paths.front(),
1892 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00001893
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001894 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001895 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00001896 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001897 return false;
1898}
1899
Douglas Gregor98cd5992008-10-21 23:43:52 +00001900/// IsQualificationConversion - Determines whether the conversion from
1901/// an rvalue of type FromType to ToType is a qualification conversion
1902/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001903bool
1904Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001905 FromType = Context.getCanonicalType(FromType);
1906 ToType = Context.getCanonicalType(ToType);
1907
1908 // If FromType and ToType are the same type, this is not a
1909 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00001910 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00001911 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001912
Douglas Gregor98cd5992008-10-21 23:43:52 +00001913 // (C++ 4.4p4):
1914 // A conversion can add cv-qualifiers at levels other than the first
1915 // in multi-level pointers, subject to the following rules: [...]
1916 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001917 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00001918 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001919 // Within each iteration of the loop, we check the qualifiers to
1920 // determine if this still looks like a qualification
1921 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001922 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001923 // until there are no more pointers or pointers-to-members left to
1924 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001925 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001926
1927 // -- for every j > 0, if const is in cv 1,j then const is in cv
1928 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001929 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001930 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001931
Douglas Gregor98cd5992008-10-21 23:43:52 +00001932 // -- if the cv 1,j and cv 2,j are different, then const is in
1933 // every cv for 0 < k < j.
1934 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001935 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001936 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001937
Douglas Gregor98cd5992008-10-21 23:43:52 +00001938 // Keep track of whether all prior cv-qualifiers in the "to" type
1939 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00001940 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00001941 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001942 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001943
1944 // We are left with FromType and ToType being the pointee types
1945 // after unwrapping the original FromType and ToType the same number
1946 // of types. If we unwrapped any pointers, and if FromType and
1947 // ToType have the same unqualified type (since we checked
1948 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001949 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00001950}
1951
Douglas Gregor734d9862009-01-30 23:27:23 +00001952/// Determines whether there is a user-defined conversion sequence
1953/// (C++ [over.ics.user]) that converts expression From to the type
1954/// ToType. If such a conversion exists, User will contain the
1955/// user-defined conversion sequence that performs such a conversion
1956/// and this routine will return true. Otherwise, this routine returns
1957/// false and User is unspecified.
1958///
Douglas Gregor734d9862009-01-30 23:27:23 +00001959/// \param AllowExplicit true if the conversion should consider C++0x
1960/// "explicit" conversion functions as well as non-explicit conversion
1961/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00001962static OverloadingResult
1963IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1964 UserDefinedConversionSequence& User,
1965 OverloadCandidateSet& CandidateSet,
1966 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001967 // Whether we will only visit constructors.
1968 bool ConstructorsOnly = false;
1969
1970 // If the type we are conversion to is a class type, enumerate its
1971 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00001972 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001973 // C++ [over.match.ctor]p1:
1974 // When objects of class type are direct-initialized (8.5), or
1975 // copy-initialized from an expression of the same or a
1976 // derived class type (8.5), overload resolution selects the
1977 // constructor. [...] For copy-initialization, the candidate
1978 // functions are all the converting constructors (12.3.1) of
1979 // that class. The argument list is the expression-list within
1980 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00001981 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001982 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001983 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001984 ConstructorsOnly = true;
1985
John McCall120d63c2010-08-24 20:38:10 +00001986 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag())) {
Douglas Gregor393896f2009-11-05 13:06:35 +00001987 // We're not going to find any constructors.
1988 } else if (CXXRecordDecl *ToRecordDecl
1989 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001990 DeclContext::lookup_iterator Con, ConEnd;
John McCall120d63c2010-08-24 20:38:10 +00001991 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001992 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00001993 NamedDecl *D = *Con;
1994 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1995
Douglas Gregordec06662009-08-21 18:42:58 +00001996 // Find the constructor (which may be a template).
1997 CXXConstructorDecl *Constructor = 0;
1998 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00001999 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00002000 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00002001 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00002002 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2003 else
John McCall9aa472c2010-03-19 07:35:19 +00002004 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002005
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00002006 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00002007 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00002008 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00002009 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2010 /*ExplicitArgs*/ 0,
2011 &From, 1, CandidateSet,
2012 /*SuppressUserConversions=*/
2013 !ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00002014 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00002015 // Allow one user-defined conversion when user specifies a
2016 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00002017 S.AddOverloadCandidate(Constructor, FoundDecl,
2018 &From, 1, CandidateSet,
2019 /*SuppressUserConversions=*/
2020 !ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00002021 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002022 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002023 }
2024 }
2025
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002026 // Enumerate conversion functions, if we're allowed to.
2027 if (ConstructorsOnly) {
John McCall120d63c2010-08-24 20:38:10 +00002028 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2029 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00002030 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00002031 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002032 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002033 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002034 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2035 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00002036 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002037 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002038 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00002039 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00002040 DeclAccessPair FoundDecl = I.getPair();
2041 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00002042 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2043 if (isa<UsingShadowDecl>(D))
2044 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2045
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002046 CXXConversionDecl *Conv;
2047 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00002048 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2049 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002050 else
John McCall32daa422010-03-31 01:36:47 +00002051 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002052
2053 if (AllowExplicit || !Conv->isExplicit()) {
2054 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00002055 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2056 ActingContext, From, ToType,
2057 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002058 else
John McCall120d63c2010-08-24 20:38:10 +00002059 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2060 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002061 }
2062 }
2063 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002064 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002065
2066 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002067 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00002068 case OR_Success:
2069 // Record the standard conversion we used and the conversion function.
2070 if (CXXConstructorDecl *Constructor
2071 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
2072 // C++ [over.ics.user]p1:
2073 // If the user-defined conversion is specified by a
2074 // constructor (12.3.1), the initial standard conversion
2075 // sequence converts the source type to the type required by
2076 // the argument of the constructor.
2077 //
2078 QualType ThisType = Constructor->getThisType(S.Context);
2079 if (Best->Conversions[0].isEllipsis())
2080 User.EllipsisConversion = true;
2081 else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002082 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002083 User.EllipsisConversion = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002084 }
John McCall120d63c2010-08-24 20:38:10 +00002085 User.ConversionFunction = Constructor;
2086 User.After.setAsIdentityConversion();
2087 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2088 User.After.setAllToTypes(ToType);
2089 return OR_Success;
2090 } else if (CXXConversionDecl *Conversion
2091 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2092 // C++ [over.ics.user]p1:
2093 //
2094 // [...] If the user-defined conversion is specified by a
2095 // conversion function (12.3.2), the initial standard
2096 // conversion sequence converts the source type to the
2097 // implicit object parameter of the conversion function.
2098 User.Before = Best->Conversions[0].Standard;
2099 User.ConversionFunction = Conversion;
2100 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002101
John McCall120d63c2010-08-24 20:38:10 +00002102 // C++ [over.ics.user]p2:
2103 // The second standard conversion sequence converts the
2104 // result of the user-defined conversion to the target type
2105 // for the sequence. Since an implicit conversion sequence
2106 // is an initialization, the special rules for
2107 // initialization by user-defined conversion apply when
2108 // selecting the best user-defined conversion for a
2109 // user-defined conversion sequence (see 13.3.3 and
2110 // 13.3.3.1).
2111 User.After = Best->FinalConversion;
2112 return OR_Success;
2113 } else {
2114 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002115 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002116 }
2117
John McCall120d63c2010-08-24 20:38:10 +00002118 case OR_No_Viable_Function:
2119 return OR_No_Viable_Function;
2120 case OR_Deleted:
2121 // No conversion here! We're done.
2122 return OR_Deleted;
2123
2124 case OR_Ambiguous:
2125 return OR_Ambiguous;
2126 }
2127
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002128 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002129}
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002130
2131bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002132Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002133 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00002134 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002135 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00002136 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002137 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002138 if (OvResult == OR_Ambiguous)
2139 Diag(From->getSourceRange().getBegin(),
2140 diag::err_typecheck_ambiguous_condition)
2141 << From->getType() << ToType << From->getSourceRange();
2142 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2143 Diag(From->getSourceRange().getBegin(),
2144 diag::err_typecheck_nonviable_condition)
2145 << From->getType() << ToType << From->getSourceRange();
2146 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002147 return false;
John McCall120d63c2010-08-24 20:38:10 +00002148 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002149 return true;
2150}
Douglas Gregor60d62c22008-10-31 16:23:19 +00002151
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002152/// CompareImplicitConversionSequences - Compare two implicit
2153/// conversion sequences to determine whether one is better than the
2154/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00002155static ImplicitConversionSequence::CompareKind
2156CompareImplicitConversionSequences(Sema &S,
2157 const ImplicitConversionSequence& ICS1,
2158 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002159{
2160 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2161 // conversion sequences (as defined in 13.3.3.1)
2162 // -- a standard conversion sequence (13.3.3.1.1) is a better
2163 // conversion sequence than a user-defined conversion sequence or
2164 // an ellipsis conversion sequence, and
2165 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2166 // conversion sequence than an ellipsis conversion sequence
2167 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002168 //
John McCall1d318332010-01-12 00:44:57 +00002169 // C++0x [over.best.ics]p10:
2170 // For the purpose of ranking implicit conversion sequences as
2171 // described in 13.3.3.2, the ambiguous conversion sequence is
2172 // treated as a user-defined sequence that is indistinguishable
2173 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002174 if (ICS1.getKindRank() < ICS2.getKindRank())
2175 return ImplicitConversionSequence::Better;
2176 else if (ICS2.getKindRank() < ICS1.getKindRank())
2177 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002178
Benjamin Kramerb6eee072010-04-18 12:05:54 +00002179 // The following checks require both conversion sequences to be of
2180 // the same kind.
2181 if (ICS1.getKind() != ICS2.getKind())
2182 return ImplicitConversionSequence::Indistinguishable;
2183
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002184 // Two implicit conversion sequences of the same form are
2185 // indistinguishable conversion sequences unless one of the
2186 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00002187 if (ICS1.isStandard())
John McCall120d63c2010-08-24 20:38:10 +00002188 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00002189 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002190 // User-defined conversion sequence U1 is a better conversion
2191 // sequence than another user-defined conversion sequence U2 if
2192 // they contain the same user-defined conversion function or
2193 // constructor and if the second standard conversion sequence of
2194 // U1 is better than the second standard conversion sequence of
2195 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002196 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002197 ICS2.UserDefined.ConversionFunction)
John McCall120d63c2010-08-24 20:38:10 +00002198 return CompareStandardConversionSequences(S,
2199 ICS1.UserDefined.After,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002200 ICS2.UserDefined.After);
2201 }
2202
2203 return ImplicitConversionSequence::Indistinguishable;
2204}
2205
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002206static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2207 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2208 Qualifiers Quals;
2209 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2210 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2211 }
2212
2213 return Context.hasSameUnqualifiedType(T1, T2);
2214}
2215
Douglas Gregorad323a82010-01-27 03:51:04 +00002216// Per 13.3.3.2p3, compare the given standard conversion sequences to
2217// determine if one is a proper subset of the other.
2218static ImplicitConversionSequence::CompareKind
2219compareStandardConversionSubsets(ASTContext &Context,
2220 const StandardConversionSequence& SCS1,
2221 const StandardConversionSequence& SCS2) {
2222 ImplicitConversionSequence::CompareKind Result
2223 = ImplicitConversionSequence::Indistinguishable;
2224
Douglas Gregorae65f4b2010-05-23 22:10:15 +00002225 // the identity conversion sequence is considered to be a subsequence of
2226 // any non-identity conversion sequence
2227 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2228 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2229 return ImplicitConversionSequence::Better;
2230 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2231 return ImplicitConversionSequence::Worse;
2232 }
2233
Douglas Gregorad323a82010-01-27 03:51:04 +00002234 if (SCS1.Second != SCS2.Second) {
2235 if (SCS1.Second == ICK_Identity)
2236 Result = ImplicitConversionSequence::Better;
2237 else if (SCS2.Second == ICK_Identity)
2238 Result = ImplicitConversionSequence::Worse;
2239 else
2240 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002241 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00002242 return ImplicitConversionSequence::Indistinguishable;
2243
2244 if (SCS1.Third == SCS2.Third) {
2245 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2246 : ImplicitConversionSequence::Indistinguishable;
2247 }
2248
2249 if (SCS1.Third == ICK_Identity)
2250 return Result == ImplicitConversionSequence::Worse
2251 ? ImplicitConversionSequence::Indistinguishable
2252 : ImplicitConversionSequence::Better;
2253
2254 if (SCS2.Third == ICK_Identity)
2255 return Result == ImplicitConversionSequence::Better
2256 ? ImplicitConversionSequence::Indistinguishable
2257 : ImplicitConversionSequence::Worse;
2258
2259 return ImplicitConversionSequence::Indistinguishable;
2260}
2261
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002262/// CompareStandardConversionSequences - Compare two standard
2263/// conversion sequences to determine whether one is better than the
2264/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00002265static ImplicitConversionSequence::CompareKind
2266CompareStandardConversionSequences(Sema &S,
2267 const StandardConversionSequence& SCS1,
2268 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002269{
2270 // Standard conversion sequence S1 is a better conversion sequence
2271 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2272
2273 // -- S1 is a proper subsequence of S2 (comparing the conversion
2274 // sequences in the canonical form defined by 13.3.3.1.1,
2275 // excluding any Lvalue Transformation; the identity conversion
2276 // sequence is considered to be a subsequence of any
2277 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00002278 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00002279 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00002280 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002281
2282 // -- the rank of S1 is better than the rank of S2 (by the rules
2283 // defined below), or, if not that,
2284 ImplicitConversionRank Rank1 = SCS1.getRank();
2285 ImplicitConversionRank Rank2 = SCS2.getRank();
2286 if (Rank1 < Rank2)
2287 return ImplicitConversionSequence::Better;
2288 else if (Rank2 < Rank1)
2289 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002290
Douglas Gregor57373262008-10-22 14:17:15 +00002291 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2292 // are indistinguishable unless one of the following rules
2293 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00002294
Douglas Gregor57373262008-10-22 14:17:15 +00002295 // A conversion that is not a conversion of a pointer, or
2296 // pointer to member, to bool is better than another conversion
2297 // that is such a conversion.
2298 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2299 return SCS2.isPointerConversionToBool()
2300 ? ImplicitConversionSequence::Better
2301 : ImplicitConversionSequence::Worse;
2302
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002303 // C++ [over.ics.rank]p4b2:
2304 //
2305 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002306 // conversion of B* to A* is better than conversion of B* to
2307 // void*, and conversion of A* to void* is better than conversion
2308 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00002309 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00002310 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002311 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00002312 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002313 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2314 // Exactly one of the conversion sequences is a conversion to
2315 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002316 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2317 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002318 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2319 // Neither conversion sequence converts to a void pointer; compare
2320 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002321 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00002322 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002323 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002324 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2325 // Both conversion sequences are conversions to void
2326 // pointers. Compare the source types to determine if there's an
2327 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00002328 QualType FromType1 = SCS1.getFromType();
2329 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002330
2331 // Adjust the types we're converting from via the array-to-pointer
2332 // conversion, if we need to.
2333 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002334 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002335 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002336 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002337
Douglas Gregor01919692009-12-13 21:37:05 +00002338 QualType FromPointee1
2339 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2340 QualType FromPointee2
2341 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002342
John McCall120d63c2010-08-24 20:38:10 +00002343 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00002344 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002345 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00002346 return ImplicitConversionSequence::Worse;
2347
2348 // Objective-C++: If one interface is more specific than the
2349 // other, it is the better one.
John McCallc12c5bb2010-05-15 11:32:37 +00002350 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2351 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor01919692009-12-13 21:37:05 +00002352 if (FromIface1 && FromIface1) {
John McCall120d63c2010-08-24 20:38:10 +00002353 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor01919692009-12-13 21:37:05 +00002354 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002355 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor01919692009-12-13 21:37:05 +00002356 return ImplicitConversionSequence::Worse;
2357 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002358 }
Douglas Gregor57373262008-10-22 14:17:15 +00002359
2360 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2361 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00002362 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00002363 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002364 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00002365
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002366 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002367 // C++0x [over.ics.rank]p3b4:
2368 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2369 // implicit object parameter of a non-static member function declared
2370 // without a ref-qualifier, and S1 binds an rvalue reference to an
2371 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00002372 // FIXME: We don't know if we're dealing with the implicit object parameter,
2373 // or if the member function in this case has a ref qualifier.
2374 // (Of course, we don't have ref qualifiers yet.)
2375 if (SCS1.RRefBinding != SCS2.RRefBinding)
2376 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2377 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002378
2379 // C++ [over.ics.rank]p3b4:
2380 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2381 // which the references refer are the same type except for
2382 // top-level cv-qualifiers, and the type to which the reference
2383 // initialized by S2 refers is more cv-qualified than the type
2384 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00002385 QualType T1 = SCS1.getToType(2);
2386 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00002387 T1 = S.Context.getCanonicalType(T1);
2388 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002389 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00002390 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2391 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002392 if (UnqualT1 == UnqualT2) {
2393 // If the type is an array type, promote the element qualifiers to the type
2394 // for comparison.
2395 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00002396 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002397 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00002398 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002399 if (T2.isMoreQualifiedThan(T1))
2400 return ImplicitConversionSequence::Better;
2401 else if (T1.isMoreQualifiedThan(T2))
2402 return ImplicitConversionSequence::Worse;
2403 }
2404 }
Douglas Gregor57373262008-10-22 14:17:15 +00002405
2406 return ImplicitConversionSequence::Indistinguishable;
2407}
2408
2409/// CompareQualificationConversions - Compares two standard conversion
2410/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00002411/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2412ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00002413CompareQualificationConversions(Sema &S,
2414 const StandardConversionSequence& SCS1,
2415 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00002416 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00002417 // -- S1 and S2 differ only in their qualification conversion and
2418 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2419 // cv-qualification signature of type T1 is a proper subset of
2420 // the cv-qualification signature of type T2, and S1 is not the
2421 // deprecated string literal array-to-pointer conversion (4.2).
2422 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2423 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2424 return ImplicitConversionSequence::Indistinguishable;
2425
2426 // FIXME: the example in the standard doesn't use a qualification
2427 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00002428 QualType T1 = SCS1.getToType(2);
2429 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00002430 T1 = S.Context.getCanonicalType(T1);
2431 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002432 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00002433 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2434 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00002435
2436 // If the types are the same, we won't learn anything by unwrapped
2437 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00002438 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00002439 return ImplicitConversionSequence::Indistinguishable;
2440
Chandler Carruth28e318c2009-12-29 07:16:59 +00002441 // If the type is an array type, promote the element qualifiers to the type
2442 // for comparison.
2443 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00002444 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002445 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00002446 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002447
Mike Stump1eb44332009-09-09 15:08:12 +00002448 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00002449 = ImplicitConversionSequence::Indistinguishable;
John McCall120d63c2010-08-24 20:38:10 +00002450 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00002451 // Within each iteration of the loop, we check the qualifiers to
2452 // determine if this still looks like a qualification
2453 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002454 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00002455 // until there are no more pointers or pointers-to-members left
2456 // to unwrap. This essentially mimics what
2457 // IsQualificationConversion does, but here we're checking for a
2458 // strict subset of qualifiers.
2459 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2460 // The qualifiers are the same, so this doesn't tell us anything
2461 // about how the sequences rank.
2462 ;
2463 else if (T2.isMoreQualifiedThan(T1)) {
2464 // T1 has fewer qualifiers, so it could be the better sequence.
2465 if (Result == ImplicitConversionSequence::Worse)
2466 // Neither has qualifiers that are a subset of the other's
2467 // qualifiers.
2468 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002469
Douglas Gregor57373262008-10-22 14:17:15 +00002470 Result = ImplicitConversionSequence::Better;
2471 } else if (T1.isMoreQualifiedThan(T2)) {
2472 // T2 has fewer qualifiers, so it could be the better sequence.
2473 if (Result == ImplicitConversionSequence::Better)
2474 // Neither has qualifiers that are a subset of the other's
2475 // qualifiers.
2476 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002477
Douglas Gregor57373262008-10-22 14:17:15 +00002478 Result = ImplicitConversionSequence::Worse;
2479 } else {
2480 // Qualifiers are disjoint.
2481 return ImplicitConversionSequence::Indistinguishable;
2482 }
2483
2484 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00002485 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00002486 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002487 }
2488
Douglas Gregor57373262008-10-22 14:17:15 +00002489 // Check that the winning standard conversion sequence isn't using
2490 // the deprecated string literal array to pointer conversion.
2491 switch (Result) {
2492 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00002493 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002494 Result = ImplicitConversionSequence::Indistinguishable;
2495 break;
2496
2497 case ImplicitConversionSequence::Indistinguishable:
2498 break;
2499
2500 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00002501 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002502 Result = ImplicitConversionSequence::Indistinguishable;
2503 break;
2504 }
2505
2506 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002507}
2508
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002509/// CompareDerivedToBaseConversions - Compares two standard conversion
2510/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00002511/// various kinds of derived-to-base conversions (C++
2512/// [over.ics.rank]p4b3). As part of these checks, we also look at
2513/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002514ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00002515CompareDerivedToBaseConversions(Sema &S,
2516 const StandardConversionSequence& SCS1,
2517 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00002518 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002519 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00002520 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002521 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002522
2523 // Adjust the types we're converting from via the array-to-pointer
2524 // conversion, if we need to.
2525 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002526 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002527 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002528 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002529
2530 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00002531 FromType1 = S.Context.getCanonicalType(FromType1);
2532 ToType1 = S.Context.getCanonicalType(ToType1);
2533 FromType2 = S.Context.getCanonicalType(FromType2);
2534 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002535
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002536 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002537 //
2538 // If class B is derived directly or indirectly from class A and
2539 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002540 //
2541 // For Objective-C, we let A, B, and C also be Objective-C
2542 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002543
2544 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00002545 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00002546 SCS2.Second == ICK_Pointer_Conversion &&
2547 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2548 FromType1->isPointerType() && FromType2->isPointerType() &&
2549 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002550 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002551 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002552 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002553 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002554 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002555 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002556 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002557 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002558
John McCallc12c5bb2010-05-15 11:32:37 +00002559 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2560 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2561 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2562 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002563
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002564 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002565 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002566 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002567 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002568 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002569 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00002570
2571 if (ToIface1 && ToIface2) {
John McCall120d63c2010-08-24 20:38:10 +00002572 if (S.Context.canAssignObjCInterfaces(ToIface2, ToIface1))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002573 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002574 else if (S.Context.canAssignObjCInterfaces(ToIface1, ToIface2))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002575 return ImplicitConversionSequence::Worse;
2576 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002577 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002578
2579 // -- conversion of B* to A* is better than conversion of C* to A*,
2580 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002581 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002582 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002583 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002584 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00002585
Douglas Gregorcb7de522008-11-26 23:31:11 +00002586 if (FromIface1 && FromIface2) {
John McCall120d63c2010-08-24 20:38:10 +00002587 if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002588 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002589 else if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002590 return ImplicitConversionSequence::Worse;
2591 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002592 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002593 }
2594
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002595 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002596 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2597 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2598 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2599 const MemberPointerType * FromMemPointer1 =
2600 FromType1->getAs<MemberPointerType>();
2601 const MemberPointerType * ToMemPointer1 =
2602 ToType1->getAs<MemberPointerType>();
2603 const MemberPointerType * FromMemPointer2 =
2604 FromType2->getAs<MemberPointerType>();
2605 const MemberPointerType * ToMemPointer2 =
2606 ToType2->getAs<MemberPointerType>();
2607 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2608 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2609 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2610 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2611 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2612 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2613 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2614 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002615 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002616 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002617 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002618 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00002619 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002620 return ImplicitConversionSequence::Better;
2621 }
2622 // conversion of B::* to C::* is better than conversion of A::* to C::*
2623 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002624 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002625 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002626 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002627 return ImplicitConversionSequence::Worse;
2628 }
2629 }
2630
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002631 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002632 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00002633 // -- binding of an expression of type C to a reference of type
2634 // B& is better than binding an expression of type C to a
2635 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00002636 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2637 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2638 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002639 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002640 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002641 return ImplicitConversionSequence::Worse;
2642 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002643
Douglas Gregor225c41e2008-11-03 19:09:14 +00002644 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00002645 // -- binding of an expression of type B to a reference of type
2646 // A& is better than binding an expression of type C to a
2647 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00002648 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2649 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2650 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002651 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002652 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002653 return ImplicitConversionSequence::Worse;
2654 }
2655 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002656
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002657 return ImplicitConversionSequence::Indistinguishable;
2658}
2659
Douglas Gregorabe183d2010-04-13 16:31:36 +00002660/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2661/// determine whether they are reference-related,
2662/// reference-compatible, reference-compatible with added
2663/// qualification, or incompatible, for use in C++ initialization by
2664/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2665/// type, and the first type (T1) is the pointee type of the reference
2666/// type being initialized.
2667Sema::ReferenceCompareResult
2668Sema::CompareReferenceRelationship(SourceLocation Loc,
2669 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00002670 bool &DerivedToBase,
2671 bool &ObjCConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002672 assert(!OrigT1->isReferenceType() &&
2673 "T1 must be the pointee type of the reference type");
2674 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2675
2676 QualType T1 = Context.getCanonicalType(OrigT1);
2677 QualType T2 = Context.getCanonicalType(OrigT2);
2678 Qualifiers T1Quals, T2Quals;
2679 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2680 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2681
2682 // C++ [dcl.init.ref]p4:
2683 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2684 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2685 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00002686 DerivedToBase = false;
2687 ObjCConversion = false;
2688 if (UnqualT1 == UnqualT2) {
2689 // Nothing to do.
2690 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00002691 IsDerivedFrom(UnqualT2, UnqualT1))
2692 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00002693 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2694 UnqualT2->isObjCObjectOrInterfaceType() &&
2695 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2696 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002697 else
2698 return Ref_Incompatible;
2699
2700 // At this point, we know that T1 and T2 are reference-related (at
2701 // least).
2702
2703 // If the type is an array type, promote the element qualifiers to the type
2704 // for comparison.
2705 if (isa<ArrayType>(T1) && T1Quals)
2706 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2707 if (isa<ArrayType>(T2) && T2Quals)
2708 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2709
2710 // C++ [dcl.init.ref]p4:
2711 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2712 // reference-related to T2 and cv1 is the same cv-qualification
2713 // as, or greater cv-qualification than, cv2. For purposes of
2714 // overload resolution, cases for which cv1 is greater
2715 // cv-qualification than cv2 are identified as
2716 // reference-compatible with added qualification (see 13.3.3.2).
2717 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2718 return Ref_Compatible;
2719 else if (T1.isMoreQualifiedThan(T2))
2720 return Ref_Compatible_With_Added_Qualification;
2721 else
2722 return Ref_Related;
2723}
2724
Douglas Gregor604eb652010-08-11 02:15:33 +00002725/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00002726/// with DeclType. Return true if something definite is found.
2727static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00002728FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2729 QualType DeclType, SourceLocation DeclLoc,
2730 Expr *Init, QualType T2, bool AllowRvalues,
2731 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00002732 assert(T2->isRecordType() && "Can only find conversions of record types.");
2733 CXXRecordDecl *T2RecordDecl
2734 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2735
Douglas Gregor604eb652010-08-11 02:15:33 +00002736 QualType ToType
2737 = AllowRvalues? DeclType->getAs<ReferenceType>()->getPointeeType()
2738 : DeclType;
2739
Sebastian Redl4680bf22010-06-30 18:13:39 +00002740 OverloadCandidateSet CandidateSet(DeclLoc);
2741 const UnresolvedSetImpl *Conversions
2742 = T2RecordDecl->getVisibleConversionFunctions();
2743 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2744 E = Conversions->end(); I != E; ++I) {
2745 NamedDecl *D = *I;
2746 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2747 if (isa<UsingShadowDecl>(D))
2748 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2749
2750 FunctionTemplateDecl *ConvTemplate
2751 = dyn_cast<FunctionTemplateDecl>(D);
2752 CXXConversionDecl *Conv;
2753 if (ConvTemplate)
2754 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2755 else
2756 Conv = cast<CXXConversionDecl>(D);
2757
Douglas Gregor604eb652010-08-11 02:15:33 +00002758 // If this is an explicit conversion, and we're not allowed to consider
2759 // explicit conversions, skip it.
2760 if (!AllowExplicit && Conv->isExplicit())
2761 continue;
2762
2763 if (AllowRvalues) {
2764 bool DerivedToBase = false;
2765 bool ObjCConversion = false;
2766 if (!ConvTemplate &&
2767 S.CompareReferenceRelationship(DeclLoc,
2768 Conv->getConversionType().getNonReferenceType().getUnqualifiedType(),
2769 DeclType.getNonReferenceType().getUnqualifiedType(),
2770 DerivedToBase, ObjCConversion)
2771 == Sema::Ref_Incompatible)
2772 continue;
2773 } else {
2774 // If the conversion function doesn't return a reference type,
2775 // it can't be considered for this conversion. An rvalue reference
2776 // is only acceptable if its referencee is a function type.
2777
2778 const ReferenceType *RefType =
2779 Conv->getConversionType()->getAs<ReferenceType>();
2780 if (!RefType ||
2781 (!RefType->isLValueReferenceType() &&
2782 !RefType->getPointeeType()->isFunctionType()))
2783 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002784 }
Douglas Gregor604eb652010-08-11 02:15:33 +00002785
2786 if (ConvTemplate)
2787 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2788 Init, ToType, CandidateSet);
2789 else
2790 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2791 ToType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002792 }
2793
2794 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002795 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00002796 case OR_Success:
2797 // C++ [over.ics.ref]p1:
2798 //
2799 // [...] If the parameter binds directly to the result of
2800 // applying a conversion function to the argument
2801 // expression, the implicit conversion sequence is a
2802 // user-defined conversion sequence (13.3.3.1.2), with the
2803 // second standard conversion sequence either an identity
2804 // conversion or, if the conversion function returns an
2805 // entity of a type that is a derived class of the parameter
2806 // type, a derived-to-base Conversion.
2807 if (!Best->FinalConversion.DirectBinding)
2808 return false;
2809
2810 ICS.setUserDefined();
2811 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2812 ICS.UserDefined.After = Best->FinalConversion;
2813 ICS.UserDefined.ConversionFunction = Best->Function;
2814 ICS.UserDefined.EllipsisConversion = false;
2815 assert(ICS.UserDefined.After.ReferenceBinding &&
2816 ICS.UserDefined.After.DirectBinding &&
2817 "Expected a direct reference binding!");
2818 return true;
2819
2820 case OR_Ambiguous:
2821 ICS.setAmbiguous();
2822 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2823 Cand != CandidateSet.end(); ++Cand)
2824 if (Cand->Viable)
2825 ICS.Ambiguous.addConversion(Cand->Function);
2826 return true;
2827
2828 case OR_No_Viable_Function:
2829 case OR_Deleted:
2830 // There was no suitable conversion, or we found a deleted
2831 // conversion; continue with other checks.
2832 return false;
2833 }
Eric Christopher1c3d5022010-06-30 18:36:32 +00002834
2835 return false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002836}
2837
Douglas Gregorabe183d2010-04-13 16:31:36 +00002838/// \brief Compute an implicit conversion sequence for reference
2839/// initialization.
2840static ImplicitConversionSequence
2841TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2842 SourceLocation DeclLoc,
2843 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00002844 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002845 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2846
2847 // Most paths end in a failed conversion.
2848 ImplicitConversionSequence ICS;
2849 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2850
2851 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2852 QualType T2 = Init->getType();
2853
2854 // If the initializer is the address of an overloaded function, try
2855 // to resolve the overloaded function. If all goes well, T2 is the
2856 // type of the resulting function.
2857 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2858 DeclAccessPair Found;
2859 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2860 false, Found))
2861 T2 = Fn->getType();
2862 }
2863
2864 // Compute some basic properties of the types and the initializer.
2865 bool isRValRef = DeclType->isRValueReferenceType();
2866 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002867 bool ObjCConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002868 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002869 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00002870 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
2871 ObjCConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002872
Douglas Gregorabe183d2010-04-13 16:31:36 +00002873
Sebastian Redl4680bf22010-06-30 18:13:39 +00002874 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00002875 // A reference to type "cv1 T1" is initialized by an expression
2876 // of type "cv2 T2" as follows:
2877
Sebastian Redl4680bf22010-06-30 18:13:39 +00002878 // -- If reference is an lvalue reference and the initializer expression
2879 // The next bullet point (T1 is a function) is pretty much equivalent to this
2880 // one, so it's handled here.
2881 if (!isRValRef || T1->isFunctionType()) {
2882 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2883 // reference-compatible with "cv2 T2," or
2884 //
2885 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2886 if (InitCategory.isLValue() &&
2887 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002888 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00002889 // When a parameter of reference type binds directly (8.5.3)
2890 // to an argument expression, the implicit conversion sequence
2891 // is the identity conversion, unless the argument expression
2892 // has a type that is a derived class of the parameter type,
2893 // in which case the implicit conversion sequence is a
2894 // derived-to-base Conversion (13.3.3.1).
2895 ICS.setStandard();
2896 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00002897 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2898 : ObjCConversion? ICK_Compatible_Conversion
2899 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002900 ICS.Standard.Third = ICK_Identity;
2901 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2902 ICS.Standard.setToType(0, T2);
2903 ICS.Standard.setToType(1, T1);
2904 ICS.Standard.setToType(2, T1);
2905 ICS.Standard.ReferenceBinding = true;
2906 ICS.Standard.DirectBinding = true;
2907 ICS.Standard.RRefBinding = isRValRef;
2908 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002909
Sebastian Redl4680bf22010-06-30 18:13:39 +00002910 // Nothing more to do: the inaccessibility/ambiguity check for
2911 // derived-to-base conversions is suppressed when we're
2912 // computing the implicit conversion sequence (C++
2913 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00002914 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002915 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00002916
Sebastian Redl4680bf22010-06-30 18:13:39 +00002917 // -- has a class type (i.e., T2 is a class type), where T1 is
2918 // not reference-related to T2, and can be implicitly
2919 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2920 // is reference-compatible with "cv3 T3" 92) (this
2921 // conversion is selected by enumerating the applicable
2922 // conversion functions (13.3.1.6) and choosing the best
2923 // one through overload resolution (13.3)),
2924 if (!SuppressUserConversions && T2->isRecordType() &&
2925 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2926 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00002927 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2928 Init, T2, /*AllowRvalues=*/false,
2929 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00002930 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002931 }
2932 }
2933
Sebastian Redl4680bf22010-06-30 18:13:39 +00002934 // -- Otherwise, the reference shall be an lvalue reference to a
2935 // non-volatile const type (i.e., cv1 shall be const), or the reference
2936 // shall be an rvalue reference and the initializer expression shall be
2937 // an rvalue or have a function type.
Douglas Gregor66821b52010-04-18 09:22:00 +00002938 //
2939 // We actually handle one oddity of C++ [over.ics.ref] at this
2940 // point, which is that, due to p2 (which short-circuits reference
2941 // binding by only attempting a simple conversion for non-direct
2942 // bindings) and p3's strange wording, we allow a const volatile
2943 // reference to bind to an rvalue. Hence the check for the presence
2944 // of "const" rather than checking for "const" being the only
2945 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00002946 // This is also the point where rvalue references and lvalue inits no longer
2947 // go together.
2948 if ((!isRValRef && !T1.isConstQualified()) ||
2949 (isRValRef && InitCategory.isLValue()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00002950 return ICS;
2951
Sebastian Redl4680bf22010-06-30 18:13:39 +00002952 // -- If T1 is a function type, then
2953 // -- if T2 is the same type as T1, the reference is bound to the
2954 // initializer expression lvalue;
2955 // -- if T2 is a class type and the initializer expression can be
2956 // implicitly converted to an lvalue of type T1 [...], the
2957 // reference is bound to the function lvalue that is the result
2958 // of the conversion;
2959 // This is the same as for the lvalue case above, so it was handled there.
2960 // -- otherwise, the program is ill-formed.
2961 // This is the one difference to the lvalue case.
2962 if (T1->isFunctionType())
2963 return ICS;
2964
2965 // -- Otherwise, if T2 is a class type and
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002966 // -- the initializer expression is an rvalue and "cv1 T1"
2967 // is reference-compatible with "cv2 T2," or
Douglas Gregorabe183d2010-04-13 16:31:36 +00002968 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002969 // -- T1 is not reference-related to T2 and the initializer
2970 // expression can be implicitly converted to an rvalue
2971 // of type "cv3 T3" (this conversion is selected by
2972 // enumerating the applicable conversion functions
2973 // (13.3.1.6) and choosing the best one through overload
2974 // resolution (13.3)),
Douglas Gregorabe183d2010-04-13 16:31:36 +00002975 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002976 // then the reference is bound to the initializer
2977 // expression rvalue in the first case and to the object
2978 // that is the result of the conversion in the second case
2979 // (or, in either case, to the appropriate base class
2980 // subobject of the object).
Douglas Gregor604eb652010-08-11 02:15:33 +00002981 if (T2->isRecordType()) {
2982 // First case: "cv1 T1" is reference-compatible with "cv2 T2". This is a
2983 // direct binding in C++0x but not in C++03.
2984 if (InitCategory.isRValue() &&
2985 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2986 ICS.setStandard();
2987 ICS.Standard.First = ICK_Identity;
2988 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2989 : ObjCConversion? ICK_Compatible_Conversion
2990 : ICK_Identity;
2991 ICS.Standard.Third = ICK_Identity;
2992 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2993 ICS.Standard.setToType(0, T2);
2994 ICS.Standard.setToType(1, T1);
2995 ICS.Standard.setToType(2, T1);
2996 ICS.Standard.ReferenceBinding = true;
2997 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
2998 ICS.Standard.RRefBinding = isRValRef;
2999 ICS.Standard.CopyConstructor = 0;
3000 return ICS;
3001 }
3002
3003 // Second case: not reference-related.
3004 if (RefRelationship == Sema::Ref_Incompatible &&
3005 !S.RequireCompleteType(DeclLoc, T2, 0) &&
3006 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3007 Init, T2, /*AllowRvalues=*/true,
3008 AllowExplicit))
3009 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003010 }
Douglas Gregor604eb652010-08-11 02:15:33 +00003011
Douglas Gregorabe183d2010-04-13 16:31:36 +00003012 // -- Otherwise, a temporary of type "cv1 T1" is created and
3013 // initialized from the initializer expression using the
3014 // rules for a non-reference copy initialization (8.5). The
3015 // reference is then bound to the temporary. If T1 is
3016 // reference-related to T2, cv1 must be the same
3017 // cv-qualification as, or greater cv-qualification than,
3018 // cv2; otherwise, the program is ill-formed.
3019 if (RefRelationship == Sema::Ref_Related) {
3020 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3021 // we would be reference-compatible or reference-compatible with
3022 // added qualification. But that wasn't the case, so the reference
3023 // initialization fails.
3024 return ICS;
3025 }
3026
3027 // If at least one of the types is a class type, the types are not
3028 // related, and we aren't allowed any user conversions, the
3029 // reference binding fails. This case is important for breaking
3030 // recursion, since TryImplicitConversion below will attempt to
3031 // create a temporary through the use of a copy constructor.
3032 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3033 (T1->isRecordType() || T2->isRecordType()))
3034 return ICS;
3035
3036 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00003037 // When a parameter of reference type is not bound directly to
3038 // an argument expression, the conversion sequence is the one
3039 // required to convert the argument expression to the
3040 // underlying type of the reference according to
3041 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3042 // to copy-initializing a temporary of the underlying type with
3043 // the argument expression. Any difference in top-level
3044 // cv-qualification is subsumed by the initialization itself
3045 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00003046 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3047 /*AllowExplicit=*/false,
3048 /*InOverloadResolution=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003049
3050 // Of course, that's still a reference binding.
3051 if (ICS.isStandard()) {
3052 ICS.Standard.ReferenceBinding = true;
3053 ICS.Standard.RRefBinding = isRValRef;
3054 } else if (ICS.isUserDefined()) {
3055 ICS.UserDefined.After.ReferenceBinding = true;
3056 ICS.UserDefined.After.RRefBinding = isRValRef;
3057 }
3058 return ICS;
3059}
3060
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003061/// TryCopyInitialization - Try to copy-initialize a value of type
3062/// ToType from the expression From. Return the implicit conversion
3063/// sequence required to pass this argument, which may be a bad
3064/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00003065/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00003066/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00003067static ImplicitConversionSequence
3068TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregorb7f9e6a2010-04-16 17:53:55 +00003069 bool SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00003070 bool InOverloadResolution) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003071 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00003072 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00003073 /*FIXME:*/From->getLocStart(),
3074 SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00003075 /*AllowExplicit=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003076
John McCall120d63c2010-08-24 20:38:10 +00003077 return TryImplicitConversion(S, From, ToType,
3078 SuppressUserConversions,
3079 /*AllowExplicit=*/false,
3080 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003081}
3082
Douglas Gregor96176b32008-11-18 23:14:02 +00003083/// TryObjectArgumentInitialization - Try to initialize the object
3084/// parameter of the given member function (@c Method) from the
3085/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00003086static ImplicitConversionSequence
3087TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
3088 CXXMethodDecl *Method,
3089 CXXRecordDecl *ActingContext) {
3090 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00003091 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3092 // const volatile object.
3093 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3094 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00003095 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00003096
3097 // Set up the conversion sequence as a "bad" conversion, to allow us
3098 // to exit early.
3099 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00003100
3101 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00003102 QualType FromType = OrigFromType;
Ted Kremenek6217b802009-07-29 21:53:49 +00003103 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00003104 FromType = PT->getPointeeType();
3105
3106 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00003107
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00003108 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor96176b32008-11-18 23:14:02 +00003109 // where X is the class of which the function is a member
3110 // (C++ [over.match.funcs]p4). However, when finding an implicit
3111 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00003112 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00003113 // (C++ [over.match.funcs]p5). We perform a simplified version of
3114 // reference binding here, that allows class rvalues to bind to
3115 // non-constant references.
3116
3117 // First check the qualifiers. We don't care about lvalue-vs-rvalue
3118 // with the implicit object parameter (C++ [over.match.funcs]p5).
John McCall120d63c2010-08-24 20:38:10 +00003119 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00003120 if (ImplicitParamType.getCVRQualifiers()
3121 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00003122 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00003123 ICS.setBad(BadConversionSequence::bad_qualifiers,
3124 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003125 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003126 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003127
3128 // Check that we have either the same type or a derived type. It
3129 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00003130 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00003131 ImplicitConversionKind SecondKind;
3132 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3133 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00003134 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00003135 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00003136 else {
John McCallb1bdc622010-02-25 01:37:24 +00003137 ICS.setBad(BadConversionSequence::unrelated_class,
3138 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003139 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003140 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003141
3142 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00003143 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00003144 ICS.Standard.setAsIdentityConversion();
3145 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00003146 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003147 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003148 ICS.Standard.ReferenceBinding = true;
3149 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00003150 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003151 return ICS;
3152}
3153
3154/// PerformObjectArgumentInitialization - Perform initialization of
3155/// the implicit object parameter for the given Method with the given
3156/// expression.
3157bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00003158Sema::PerformObjectArgumentInitialization(Expr *&From,
3159 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00003160 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00003161 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003162 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00003163 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00003164 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003165
Ted Kremenek6217b802009-07-29 21:53:49 +00003166 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003167 FromRecordType = PT->getPointeeType();
3168 DestType = Method->getThisType(Context);
3169 } else {
3170 FromRecordType = From->getType();
3171 DestType = ImplicitParamRecordType;
3172 }
3173
John McCall701c89e2009-12-03 04:06:58 +00003174 // Note that we always use the true parent context when performing
3175 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003176 ImplicitConversionSequence ICS
John McCall120d63c2010-08-24 20:38:10 +00003177 = TryObjectArgumentInitialization(*this, From->getType(), Method,
John McCall701c89e2009-12-03 04:06:58 +00003178 Method->getParent());
John McCall1d318332010-01-12 00:44:57 +00003179 if (ICS.isBad())
Douglas Gregor96176b32008-11-18 23:14:02 +00003180 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003181 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00003182 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003183
Douglas Gregor5fccd362010-03-03 23:55:11 +00003184 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall6bb80172010-03-30 21:47:33 +00003185 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor96176b32008-11-18 23:14:02 +00003186
Douglas Gregor5fccd362010-03-03 23:55:11 +00003187 if (!Context.hasSameType(From->getType(), DestType))
John McCall2de56d12010-08-25 11:45:40 +00003188 ImpCastExprToType(From, DestType, CK_NoOp,
John McCall5baba9d2010-08-25 10:28:54 +00003189 From->getType()->isPointerType() ? VK_RValue : VK_LValue);
Douglas Gregor96176b32008-11-18 23:14:02 +00003190 return false;
3191}
3192
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003193/// TryContextuallyConvertToBool - Attempt to contextually convert the
3194/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00003195static ImplicitConversionSequence
3196TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00003197 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00003198 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00003199 // FIXME: Are these flags correct?
3200 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00003201 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00003202 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003203}
3204
3205/// PerformContextuallyConvertToBool - Perform a contextual conversion
3206/// of the expression From to bool (C++0x [conv]p3).
3207bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
John McCall120d63c2010-08-24 20:38:10 +00003208 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00003209 if (!ICS.isBad())
3210 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003211
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003212 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003213 return Diag(From->getSourceRange().getBegin(),
3214 diag::err_typecheck_bool_condition)
3215 << From->getType() << From->getSourceRange();
3216 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003217}
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003218
3219/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3220/// expression From to 'id'.
John McCall120d63c2010-08-24 20:38:10 +00003221static ImplicitConversionSequence
3222TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3223 QualType Ty = S.Context.getObjCIdType();
3224 return TryImplicitConversion(S, From, Ty,
3225 // FIXME: Are these flags correct?
3226 /*SuppressUserConversions=*/false,
3227 /*AllowExplicit=*/true,
3228 /*InOverloadResolution=*/false);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003229}
John McCall120d63c2010-08-24 20:38:10 +00003230
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003231/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3232/// of the expression From to 'id'.
3233bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCallc12c5bb2010-05-15 11:32:37 +00003234 QualType Ty = Context.getObjCIdType();
John McCall120d63c2010-08-24 20:38:10 +00003235 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003236 if (!ICS.isBad())
3237 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3238 return true;
3239}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003240
Douglas Gregorc30614b2010-06-29 23:17:37 +00003241/// \brief Attempt to convert the given expression to an integral or
3242/// enumeration type.
3243///
3244/// This routine will attempt to convert an expression of class type to an
3245/// integral or enumeration type, if that class type only has a single
3246/// conversion to an integral or enumeration type.
3247///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003248/// \param Loc The source location of the construct that requires the
3249/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00003250///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003251/// \param FromE The expression we're converting from.
3252///
3253/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3254/// have integral or enumeration type.
3255///
3256/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3257/// incomplete class type.
3258///
3259/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3260/// explicit conversion function (because no implicit conversion functions
3261/// were available). This is a recovery mode.
3262///
3263/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3264/// showing which conversion was picked.
3265///
3266/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3267/// conversion function that could convert to integral or enumeration type.
3268///
3269/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3270/// usable conversion function.
3271///
3272/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3273/// function, which may be an extension in this case.
3274///
3275/// \returns The expression, converted to an integral or enumeration type if
3276/// successful.
John McCall60d7b3a2010-08-24 06:29:42 +00003277ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003278Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorc30614b2010-06-29 23:17:37 +00003279 const PartialDiagnostic &NotIntDiag,
3280 const PartialDiagnostic &IncompleteDiag,
3281 const PartialDiagnostic &ExplicitConvDiag,
3282 const PartialDiagnostic &ExplicitConvNote,
3283 const PartialDiagnostic &AmbigDiag,
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003284 const PartialDiagnostic &AmbigNote,
3285 const PartialDiagnostic &ConvDiag) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00003286 // We can't perform any more checking for type-dependent expressions.
3287 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00003288 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003289
3290 // If the expression already has integral or enumeration type, we're golden.
3291 QualType T = From->getType();
3292 if (T->isIntegralOrEnumerationType())
John McCall9ae2f072010-08-23 23:25:46 +00003293 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003294
3295 // FIXME: Check for missing '()' if T is a function type?
3296
3297 // If we don't have a class type in C++, there's no way we can get an
3298 // expression of integral or enumeration type.
3299 const RecordType *RecordTy = T->getAs<RecordType>();
3300 if (!RecordTy || !getLangOptions().CPlusPlus) {
3301 Diag(Loc, NotIntDiag)
3302 << T << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00003303 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003304 }
3305
3306 // We must have a complete class type.
3307 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCall9ae2f072010-08-23 23:25:46 +00003308 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003309
3310 // Look for a conversion to an integral or enumeration type.
3311 UnresolvedSet<4> ViableConversions;
3312 UnresolvedSet<4> ExplicitConversions;
3313 const UnresolvedSetImpl *Conversions
3314 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3315
3316 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3317 E = Conversions->end();
3318 I != E;
3319 ++I) {
3320 if (CXXConversionDecl *Conversion
3321 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3322 if (Conversion->getConversionType().getNonReferenceType()
3323 ->isIntegralOrEnumerationType()) {
3324 if (Conversion->isExplicit())
3325 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3326 else
3327 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3328 }
3329 }
3330
3331 switch (ViableConversions.size()) {
3332 case 0:
3333 if (ExplicitConversions.size() == 1) {
3334 DeclAccessPair Found = ExplicitConversions[0];
3335 CXXConversionDecl *Conversion
3336 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3337
3338 // The user probably meant to invoke the given explicit
3339 // conversion; use it.
3340 QualType ConvTy
3341 = Conversion->getConversionType().getNonReferenceType();
3342 std::string TypeStr;
3343 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3344
3345 Diag(Loc, ExplicitConvDiag)
3346 << T << ConvTy
3347 << FixItHint::CreateInsertion(From->getLocStart(),
3348 "static_cast<" + TypeStr + ">(")
3349 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3350 ")");
3351 Diag(Conversion->getLocation(), ExplicitConvNote)
3352 << ConvTy->isEnumeralType() << ConvTy;
3353
3354 // If we aren't in a SFINAE context, build a call to the
3355 // explicit conversion function.
3356 if (isSFINAEContext())
3357 return ExprError();
3358
3359 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
John McCall9ae2f072010-08-23 23:25:46 +00003360 From = BuildCXXMemberCallExpr(From, Found, Conversion);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003361 }
3362
3363 // We'll complain below about a non-integral condition type.
3364 break;
3365
3366 case 1: {
3367 // Apply this conversion.
3368 DeclAccessPair Found = ViableConversions[0];
3369 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003370
3371 CXXConversionDecl *Conversion
3372 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3373 QualType ConvTy
3374 = Conversion->getConversionType().getNonReferenceType();
3375 if (ConvDiag.getDiagID()) {
3376 if (isSFINAEContext())
3377 return ExprError();
3378
3379 Diag(Loc, ConvDiag)
3380 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3381 }
3382
John McCall9ae2f072010-08-23 23:25:46 +00003383 From = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorc30614b2010-06-29 23:17:37 +00003384 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregorc30614b2010-06-29 23:17:37 +00003385 break;
3386 }
3387
3388 default:
3389 Diag(Loc, AmbigDiag)
3390 << T << From->getSourceRange();
3391 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3392 CXXConversionDecl *Conv
3393 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3394 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3395 Diag(Conv->getLocation(), AmbigNote)
3396 << ConvTy->isEnumeralType() << ConvTy;
3397 }
John McCall9ae2f072010-08-23 23:25:46 +00003398 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003399 }
3400
Douglas Gregoracb0bd82010-06-29 23:25:20 +00003401 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorc30614b2010-06-29 23:17:37 +00003402 Diag(Loc, NotIntDiag)
3403 << From->getType() << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00003404
John McCall9ae2f072010-08-23 23:25:46 +00003405 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003406}
3407
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003408/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00003409/// candidate functions, using the given function call arguments. If
3410/// @p SuppressUserConversions, then don't allow user-defined
3411/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003412///
3413/// \para PartialOverloading true if we are performing "partial" overloading
3414/// based on an incomplete set of function arguments. This feature is used by
3415/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00003416void
3417Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00003418 DeclAccessPair FoundDecl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003419 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00003420 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00003421 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003422 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00003423 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003424 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003425 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00003426 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00003427 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00003428
Douglas Gregor88a35142008-12-22 05:46:06 +00003429 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003430 if (!isa<CXXConstructorDecl>(Method)) {
3431 // If we get here, it's because we're calling a member function
3432 // that is named without a member access expression (e.g.,
3433 // "this->f") that was either written explicitly or created
3434 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00003435 // function, e.g., X::f(). We use an empty type for the implied
3436 // object argument (C++ [over.call.func]p3), and the acting context
3437 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00003438 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall701c89e2009-12-03 04:06:58 +00003439 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003440 SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003441 return;
3442 }
3443 // We treat a constructor like a non-member function, since its object
3444 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00003445 }
3446
Douglas Gregorfd476482009-11-13 23:59:09 +00003447 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00003448 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00003449
Douglas Gregor7edfb692009-11-23 12:27:39 +00003450 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003451 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003452
Douglas Gregor66724ea2009-11-14 01:20:54 +00003453 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3454 // C++ [class.copy]p3:
3455 // A member function template is never instantiated to perform the copy
3456 // of a class object to an object of its class type.
3457 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3458 if (NumArgs == 1 &&
3459 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor12116062010-02-21 18:30:38 +00003460 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3461 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00003462 return;
3463 }
3464
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003465 // Add this candidate
3466 CandidateSet.push_back(OverloadCandidate());
3467 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003468 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003469 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00003470 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003471 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003472 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003473
3474 unsigned NumArgsInProto = Proto->getNumArgs();
3475
3476 // (C++ 13.3.2p2): A candidate function having fewer than m
3477 // parameters is viable only if it has an ellipsis in its parameter
3478 // list (8.3.5).
Douglas Gregor5bd1a112009-09-23 14:56:09 +00003479 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3480 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003481 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003482 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003483 return;
3484 }
3485
3486 // (C++ 13.3.2p2): A candidate function having more than m parameters
3487 // is viable only if the (m+1)st parameter has a default argument
3488 // (8.3.6). For the purposes of overload resolution, the
3489 // parameter list is truncated on the right, so that there are
3490 // exactly m parameters.
3491 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003492 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003493 // Not enough arguments.
3494 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003495 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003496 return;
3497 }
3498
3499 // Determine the implicit conversion sequences for each of the
3500 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003501 Candidate.Conversions.resize(NumArgs);
3502 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3503 if (ArgIdx < NumArgsInProto) {
3504 // (C++ 13.3.2p3): for F to be a viable function, there shall
3505 // exist for each argument an implicit conversion sequence
3506 // (13.3.3.1) that converts that argument to the corresponding
3507 // parameter of F.
3508 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003509 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003510 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003511 SuppressUserConversions,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003512 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003513 if (Candidate.Conversions[ArgIdx].isBad()) {
3514 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003515 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00003516 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00003517 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003518 } else {
3519 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3520 // argument for which there is no corresponding parameter is
3521 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003522 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003523 }
3524 }
3525}
3526
Douglas Gregor063daf62009-03-13 18:40:31 +00003527/// \brief Add all of the function declarations in the given function set to
3528/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00003529void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00003530 Expr **Args, unsigned NumArgs,
3531 OverloadCandidateSet& CandidateSet,
3532 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00003533 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00003534 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3535 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003536 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003537 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003538 cast<CXXMethodDecl>(FD)->getParent(),
3539 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003540 CandidateSet, SuppressUserConversions);
3541 else
John McCall9aa472c2010-03-19 07:35:19 +00003542 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00003543 SuppressUserConversions);
3544 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003545 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00003546 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3547 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003548 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003549 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00003550 /*FIXME: explicit args */ 0,
John McCall701c89e2009-12-03 04:06:58 +00003551 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003552 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00003553 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00003554 else
John McCall9aa472c2010-03-19 07:35:19 +00003555 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCalld5532b62009-11-23 01:53:49 +00003556 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00003557 Args, NumArgs, CandidateSet,
3558 SuppressUserConversions);
3559 }
Douglas Gregor364e0212009-06-27 21:05:07 +00003560 }
Douglas Gregor063daf62009-03-13 18:40:31 +00003561}
3562
John McCall314be4e2009-11-17 07:50:12 +00003563/// AddMethodCandidate - Adds a named decl (which is some kind of
3564/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00003565void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003566 QualType ObjectType,
John McCall314be4e2009-11-17 07:50:12 +00003567 Expr **Args, unsigned NumArgs,
3568 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003569 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00003570 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003571 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00003572
3573 if (isa<UsingShadowDecl>(Decl))
3574 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3575
3576 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3577 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3578 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00003579 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3580 /*ExplicitArgs*/ 0,
John McCall701c89e2009-12-03 04:06:58 +00003581 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00003582 CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003583 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003584 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003585 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall701c89e2009-12-03 04:06:58 +00003586 ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003587 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003588 }
3589}
3590
Douglas Gregor96176b32008-11-18 23:14:02 +00003591/// AddMethodCandidate - Adds the given C++ member function to the set
3592/// of candidate functions, using the given function call arguments
3593/// and the object argument (@c Object). For example, in a call
3594/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3595/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3596/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00003597/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00003598void
John McCall9aa472c2010-03-19 07:35:19 +00003599Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003600 CXXRecordDecl *ActingContext, QualType ObjectType,
3601 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00003602 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003603 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00003604 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003605 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00003606 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003607 assert(!isa<CXXConstructorDecl>(Method) &&
3608 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00003609
Douglas Gregor3f396022009-09-28 04:47:19 +00003610 if (!CandidateSet.isNewCandidate(Method))
3611 return;
3612
Douglas Gregor7edfb692009-11-23 12:27:39 +00003613 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003614 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003615
Douglas Gregor96176b32008-11-18 23:14:02 +00003616 // Add this candidate
3617 CandidateSet.push_back(OverloadCandidate());
3618 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003619 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00003620 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003621 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003622 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003623
3624 unsigned NumArgsInProto = Proto->getNumArgs();
3625
3626 // (C++ 13.3.2p2): A candidate function having fewer than m
3627 // parameters is viable only if it has an ellipsis in its parameter
3628 // list (8.3.5).
3629 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3630 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003631 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003632 return;
3633 }
3634
3635 // (C++ 13.3.2p2): A candidate function having more than m parameters
3636 // is viable only if the (m+1)st parameter has a default argument
3637 // (8.3.6). For the purposes of overload resolution, the
3638 // parameter list is truncated on the right, so that there are
3639 // exactly m parameters.
3640 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3641 if (NumArgs < MinRequiredArgs) {
3642 // Not enough arguments.
3643 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003644 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003645 return;
3646 }
3647
3648 Candidate.Viable = true;
3649 Candidate.Conversions.resize(NumArgs + 1);
3650
John McCall701c89e2009-12-03 04:06:58 +00003651 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00003652 // The implicit object argument is ignored.
3653 Candidate.IgnoreObjectArgument = true;
3654 else {
3655 // Determine the implicit conversion sequence for the object
3656 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00003657 Candidate.Conversions[0]
John McCall120d63c2010-08-24 20:38:10 +00003658 = TryObjectArgumentInitialization(*this, ObjectType, Method,
3659 ActingContext);
John McCall1d318332010-01-12 00:44:57 +00003660 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003661 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003662 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00003663 return;
3664 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003665 }
3666
3667 // Determine the implicit conversion sequences for each of the
3668 // arguments.
3669 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3670 if (ArgIdx < NumArgsInProto) {
3671 // (C++ 13.3.2p3): for F to be a viable function, there shall
3672 // exist for each argument an implicit conversion sequence
3673 // (13.3.3.1) that converts that argument to the corresponding
3674 // parameter of F.
3675 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003676 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003677 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003678 SuppressUserConversions,
Anders Carlsson08972922009-08-28 15:33:32 +00003679 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003680 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00003681 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003682 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00003683 break;
3684 }
3685 } else {
3686 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3687 // argument for which there is no corresponding parameter is
3688 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003689 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00003690 }
3691 }
3692}
Douglas Gregora9333192010-05-08 17:41:32 +00003693
Douglas Gregor6b906862009-08-21 00:16:32 +00003694/// \brief Add a C++ member function template as a candidate to the candidate
3695/// set, using template argument deduction to produce an appropriate member
3696/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003697void
Douglas Gregor6b906862009-08-21 00:16:32 +00003698Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00003699 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003700 CXXRecordDecl *ActingContext,
John McCalld5532b62009-11-23 01:53:49 +00003701 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00003702 QualType ObjectType,
3703 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003704 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003705 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003706 if (!CandidateSet.isNewCandidate(MethodTmpl))
3707 return;
3708
Douglas Gregor6b906862009-08-21 00:16:32 +00003709 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003710 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00003711 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003712 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00003713 // candidate functions in the usual way.113) A given name can refer to one
3714 // or more function templates and also to a set of overloaded non-template
3715 // functions. In such a case, the candidate functions generated from each
3716 // function template are combined with the set of non-template candidate
3717 // functions.
John McCall5769d612010-02-08 23:07:23 +00003718 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00003719 FunctionDecl *Specialization = 0;
3720 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003721 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003722 Args, NumArgs, Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003723 CandidateSet.push_back(OverloadCandidate());
3724 OverloadCandidate &Candidate = CandidateSet.back();
3725 Candidate.FoundDecl = FoundDecl;
3726 Candidate.Function = MethodTmpl->getTemplatedDecl();
3727 Candidate.Viable = false;
3728 Candidate.FailureKind = ovl_fail_bad_deduction;
3729 Candidate.IsSurrogate = false;
3730 Candidate.IgnoreObjectArgument = false;
3731 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3732 Info);
3733 return;
3734 }
Mike Stump1eb44332009-09-09 15:08:12 +00003735
Douglas Gregor6b906862009-08-21 00:16:32 +00003736 // Add the function template specialization produced by template argument
3737 // deduction as a candidate.
3738 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00003739 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00003740 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00003741 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003742 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003743 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00003744}
3745
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003746/// \brief Add a C++ function template specialization as a candidate
3747/// in the candidate set, using template argument deduction to produce
3748/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003749void
Douglas Gregore53060f2009-06-25 22:08:12 +00003750Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003751 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00003752 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00003753 Expr **Args, unsigned NumArgs,
3754 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003755 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003756 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3757 return;
3758
Douglas Gregore53060f2009-06-25 22:08:12 +00003759 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003760 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00003761 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003762 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00003763 // candidate functions in the usual way.113) A given name can refer to one
3764 // or more function templates and also to a set of overloaded non-template
3765 // functions. In such a case, the candidate functions generated from each
3766 // function template are combined with the set of non-template candidate
3767 // functions.
John McCall5769d612010-02-08 23:07:23 +00003768 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00003769 FunctionDecl *Specialization = 0;
3770 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003771 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003772 Args, NumArgs, Specialization, Info)) {
John McCall578b69b2009-12-16 08:11:27 +00003773 CandidateSet.push_back(OverloadCandidate());
3774 OverloadCandidate &Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003775 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00003776 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3777 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003778 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00003779 Candidate.IsSurrogate = false;
3780 Candidate.IgnoreObjectArgument = false;
Douglas Gregorff5adac2010-05-08 20:18:54 +00003781 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3782 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00003783 return;
3784 }
Mike Stump1eb44332009-09-09 15:08:12 +00003785
Douglas Gregore53060f2009-06-25 22:08:12 +00003786 // Add the function template specialization produced by template argument
3787 // deduction as a candidate.
3788 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003789 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003790 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00003791}
Mike Stump1eb44332009-09-09 15:08:12 +00003792
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003793/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00003794/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003795/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00003796/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003797/// (which may or may not be the same type as the type that the
3798/// conversion function produces).
3799void
3800Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003801 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003802 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003803 Expr *From, QualType ToType,
3804 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003805 assert(!Conversion->getDescribedFunctionTemplate() &&
3806 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003807 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00003808 if (!CandidateSet.isNewCandidate(Conversion))
3809 return;
3810
Douglas Gregor7edfb692009-11-23 12:27:39 +00003811 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003812 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003813
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003814 // Add this candidate
3815 CandidateSet.push_back(OverloadCandidate());
3816 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003817 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003818 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003819 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003820 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003821 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003822 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003823 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003824 Candidate.Viable = true;
3825 Candidate.Conversions.resize(1);
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003826
Douglas Gregorbca39322010-08-19 15:37:02 +00003827 // C++ [over.match.funcs]p4:
3828 // For conversion functions, the function is considered to be a member of
3829 // the class of the implicit implied object argument for the purpose of
3830 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003831 //
3832 // Determine the implicit conversion sequence for the implicit
3833 // object parameter.
3834 QualType ImplicitParamType = From->getType();
3835 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
3836 ImplicitParamType = FromPtrType->getPointeeType();
3837 CXXRecordDecl *ConversionContext
3838 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
3839
3840 Candidate.Conversions[0]
John McCall120d63c2010-08-24 20:38:10 +00003841 = TryObjectArgumentInitialization(*this, From->getType(), Conversion,
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003842 ConversionContext);
3843
John McCall1d318332010-01-12 00:44:57 +00003844 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003845 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003846 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003847 return;
3848 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003849
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003850 // We won't go through a user-define type conversion function to convert a
3851 // derived to base as such conversions are given Conversion Rank. They only
3852 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3853 QualType FromCanon
3854 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3855 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3856 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3857 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003858 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003859 return;
3860 }
3861
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003862 // To determine what the conversion from the result of calling the
3863 // conversion function to the type we're eventually trying to
3864 // convert to (ToType), we need to synthesize a call to the
3865 // conversion function and attempt copy initialization from it. This
3866 // makes sure that we get the right semantics with respect to
3867 // lvalues/rvalues and the type. Fortunately, we can allocate this
3868 // call on the stack and we don't need its arguments to be
3869 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00003870 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003871 From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00003872 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
3873 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00003874 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00003875 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00003876
3877 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00003878 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3879 // allocator).
Mike Stump1eb44332009-09-09 15:08:12 +00003880 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregor63982352010-07-13 18:40:04 +00003881 Conversion->getConversionType().getNonLValueExprType(Context),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003882 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00003883 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00003884 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00003885 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003886 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00003887
John McCall1d318332010-01-12 00:44:57 +00003888 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003889 case ImplicitConversionSequence::StandardConversion:
3890 Candidate.FinalConversion = ICS.Standard;
Douglas Gregorc520c842010-04-12 23:42:09 +00003891
3892 // C++ [over.ics.user]p3:
3893 // If the user-defined conversion is specified by a specialization of a
3894 // conversion function template, the second standard conversion sequence
3895 // shall have exact match rank.
3896 if (Conversion->getPrimaryTemplate() &&
3897 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3898 Candidate.Viable = false;
3899 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3900 }
3901
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003902 break;
3903
3904 case ImplicitConversionSequence::BadConversion:
3905 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003906 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003907 break;
3908
3909 default:
Mike Stump1eb44332009-09-09 15:08:12 +00003910 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003911 "Can only end up with a standard conversion sequence or failure");
3912 }
3913}
3914
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003915/// \brief Adds a conversion function template specialization
3916/// candidate to the overload set, using template argument deduction
3917/// to deduce the template arguments of the conversion function
3918/// template from the type that we are converting to (C++
3919/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00003920void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003921Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003922 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003923 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003924 Expr *From, QualType ToType,
3925 OverloadCandidateSet &CandidateSet) {
3926 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3927 "Only conversion function templates permitted here");
3928
Douglas Gregor3f396022009-09-28 04:47:19 +00003929 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3930 return;
3931
John McCall5769d612010-02-08 23:07:23 +00003932 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003933 CXXConversionDecl *Specialization = 0;
3934 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00003935 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003936 Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003937 CandidateSet.push_back(OverloadCandidate());
3938 OverloadCandidate &Candidate = CandidateSet.back();
3939 Candidate.FoundDecl = FoundDecl;
3940 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3941 Candidate.Viable = false;
3942 Candidate.FailureKind = ovl_fail_bad_deduction;
3943 Candidate.IsSurrogate = false;
3944 Candidate.IgnoreObjectArgument = false;
3945 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3946 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003947 return;
3948 }
Mike Stump1eb44332009-09-09 15:08:12 +00003949
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003950 // Add the conversion function template specialization produced by
3951 // template argument deduction as a candidate.
3952 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003953 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00003954 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003955}
3956
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003957/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3958/// converts the given @c Object to a function pointer via the
3959/// conversion function @c Conversion, and then attempts to call it
3960/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3961/// the type of function that we'll eventually be calling.
3962void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003963 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003964 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00003965 const FunctionProtoType *Proto,
John McCall701c89e2009-12-03 04:06:58 +00003966 QualType ObjectType,
3967 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003968 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003969 if (!CandidateSet.isNewCandidate(Conversion))
3970 return;
3971
Douglas Gregor7edfb692009-11-23 12:27:39 +00003972 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003973 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003974
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003975 CandidateSet.push_back(OverloadCandidate());
3976 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003977 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003978 Candidate.Function = 0;
3979 Candidate.Surrogate = Conversion;
3980 Candidate.Viable = true;
3981 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003982 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003983 Candidate.Conversions.resize(NumArgs + 1);
3984
3985 // Determine the implicit conversion sequence for the implicit
3986 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00003987 ImplicitConversionSequence ObjectInit
John McCall120d63c2010-08-24 20:38:10 +00003988 = TryObjectArgumentInitialization(*this, ObjectType, Conversion,
3989 ActingContext);
John McCall1d318332010-01-12 00:44:57 +00003990 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003991 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003992 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00003993 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003994 return;
3995 }
3996
3997 // The first conversion is actually a user-defined conversion whose
3998 // first conversion is ObjectInit's standard conversion (which is
3999 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00004000 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004001 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00004002 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004003 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00004004 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004005 = Candidate.Conversions[0].UserDefined.Before;
4006 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4007
Mike Stump1eb44332009-09-09 15:08:12 +00004008 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004009 unsigned NumArgsInProto = Proto->getNumArgs();
4010
4011 // (C++ 13.3.2p2): A candidate function having fewer than m
4012 // parameters is viable only if it has an ellipsis in its parameter
4013 // list (8.3.5).
4014 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4015 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004016 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004017 return;
4018 }
4019
4020 // Function types don't have any default arguments, so just check if
4021 // we have enough arguments.
4022 if (NumArgs < NumArgsInProto) {
4023 // Not enough arguments.
4024 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004025 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004026 return;
4027 }
4028
4029 // Determine the implicit conversion sequences for each of the
4030 // arguments.
4031 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4032 if (ArgIdx < NumArgsInProto) {
4033 // (C++ 13.3.2p3): for F to be a viable function, there shall
4034 // exist for each argument an implicit conversion sequence
4035 // (13.3.3.1) that converts that argument to the corresponding
4036 // parameter of F.
4037 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00004038 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004039 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00004040 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00004041 /*InOverloadResolution=*/false);
John McCall1d318332010-01-12 00:44:57 +00004042 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004043 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004044 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004045 break;
4046 }
4047 } else {
4048 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4049 // argument for which there is no corresponding parameter is
4050 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00004051 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004052 }
4053 }
4054}
4055
Douglas Gregor063daf62009-03-13 18:40:31 +00004056/// \brief Add overload candidates for overloaded operators that are
4057/// member functions.
4058///
4059/// Add the overloaded operator candidates that are member functions
4060/// for the operator Op that was used in an operator expression such
4061/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4062/// CandidateSet will store the added overload candidates. (C++
4063/// [over.match.oper]).
4064void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4065 SourceLocation OpLoc,
4066 Expr **Args, unsigned NumArgs,
4067 OverloadCandidateSet& CandidateSet,
4068 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00004069 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4070
4071 // C++ [over.match.oper]p3:
4072 // For a unary operator @ with an operand of a type whose
4073 // cv-unqualified version is T1, and for a binary operator @ with
4074 // a left operand of a type whose cv-unqualified version is T1 and
4075 // a right operand of a type whose cv-unqualified version is T2,
4076 // three sets of candidate functions, designated member
4077 // candidates, non-member candidates and built-in candidates, are
4078 // constructed as follows:
4079 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00004080
4081 // -- If T1 is a class type, the set of member candidates is the
4082 // result of the qualified lookup of T1::operator@
4083 // (13.3.1.1.1); otherwise, the set of member candidates is
4084 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00004085 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004086 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004087 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004088 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004089
John McCalla24dc2e2009-11-17 02:14:36 +00004090 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4091 LookupQualifiedName(Operators, T1Rec->getDecl());
4092 Operators.suppressDiagnostics();
4093
Mike Stump1eb44332009-09-09 15:08:12 +00004094 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004095 OperEnd = Operators.end();
4096 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00004097 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00004098 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall701c89e2009-12-03 04:06:58 +00004099 Args + 1, NumArgs - 1, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00004100 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00004101 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004102}
4103
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004104/// AddBuiltinCandidate - Add a candidate for a built-in
4105/// operator. ResultTy and ParamTys are the result and parameter types
4106/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004107/// arguments being passed to the candidate. IsAssignmentOperator
4108/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004109/// operator. NumContextualBoolArguments is the number of arguments
4110/// (at the beginning of the argument list) that will be contextually
4111/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00004112void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004113 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004114 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004115 bool IsAssignmentOperator,
4116 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00004117 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004118 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004119
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004120 // Add this candidate
4121 CandidateSet.push_back(OverloadCandidate());
4122 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004123 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004124 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00004125 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004126 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004127 Candidate.BuiltinTypes.ResultTy = ResultTy;
4128 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4129 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4130
4131 // Determine the implicit conversion sequences for each of the
4132 // arguments.
4133 Candidate.Viable = true;
4134 Candidate.Conversions.resize(NumArgs);
4135 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004136 // C++ [over.match.oper]p4:
4137 // For the built-in assignment operators, conversions of the
4138 // left operand are restricted as follows:
4139 // -- no temporaries are introduced to hold the left operand, and
4140 // -- no user-defined conversions are applied to the left
4141 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00004142 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004143 //
4144 // We block these conversions by turning off user-defined
4145 // conversions, since that is the only way that initialization of
4146 // a reference to a non-class type can occur from something that
4147 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004148 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00004149 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004150 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00004151 Candidate.Conversions[ArgIdx]
4152 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004153 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00004154 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004155 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00004156 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00004157 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004158 }
John McCall1d318332010-01-12 00:44:57 +00004159 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004160 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004161 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00004162 break;
4163 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004164 }
4165}
4166
4167/// BuiltinCandidateTypeSet - A set of types that will be used for the
4168/// candidate operator functions for built-in operators (C++
4169/// [over.built]). The types are separated into pointer types and
4170/// enumeration types.
4171class BuiltinCandidateTypeSet {
4172 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004173 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004174
4175 /// PointerTypes - The set of pointer types that will be used in the
4176 /// built-in candidates.
4177 TypeSet PointerTypes;
4178
Sebastian Redl78eb8742009-04-19 21:53:20 +00004179 /// MemberPointerTypes - The set of member pointer types that will be
4180 /// used in the built-in candidates.
4181 TypeSet MemberPointerTypes;
4182
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004183 /// EnumerationTypes - The set of enumeration types that will be
4184 /// used in the built-in candidates.
4185 TypeSet EnumerationTypes;
4186
Douglas Gregor26bcf672010-05-19 03:21:00 +00004187 /// \brief The set of vector types that will be used in the built-in
4188 /// candidates.
4189 TypeSet VectorTypes;
4190
Douglas Gregor5842ba92009-08-24 15:23:48 +00004191 /// Sema - The semantic analysis instance where we are building the
4192 /// candidate type set.
4193 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00004194
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004195 /// Context - The AST context in which we will build the type sets.
4196 ASTContext &Context;
4197
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004198 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4199 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00004200 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004201
4202public:
4203 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004204 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004205
Mike Stump1eb44332009-09-09 15:08:12 +00004206 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor5842ba92009-08-24 15:23:48 +00004207 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004208
Douglas Gregor573d9c32009-10-21 23:19:44 +00004209 void AddTypesConvertedFrom(QualType Ty,
4210 SourceLocation Loc,
4211 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004212 bool AllowExplicitConversions,
4213 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004214
4215 /// pointer_begin - First pointer type found;
4216 iterator pointer_begin() { return PointerTypes.begin(); }
4217
Sebastian Redl78eb8742009-04-19 21:53:20 +00004218 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004219 iterator pointer_end() { return PointerTypes.end(); }
4220
Sebastian Redl78eb8742009-04-19 21:53:20 +00004221 /// member_pointer_begin - First member pointer type found;
4222 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4223
4224 /// member_pointer_end - Past the last member pointer type found;
4225 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4226
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004227 /// enumeration_begin - First enumeration type found;
4228 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4229
Sebastian Redl78eb8742009-04-19 21:53:20 +00004230 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004231 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004232
4233 iterator vector_begin() { return VectorTypes.begin(); }
4234 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004235};
4236
Sebastian Redl78eb8742009-04-19 21:53:20 +00004237/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004238/// the set of pointer types along with any more-qualified variants of
4239/// that type. For example, if @p Ty is "int const *", this routine
4240/// will add "int const *", "int const volatile *", "int const
4241/// restrict *", and "int const volatile restrict *" to the set of
4242/// pointer types. Returns true if the add of @p Ty itself succeeded,
4243/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00004244///
4245/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004246bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00004247BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4248 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00004249
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004250 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004251 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004252 return false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004253
4254 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00004255 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004256 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004257 if (!PointerTy) {
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004258 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004259 PointeeTy = PTy->getPointeeType();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004260 buildObjCPtr = true;
4261 }
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004262 else
4263 assert(false && "type was not a pointer type!");
4264 }
4265 else
4266 PointeeTy = PointerTy->getPointeeType();
4267
Sebastian Redla9efada2009-11-18 20:39:26 +00004268 // Don't add qualified variants of arrays. For one, they're not allowed
4269 // (the qualifier would sink to the element type), and for another, the
4270 // only overload situation where it matters is subscript or pointer +- int,
4271 // and those shouldn't have qualifier variants anyway.
4272 if (PointeeTy->isArrayType())
4273 return true;
John McCall0953e762009-09-24 19:53:00 +00004274 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00004275 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00004276 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004277 bool hasVolatile = VisibleQuals.hasVolatile();
4278 bool hasRestrict = VisibleQuals.hasRestrict();
4279
John McCall0953e762009-09-24 19:53:00 +00004280 // Iterate through all strict supersets of BaseCVR.
4281 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4282 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004283 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4284 // in the types.
4285 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4286 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00004287 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004288 if (!buildObjCPtr)
4289 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4290 else
4291 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004292 }
4293
4294 return true;
4295}
4296
Sebastian Redl78eb8742009-04-19 21:53:20 +00004297/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4298/// to the set of pointer types along with any more-qualified variants of
4299/// that type. For example, if @p Ty is "int const *", this routine
4300/// will add "int const *", "int const volatile *", "int const
4301/// restrict *", and "int const volatile restrict *" to the set of
4302/// pointer types. Returns true if the add of @p Ty itself succeeded,
4303/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00004304///
4305/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004306bool
4307BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4308 QualType Ty) {
4309 // Insert this type.
4310 if (!MemberPointerTypes.insert(Ty))
4311 return false;
4312
John McCall0953e762009-09-24 19:53:00 +00004313 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4314 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00004315
John McCall0953e762009-09-24 19:53:00 +00004316 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00004317 // Don't add qualified variants of arrays. For one, they're not allowed
4318 // (the qualifier would sink to the element type), and for another, the
4319 // only overload situation where it matters is subscript or pointer +- int,
4320 // and those shouldn't have qualifier variants anyway.
4321 if (PointeeTy->isArrayType())
4322 return true;
John McCall0953e762009-09-24 19:53:00 +00004323 const Type *ClassTy = PointerTy->getClass();
4324
4325 // Iterate through all strict supersets of the pointee type's CVR
4326 // qualifiers.
4327 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4328 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4329 if ((CVR | BaseCVR) != CVR) continue;
4330
4331 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4332 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00004333 }
4334
4335 return true;
4336}
4337
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004338/// AddTypesConvertedFrom - Add each of the types to which the type @p
4339/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00004340/// primarily interested in pointer types and enumeration types. We also
4341/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004342/// AllowUserConversions is true if we should look at the conversion
4343/// functions of a class type, and AllowExplicitConversions if we
4344/// should also include the explicit conversion functions of a class
4345/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00004346void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004347BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004348 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004349 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004350 bool AllowExplicitConversions,
4351 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004352 // Only deal with canonical types.
4353 Ty = Context.getCanonicalType(Ty);
4354
4355 // Look through reference types; they aren't part of the type of an
4356 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00004357 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004358 Ty = RefTy->getPointeeType();
4359
4360 // We don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004361 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004362
Sebastian Redla65b5512009-11-05 16:36:20 +00004363 // If we're dealing with an array type, decay to the pointer.
4364 if (Ty->isArrayType())
4365 Ty = SemaRef.Context.getArrayDecayedType(Ty);
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004366 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4367 PointerTypes.insert(Ty);
4368 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004369 // Insert our type, and its more-qualified variants, into the set
4370 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004371 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004372 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00004373 } else if (Ty->isMemberPointerType()) {
4374 // Member pointers are far easier, since the pointee can't be converted.
4375 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4376 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004377 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00004378 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004379 } else if (Ty->isVectorType()) {
4380 VectorTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004381 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004382 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00004383 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00004384 // No conversion functions in incomplete types.
4385 return;
4386 }
Mike Stump1eb44332009-09-09 15:08:12 +00004387
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004388 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00004389 const UnresolvedSetImpl *Conversions
Fariborz Jahanianca4fb042009-10-07 17:26:09 +00004390 = ClassDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00004391 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004392 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00004393 NamedDecl *D = I.getDecl();
4394 if (isa<UsingShadowDecl>(D))
4395 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004396
Mike Stump1eb44332009-09-09 15:08:12 +00004397 // Skip conversion function templates; they don't tell us anything
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004398 // about which builtin types we can convert to.
John McCall32daa422010-03-31 01:36:47 +00004399 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004400 continue;
4401
John McCall32daa422010-03-31 01:36:47 +00004402 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004403 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00004404 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004405 VisibleQuals);
4406 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004407 }
4408 }
4409 }
4410}
4411
Douglas Gregor19b7b152009-08-24 13:43:27 +00004412/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4413/// the volatile- and non-volatile-qualified assignment operators for the
4414/// given type to the candidate set.
4415static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4416 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00004417 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004418 unsigned NumArgs,
4419 OverloadCandidateSet &CandidateSet) {
4420 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00004421
Douglas Gregor19b7b152009-08-24 13:43:27 +00004422 // T& operator=(T&, T)
4423 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4424 ParamTypes[1] = T;
4425 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4426 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004427
Douglas Gregor19b7b152009-08-24 13:43:27 +00004428 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4429 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00004430 ParamTypes[0]
4431 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00004432 ParamTypes[1] = T;
4433 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00004434 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00004435 }
4436}
Mike Stump1eb44332009-09-09 15:08:12 +00004437
Sebastian Redl9994a342009-10-25 17:03:50 +00004438/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4439/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004440static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4441 Qualifiers VRQuals;
4442 const RecordType *TyRec;
4443 if (const MemberPointerType *RHSMPType =
4444 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004445 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004446 else
4447 TyRec = ArgExpr->getType()->getAs<RecordType>();
4448 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004449 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004450 VRQuals.addVolatile();
4451 VRQuals.addRestrict();
4452 return VRQuals;
4453 }
4454
4455 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00004456 if (!ClassDecl->hasDefinition())
4457 return VRQuals;
4458
John McCalleec51cf2010-01-20 00:46:10 +00004459 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00004460 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004461
John McCalleec51cf2010-01-20 00:46:10 +00004462 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004463 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00004464 NamedDecl *D = I.getDecl();
4465 if (isa<UsingShadowDecl>(D))
4466 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4467 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004468 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4469 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4470 CanTy = ResTypeRef->getPointeeType();
4471 // Need to go down the pointer/mempointer chain and add qualifiers
4472 // as see them.
4473 bool done = false;
4474 while (!done) {
4475 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4476 CanTy = ResTypePtr->getPointeeType();
4477 else if (const MemberPointerType *ResTypeMPtr =
4478 CanTy->getAs<MemberPointerType>())
4479 CanTy = ResTypeMPtr->getPointeeType();
4480 else
4481 done = true;
4482 if (CanTy.isVolatileQualified())
4483 VRQuals.addVolatile();
4484 if (CanTy.isRestrictQualified())
4485 VRQuals.addRestrict();
4486 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4487 return VRQuals;
4488 }
4489 }
4490 }
4491 return VRQuals;
4492}
4493
Douglas Gregor74253732008-11-19 15:42:04 +00004494/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4495/// operator overloads to the candidate set (C++ [over.built]), based
4496/// on the operator @p Op and the arguments given. For example, if the
4497/// operator is a binary '+', this routine might add "int
4498/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004499void
Mike Stump1eb44332009-09-09 15:08:12 +00004500Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004501 SourceLocation OpLoc,
Douglas Gregor74253732008-11-19 15:42:04 +00004502 Expr **Args, unsigned NumArgs,
4503 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004504 // The set of "promoted arithmetic types", which are the arithmetic
4505 // types are that preserved by promotion (C++ [over.built]p2). Note
4506 // that the first few of these types are the promoted integral
4507 // types; these types need to be first.
4508 // FIXME: What about complex?
4509 const unsigned FirstIntegralType = 0;
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00004510 const unsigned LastIntegralType = 15;
4511 const unsigned FirstPromotedIntegralType = 9,
4512 LastPromotedIntegralType = 15;
4513 const unsigned FirstPromotedArithmeticType = 9,
4514 LastPromotedArithmeticType = 18;
4515 const unsigned NumArithmeticTypes = 18;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004516 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump1eb44332009-09-09 15:08:12 +00004517 Context.BoolTy, Context.CharTy, Context.WCharTy,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00004518 Context.Char16Ty, Context.Char32Ty,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004519 Context.SignedCharTy, Context.ShortTy,
4520 Context.UnsignedCharTy, Context.UnsignedShortTy,
4521 Context.IntTy, Context.LongTy, Context.LongLongTy,
4522 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
4523 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
4524 };
Douglas Gregor652371a2009-10-21 22:01:30 +00004525 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
4526 "Invalid first promoted integral type");
4527 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4528 == Context.UnsignedLongLongTy &&
4529 "Invalid last promoted integral type");
4530 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
4531 "Invalid first promoted arithmetic type");
4532 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4533 == Context.LongDoubleTy &&
4534 "Invalid last promoted arithmetic type");
4535
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004536 // Find all of the types that the arguments can convert to, but only
4537 // if the operator we're looking at has built-in operator candidates
4538 // that make use of these types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004539 Qualifiers VisibleTypeConversionsQuals;
4540 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004541 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4542 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4543
Douglas Gregor5842ba92009-08-24 15:23:48 +00004544 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004545 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4546 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4547 OpLoc,
4548 true,
4549 (Op == OO_Exclaim ||
4550 Op == OO_AmpAmp ||
4551 Op == OO_PipePipe),
4552 VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004553
Douglas Gregor661b4932010-09-12 04:28:07 +00004554 // C++ [over.built]p1:
4555 // If there is a user-written candidate with the same name and parameter
4556 // types as a built-in candidate operator function, the built-in operator
4557 // function is hidden and is not included in the set of candidate functions.
4558 //
4559 // The text is actually in a note, but if we don't implement it then we end
4560 // up with ambiguities when the user provides an overloaded operator for
4561 // an enumeration type. Note that only enumeration types have this problem,
4562 // so we track which enumeration types we've seen operators for.
4563 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
4564 UserDefinedBinaryOperators;
4565
4566 if (CandidateTypes.enumeration_begin() != CandidateTypes.enumeration_end()) {
4567 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
4568 CEnd = CandidateSet.end();
4569 C != CEnd; ++C) {
4570 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
4571 continue;
4572
4573 // Check if the first parameter is of enumeration type.
4574 QualType FirstParamType
4575 = C->Function->getParamDecl(0)->getType().getUnqualifiedType();
4576 if (!FirstParamType->isEnumeralType())
4577 continue;
4578
4579 // Check if the second parameter is of enumeration type.
4580 QualType SecondParamType
4581 = C->Function->getParamDecl(1)->getType().getUnqualifiedType();
4582 if (!SecondParamType->isEnumeralType())
4583 continue;
4584
4585 // Add this operator to the set of known user-defined operators.
4586 UserDefinedBinaryOperators.insert(
4587 std::make_pair(Context.getCanonicalType(FirstParamType),
4588 Context.getCanonicalType(SecondParamType)));
4589 }
4590 }
4591
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004592 bool isComparison = false;
4593 switch (Op) {
4594 case OO_None:
4595 case NUM_OVERLOADED_OPERATORS:
4596 assert(false && "Expected an overloaded operator");
4597 break;
4598
Douglas Gregor74253732008-11-19 15:42:04 +00004599 case OO_Star: // '*' is either unary or binary
Mike Stump1eb44332009-09-09 15:08:12 +00004600 if (NumArgs == 1)
Douglas Gregor74253732008-11-19 15:42:04 +00004601 goto UnaryStar;
4602 else
4603 goto BinaryStar;
4604 break;
4605
4606 case OO_Plus: // '+' is either unary or binary
4607 if (NumArgs == 1)
4608 goto UnaryPlus;
4609 else
4610 goto BinaryPlus;
4611 break;
4612
4613 case OO_Minus: // '-' is either unary or binary
4614 if (NumArgs == 1)
4615 goto UnaryMinus;
4616 else
4617 goto BinaryMinus;
4618 break;
4619
4620 case OO_Amp: // '&' is either unary or binary
4621 if (NumArgs == 1)
4622 goto UnaryAmp;
4623 else
4624 goto BinaryAmp;
4625
4626 case OO_PlusPlus:
4627 case OO_MinusMinus:
4628 // C++ [over.built]p3:
4629 //
4630 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4631 // is either volatile or empty, there exist candidate operator
4632 // functions of the form
4633 //
4634 // VQ T& operator++(VQ T&);
4635 // T operator++(VQ T&, int);
4636 //
4637 // C++ [over.built]p4:
4638 //
4639 // For every pair (T, VQ), where T is an arithmetic type other
4640 // than bool, and VQ is either volatile or empty, there exist
4641 // candidate operator functions of the form
4642 //
4643 // VQ T& operator--(VQ T&);
4644 // T operator--(VQ T&, int);
Mike Stump1eb44332009-09-09 15:08:12 +00004645 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor74253732008-11-19 15:42:04 +00004646 Arith < NumArithmeticTypes; ++Arith) {
4647 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump1eb44332009-09-09 15:08:12 +00004648 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004649 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00004650
4651 // Non-volatile version.
4652 if (NumArgs == 1)
4653 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4654 else
4655 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004656 // heuristic to reduce number of builtin candidates in the set.
4657 // Add volatile version only if there are conversions to a volatile type.
4658 if (VisibleTypeConversionsQuals.hasVolatile()) {
4659 // Volatile version
4660 ParamTypes[0]
4661 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4662 if (NumArgs == 1)
4663 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4664 else
4665 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4666 }
Douglas Gregor74253732008-11-19 15:42:04 +00004667 }
4668
4669 // C++ [over.built]p5:
4670 //
4671 // For every pair (T, VQ), where T is a cv-qualified or
4672 // cv-unqualified object type, and VQ is either volatile or
4673 // empty, there exist candidate operator functions of the form
4674 //
4675 // T*VQ& operator++(T*VQ&);
4676 // T*VQ& operator--(T*VQ&);
4677 // T* operator++(T*VQ&, int);
4678 // T* operator--(T*VQ&, int);
4679 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4680 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4681 // Skip pointer types that aren't pointers to object types.
Eli Friedman13578692010-08-05 02:49:48 +00004682 if (!(*Ptr)->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00004683 continue;
4684
Mike Stump1eb44332009-09-09 15:08:12 +00004685 QualType ParamTypes[2] = {
4686 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00004687 };
Mike Stump1eb44332009-09-09 15:08:12 +00004688
Douglas Gregor74253732008-11-19 15:42:04 +00004689 // Without volatile
4690 if (NumArgs == 1)
4691 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4692 else
4693 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4694
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004695 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4696 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00004697 // With volatile
John McCall0953e762009-09-24 19:53:00 +00004698 ParamTypes[0]
4699 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor74253732008-11-19 15:42:04 +00004700 if (NumArgs == 1)
4701 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4702 else
4703 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4704 }
4705 }
4706 break;
4707
4708 UnaryStar:
4709 // C++ [over.built]p6:
4710 // For every cv-qualified or cv-unqualified object type T, there
4711 // exist candidate operator functions of the form
4712 //
4713 // T& operator*(T*);
4714 //
4715 // C++ [over.built]p7:
4716 // For every function type T, there exist candidate operator
4717 // functions of the form
4718 // T& operator*(T*);
4719 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4720 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4721 QualType ParamTy = *Ptr;
Argyrios Kyrtzidis42d0f2a2010-08-23 07:12:16 +00004722 QualType PointeeTy = ParamTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004723 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00004724 &ParamTy, Args, 1, CandidateSet);
4725 }
4726 break;
4727
4728 UnaryPlus:
4729 // C++ [over.built]p8:
4730 // For every type T, there exist candidate operator functions of
4731 // the form
4732 //
4733 // T* operator+(T*);
4734 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4735 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4736 QualType ParamTy = *Ptr;
4737 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4738 }
Mike Stump1eb44332009-09-09 15:08:12 +00004739
Douglas Gregor74253732008-11-19 15:42:04 +00004740 // Fall through
4741
4742 UnaryMinus:
4743 // C++ [over.built]p9:
4744 // For every promoted arithmetic type T, there exist candidate
4745 // operator functions of the form
4746 //
4747 // T operator+(T);
4748 // T operator-(T);
Mike Stump1eb44332009-09-09 15:08:12 +00004749 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor74253732008-11-19 15:42:04 +00004750 Arith < LastPromotedArithmeticType; ++Arith) {
4751 QualType ArithTy = ArithmeticTypes[Arith];
4752 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4753 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004754
4755 // Extension: We also add these operators for vector types.
4756 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4757 VecEnd = CandidateTypes.vector_end();
4758 Vec != VecEnd; ++Vec) {
4759 QualType VecTy = *Vec;
4760 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4761 }
Douglas Gregor74253732008-11-19 15:42:04 +00004762 break;
4763
4764 case OO_Tilde:
4765 // C++ [over.built]p10:
4766 // For every promoted integral type T, there exist candidate
4767 // operator functions of the form
4768 //
4769 // T operator~(T);
Mike Stump1eb44332009-09-09 15:08:12 +00004770 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor74253732008-11-19 15:42:04 +00004771 Int < LastPromotedIntegralType; ++Int) {
4772 QualType IntTy = ArithmeticTypes[Int];
4773 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4774 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004775
4776 // Extension: We also add this operator for vector types.
4777 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4778 VecEnd = CandidateTypes.vector_end();
4779 Vec != VecEnd; ++Vec) {
4780 QualType VecTy = *Vec;
4781 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4782 }
Douglas Gregor74253732008-11-19 15:42:04 +00004783 break;
4784
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004785 case OO_New:
4786 case OO_Delete:
4787 case OO_Array_New:
4788 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004789 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00004790 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004791 break;
4792
4793 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00004794 UnaryAmp:
4795 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004796 // C++ [over.match.oper]p3:
4797 // -- For the operator ',', the unary operator '&', or the
4798 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004799 break;
4800
Douglas Gregor19b7b152009-08-24 13:43:27 +00004801 case OO_EqualEqual:
4802 case OO_ExclaimEqual:
4803 // C++ [over.match.oper]p16:
Mike Stump1eb44332009-09-09 15:08:12 +00004804 // For every pointer to member type T, there exist candidate operator
4805 // functions of the form
Douglas Gregor19b7b152009-08-24 13:43:27 +00004806 //
4807 // bool operator==(T,T);
4808 // bool operator!=(T,T);
Mike Stump1eb44332009-09-09 15:08:12 +00004809 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor19b7b152009-08-24 13:43:27 +00004810 MemPtr = CandidateTypes.member_pointer_begin(),
4811 MemPtrEnd = CandidateTypes.member_pointer_end();
4812 MemPtr != MemPtrEnd;
4813 ++MemPtr) {
4814 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4815 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4816 }
Mike Stump1eb44332009-09-09 15:08:12 +00004817
Douglas Gregor19b7b152009-08-24 13:43:27 +00004818 // Fall through
Mike Stump1eb44332009-09-09 15:08:12 +00004819
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004820 case OO_Less:
4821 case OO_Greater:
4822 case OO_LessEqual:
4823 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004824 // C++ [over.built]p15:
4825 //
4826 // For every pointer or enumeration type T, there exist
4827 // candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004828 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004829 // bool operator<(T, T);
4830 // bool operator>(T, T);
4831 // bool operator<=(T, T);
4832 // bool operator>=(T, T);
4833 // bool operator==(T, T);
4834 // bool operator!=(T, T);
4835 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4836 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4837 QualType ParamTypes[2] = { *Ptr, *Ptr };
4838 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4839 }
Mike Stump1eb44332009-09-09 15:08:12 +00004840 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004841 = CandidateTypes.enumeration_begin();
4842 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4843 QualType ParamTypes[2] = { *Enum, *Enum };
Douglas Gregor661b4932010-09-12 04:28:07 +00004844 CanQualType CanonType = Context.getCanonicalType(*Enum);
4845 if (!UserDefinedBinaryOperators.count(
4846 std::make_pair(CanonType, CanonType)))
4847 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004848 }
4849
4850 // Fall through.
4851 isComparison = true;
4852
Douglas Gregor74253732008-11-19 15:42:04 +00004853 BinaryPlus:
4854 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004855 if (!isComparison) {
4856 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4857
4858 // C++ [over.built]p13:
4859 //
4860 // For every cv-qualified or cv-unqualified object type T
4861 // there exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004862 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004863 // T* operator+(T*, ptrdiff_t);
4864 // T& operator[](T*, ptrdiff_t); [BELOW]
4865 // T* operator-(T*, ptrdiff_t);
4866 // T* operator+(ptrdiff_t, T*);
4867 // T& operator[](ptrdiff_t, T*); [BELOW]
4868 //
4869 // C++ [over.built]p14:
4870 //
4871 // For every T, where T is a pointer to object type, there
4872 // exist candidate operator functions of the form
4873 //
4874 // ptrdiff_t operator-(T, T);
Mike Stump1eb44332009-09-09 15:08:12 +00004875 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004876 = CandidateTypes.pointer_begin();
4877 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4878 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4879
4880 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4881 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4882
4883 if (Op == OO_Plus) {
4884 // T* operator+(ptrdiff_t, T*);
4885 ParamTypes[0] = ParamTypes[1];
4886 ParamTypes[1] = *Ptr;
4887 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4888 } else {
4889 // ptrdiff_t operator-(T, T);
4890 ParamTypes[1] = *Ptr;
4891 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4892 Args, 2, CandidateSet);
4893 }
4894 }
4895 }
4896 // Fall through
4897
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004898 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00004899 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004900 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004901 // C++ [over.built]p12:
4902 //
4903 // For every pair of promoted arithmetic types L and R, there
4904 // exist candidate operator functions of the form
4905 //
4906 // LR operator*(L, R);
4907 // LR operator/(L, R);
4908 // LR operator+(L, R);
4909 // LR operator-(L, R);
4910 // bool operator<(L, R);
4911 // bool operator>(L, R);
4912 // bool operator<=(L, R);
4913 // bool operator>=(L, R);
4914 // bool operator==(L, R);
4915 // bool operator!=(L, R);
4916 //
4917 // where LR is the result of the usual arithmetic conversions
4918 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004919 //
4920 // C++ [over.built]p24:
4921 //
4922 // For every pair of promoted arithmetic types L and R, there exist
4923 // candidate operator functions of the form
4924 //
4925 // LR operator?(bool, L, R);
4926 //
4927 // where LR is the result of the usual arithmetic conversions
4928 // between types L and R.
4929 // Our candidates ignore the first parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00004930 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004931 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004932 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004933 Right < LastPromotedArithmeticType; ++Right) {
4934 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00004935 QualType Result
4936 = isComparison
4937 ? Context.BoolTy
4938 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004939 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4940 }
4941 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004942
4943 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
4944 // conditional operator for vector types.
4945 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4946 Vec1End = CandidateTypes.vector_end();
4947 Vec1 != Vec1End; ++Vec1)
4948 for (BuiltinCandidateTypeSet::iterator
4949 Vec2 = CandidateTypes.vector_begin(),
4950 Vec2End = CandidateTypes.vector_end();
4951 Vec2 != Vec2End; ++Vec2) {
4952 QualType LandR[2] = { *Vec1, *Vec2 };
4953 QualType Result;
4954 if (isComparison)
4955 Result = Context.BoolTy;
4956 else {
4957 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
4958 Result = *Vec1;
4959 else
4960 Result = *Vec2;
4961 }
4962
4963 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4964 }
4965
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004966 break;
4967
4968 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00004969 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004970 case OO_Caret:
4971 case OO_Pipe:
4972 case OO_LessLess:
4973 case OO_GreaterGreater:
4974 // C++ [over.built]p17:
4975 //
4976 // For every pair of promoted integral types L and R, there
4977 // exist candidate operator functions of the form
4978 //
4979 // LR operator%(L, R);
4980 // LR operator&(L, R);
4981 // LR operator^(L, R);
4982 // LR operator|(L, R);
4983 // L operator<<(L, R);
4984 // L operator>>(L, R);
4985 //
4986 // where LR is the result of the usual arithmetic conversions
4987 // between types L and R.
Mike Stump1eb44332009-09-09 15:08:12 +00004988 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004989 Left < LastPromotedIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004990 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004991 Right < LastPromotedIntegralType; ++Right) {
4992 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4993 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4994 ? LandR[0]
Eli Friedmana95d7572009-08-19 07:44:53 +00004995 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004996 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4997 }
4998 }
4999 break;
5000
5001 case OO_Equal:
5002 // C++ [over.built]p20:
5003 //
5004 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00005005 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005006 // empty, there exist candidate operator functions of the form
5007 //
5008 // VQ T& operator=(VQ T&, T);
Douglas Gregor19b7b152009-08-24 13:43:27 +00005009 for (BuiltinCandidateTypeSet::iterator
5010 Enum = CandidateTypes.enumeration_begin(),
5011 EnumEnd = CandidateTypes.enumeration_end();
5012 Enum != EnumEnd; ++Enum)
Mike Stump1eb44332009-09-09 15:08:12 +00005013 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00005014 CandidateSet);
5015 for (BuiltinCandidateTypeSet::iterator
5016 MemPtr = CandidateTypes.member_pointer_begin(),
5017 MemPtrEnd = CandidateTypes.member_pointer_end();
5018 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump1eb44332009-09-09 15:08:12 +00005019 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00005020 CandidateSet);
Douglas Gregor26bcf672010-05-19 03:21:00 +00005021
5022 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005023
5024 case OO_PlusEqual:
5025 case OO_MinusEqual:
5026 // C++ [over.built]p19:
5027 //
5028 // For every pair (T, VQ), where T is any type and VQ is either
5029 // volatile or empty, there exist candidate operator functions
5030 // of the form
5031 //
5032 // T*VQ& operator=(T*VQ&, T*);
5033 //
5034 // C++ [over.built]p21:
5035 //
5036 // For every pair (T, VQ), where T is a cv-qualified or
5037 // cv-unqualified object type and VQ is either volatile or
5038 // empty, there exist candidate operator functions of the form
5039 //
5040 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5041 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5042 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
5043 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5044 QualType ParamTypes[2];
5045 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
5046
5047 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005048 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005049 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5050 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005051
Fariborz Jahanian8621d012009-10-19 21:30:45 +00005052 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5053 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00005054 // volatile version
John McCall0953e762009-09-24 19:53:00 +00005055 ParamTypes[0]
5056 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005057 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5058 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00005059 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005060 }
5061 // Fall through.
5062
5063 case OO_StarEqual:
5064 case OO_SlashEqual:
5065 // C++ [over.built]p18:
5066 //
5067 // For every triple (L, VQ, R), where L is an arithmetic type,
5068 // VQ is either volatile or empty, and R is a promoted
5069 // arithmetic type, there exist candidate operator functions of
5070 // the form
5071 //
5072 // VQ L& operator=(VQ L&, R);
5073 // VQ L& operator*=(VQ L&, R);
5074 // VQ L& operator/=(VQ L&, R);
5075 // VQ L& operator+=(VQ L&, R);
5076 // VQ L& operator-=(VQ L&, R);
5077 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00005078 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005079 Right < LastPromotedArithmeticType; ++Right) {
5080 QualType ParamTypes[2];
5081 ParamTypes[1] = ArithmeticTypes[Right];
5082
5083 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005084 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005085 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5086 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005087
5088 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanian8621d012009-10-19 21:30:45 +00005089 if (VisibleTypeConversionsQuals.hasVolatile()) {
5090 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
5091 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5092 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5093 /*IsAssigmentOperator=*/Op == OO_Equal);
5094 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005095 }
5096 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00005097
5098 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5099 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
5100 Vec1End = CandidateTypes.vector_end();
5101 Vec1 != Vec1End; ++Vec1)
5102 for (BuiltinCandidateTypeSet::iterator
5103 Vec2 = CandidateTypes.vector_begin(),
5104 Vec2End = CandidateTypes.vector_end();
5105 Vec2 != Vec2End; ++Vec2) {
5106 QualType ParamTypes[2];
5107 ParamTypes[1] = *Vec2;
5108 // Add this built-in operator as a candidate (VQ is empty).
5109 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
5110 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5111 /*IsAssigmentOperator=*/Op == OO_Equal);
5112
5113 // Add this built-in operator as a candidate (VQ is 'volatile').
5114 if (VisibleTypeConversionsQuals.hasVolatile()) {
5115 ParamTypes[0] = Context.getVolatileType(*Vec1);
5116 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5117 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5118 /*IsAssigmentOperator=*/Op == OO_Equal);
5119 }
5120 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005121 break;
5122
5123 case OO_PercentEqual:
5124 case OO_LessLessEqual:
5125 case OO_GreaterGreaterEqual:
5126 case OO_AmpEqual:
5127 case OO_CaretEqual:
5128 case OO_PipeEqual:
5129 // C++ [over.built]p22:
5130 //
5131 // For every triple (L, VQ, R), where L is an integral type, VQ
5132 // is either volatile or empty, and R is a promoted integral
5133 // type, there exist candidate operator functions of the form
5134 //
5135 // VQ L& operator%=(VQ L&, R);
5136 // VQ L& operator<<=(VQ L&, R);
5137 // VQ L& operator>>=(VQ L&, R);
5138 // VQ L& operator&=(VQ L&, R);
5139 // VQ L& operator^=(VQ L&, R);
5140 // VQ L& operator|=(VQ L&, R);
5141 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00005142 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005143 Right < LastPromotedIntegralType; ++Right) {
5144 QualType ParamTypes[2];
5145 ParamTypes[1] = ArithmeticTypes[Right];
5146
5147 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005148 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005149 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian035c46f2009-10-20 00:04:40 +00005150 if (VisibleTypeConversionsQuals.hasVolatile()) {
5151 // Add this built-in operator as a candidate (VQ is 'volatile').
5152 ParamTypes[0] = ArithmeticTypes[Left];
5153 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
5154 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5155 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5156 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005157 }
5158 }
5159 break;
5160
Douglas Gregor74253732008-11-19 15:42:04 +00005161 case OO_Exclaim: {
5162 // C++ [over.operator]p23:
5163 //
5164 // There also exist candidate operator functions of the form
5165 //
Mike Stump1eb44332009-09-09 15:08:12 +00005166 // bool operator!(bool);
Douglas Gregor74253732008-11-19 15:42:04 +00005167 // bool operator&&(bool, bool); [BELOW]
5168 // bool operator||(bool, bool); [BELOW]
5169 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005170 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5171 /*IsAssignmentOperator=*/false,
5172 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00005173 break;
5174 }
5175
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005176 case OO_AmpAmp:
5177 case OO_PipePipe: {
5178 // C++ [over.operator]p23:
5179 //
5180 // There also exist candidate operator functions of the form
5181 //
Douglas Gregor74253732008-11-19 15:42:04 +00005182 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005183 // bool operator&&(bool, bool);
5184 // bool operator||(bool, bool);
5185 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005186 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5187 /*IsAssignmentOperator=*/false,
5188 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005189 break;
5190 }
5191
5192 case OO_Subscript:
5193 // C++ [over.built]p13:
5194 //
5195 // For every cv-qualified or cv-unqualified object type T there
5196 // exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00005197 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005198 // T* operator+(T*, ptrdiff_t); [ABOVE]
5199 // T& operator[](T*, ptrdiff_t);
5200 // T* operator-(T*, ptrdiff_t); [ABOVE]
5201 // T* operator+(ptrdiff_t, T*); [ABOVE]
5202 // T& operator[](ptrdiff_t, T*);
5203 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
5204 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5205 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Argyrios Kyrtzidis42d0f2a2010-08-23 07:12:16 +00005206 QualType PointeeType = (*Ptr)->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005207 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005208
5209 // T& operator[](T*, ptrdiff_t)
5210 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5211
5212 // T& operator[](ptrdiff_t, T*);
5213 ParamTypes[0] = ParamTypes[1];
5214 ParamTypes[1] = *Ptr;
5215 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregor26bcf672010-05-19 03:21:00 +00005216 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005217 break;
5218
5219 case OO_ArrowStar:
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005220 // C++ [over.built]p11:
5221 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5222 // C1 is the same type as C2 or is a derived class of C2, T is an object
5223 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5224 // there exist candidate operator functions of the form
5225 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5226 // where CV12 is the union of CV1 and CV2.
5227 {
5228 for (BuiltinCandidateTypeSet::iterator Ptr =
5229 CandidateTypes.pointer_begin();
5230 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5231 QualType C1Ty = (*Ptr);
5232 QualType C1;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00005233 QualifierCollector Q1;
Argyrios Kyrtzidis42d0f2a2010-08-23 07:12:16 +00005234 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5235 if (!isa<RecordType>(C1))
5236 continue;
5237 // heuristic to reduce number of builtin candidates in the set.
5238 // Add volatile/restrict version only if there are conversions to a
5239 // volatile/restrict type.
5240 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5241 continue;
5242 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5243 continue;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005244 for (BuiltinCandidateTypeSet::iterator
5245 MemPtr = CandidateTypes.member_pointer_begin(),
5246 MemPtrEnd = CandidateTypes.member_pointer_end();
5247 MemPtr != MemPtrEnd; ++MemPtr) {
5248 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5249 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian43036972009-10-07 16:56:50 +00005250 C2 = C2.getUnqualifiedType();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005251 if (C1 != C2 && !IsDerivedFrom(C1, C2))
5252 break;
5253 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5254 // build CV12 T&
5255 QualType T = mptr->getPointeeType();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005256 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5257 T.isVolatileQualified())
5258 continue;
5259 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5260 T.isRestrictQualified())
5261 continue;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00005262 T = Q1.apply(T);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005263 QualType ResultTy = Context.getLValueReferenceType(T);
5264 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5265 }
5266 }
5267 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005268 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005269
5270 case OO_Conditional:
5271 // Note that we don't consider the first argument, since it has been
5272 // contextually converted to bool long ago. The candidates below are
5273 // therefore added as binary.
5274 //
Douglas Gregor5a1f97e2010-10-15 00:50:56 +00005275 // C++ [over.built]p25:
5276 // For every type T, where T is a pointer, pointer-to-member, or scoped
5277 // enumeration type, there exist candidate operator functions of the form
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005278 //
5279 // T operator?(bool, T, T);
5280 //
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005281 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
5282 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
5283 QualType ParamTypes[2] = { *Ptr, *Ptr };
5284 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5285 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00005286 for (BuiltinCandidateTypeSet::iterator Ptr =
5287 CandidateTypes.member_pointer_begin(),
5288 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
5289 QualType ParamTypes[2] = { *Ptr, *Ptr };
5290 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5291 }
Douglas Gregor5a1f97e2010-10-15 00:50:56 +00005292 if (getLangOptions().CPlusPlus0x)
5293 for (BuiltinCandidateTypeSet::iterator Enum =
5294 CandidateTypes.enumeration_begin(),
5295 E = CandidateTypes.enumeration_end(); Enum != E; ++Enum) {
5296 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
5297 continue;
5298 QualType ParamTypes[2] = { *Enum, *Enum };
5299 AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
5300 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005301 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005302 }
5303}
5304
Douglas Gregorfa047642009-02-04 00:32:51 +00005305/// \brief Add function candidates found via argument-dependent lookup
5306/// to the set of overloading candidates.
5307///
5308/// This routine performs argument-dependent name lookup based on the
5309/// given function name (which may also be an operator name) and adds
5310/// all of the overload candidates found by ADL to the overload
5311/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00005312void
Douglas Gregorfa047642009-02-04 00:32:51 +00005313Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00005314 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00005315 Expr **Args, unsigned NumArgs,
John McCalld5532b62009-11-23 01:53:49 +00005316 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005317 OverloadCandidateSet& CandidateSet,
5318 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00005319 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00005320
John McCalla113e722010-01-26 06:04:06 +00005321 // FIXME: This approach for uniquing ADL results (and removing
5322 // redundant candidates from the set) relies on pointer-equality,
5323 // which means we need to key off the canonical decl. However,
5324 // always going back to the canonical decl might not get us the
5325 // right set of default arguments. What default arguments are
5326 // we supposed to consider on ADL candidates, anyway?
5327
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005328 // FIXME: Pass in the explicit template arguments?
John McCall7edb5fd2010-01-26 07:16:45 +00005329 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00005330
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005331 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005332 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5333 CandEnd = CandidateSet.end();
5334 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00005335 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00005336 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00005337 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00005338 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00005339 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005340
5341 // For each of the ADL candidates we found, add it to the overload
5342 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00005343 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00005344 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00005345 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00005346 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005347 continue;
5348
John McCall9aa472c2010-03-19 07:35:19 +00005349 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00005350 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005351 } else
John McCall6e266892010-01-26 03:27:55 +00005352 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00005353 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00005354 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00005355 }
Douglas Gregorfa047642009-02-04 00:32:51 +00005356}
5357
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005358/// isBetterOverloadCandidate - Determines whether the first overload
5359/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00005360bool
John McCall120d63c2010-08-24 20:38:10 +00005361isBetterOverloadCandidate(Sema &S,
5362 const OverloadCandidate& Cand1,
5363 const OverloadCandidate& Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005364 SourceLocation Loc,
5365 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005366 // Define viable functions to be better candidates than non-viable
5367 // functions.
5368 if (!Cand2.Viable)
5369 return Cand1.Viable;
5370 else if (!Cand1.Viable)
5371 return false;
5372
Douglas Gregor88a35142008-12-22 05:46:06 +00005373 // C++ [over.match.best]p1:
5374 //
5375 // -- if F is a static member function, ICS1(F) is defined such
5376 // that ICS1(F) is neither better nor worse than ICS1(G) for
5377 // any function G, and, symmetrically, ICS1(G) is neither
5378 // better nor worse than ICS1(F).
5379 unsigned StartArg = 0;
5380 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5381 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005382
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005383 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00005384 // A viable function F1 is defined to be a better function than another
5385 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005386 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005387 unsigned NumArgs = Cand1.Conversions.size();
5388 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5389 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005390 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00005391 switch (CompareImplicitConversionSequences(S,
5392 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005393 Cand2.Conversions[ArgIdx])) {
5394 case ImplicitConversionSequence::Better:
5395 // Cand1 has a better conversion sequence.
5396 HasBetterConversion = true;
5397 break;
5398
5399 case ImplicitConversionSequence::Worse:
5400 // Cand1 can't be better than Cand2.
5401 return false;
5402
5403 case ImplicitConversionSequence::Indistinguishable:
5404 // Do nothing.
5405 break;
5406 }
5407 }
5408
Mike Stump1eb44332009-09-09 15:08:12 +00005409 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005410 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005411 if (HasBetterConversion)
5412 return true;
5413
Mike Stump1eb44332009-09-09 15:08:12 +00005414 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005415 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00005416 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005417 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5418 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005419
5420 // -- F1 and F2 are function template specializations, and the function
5421 // template for F1 is more specialized than the template for F2
5422 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005423 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00005424 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5425 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005426 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00005427 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5428 Cand2.Function->getPrimaryTemplate(),
5429 Loc,
Douglas Gregor5d7d3752009-09-14 23:02:14 +00005430 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5431 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005432 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005433
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005434 // -- the context is an initialization by user-defined conversion
5435 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5436 // from the return type of F1 to the destination type (i.e.,
5437 // the type of the entity being initialized) is a better
5438 // conversion sequence than the standard conversion sequence
5439 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005440 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00005441 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005442 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall120d63c2010-08-24 20:38:10 +00005443 switch (CompareStandardConversionSequences(S,
5444 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005445 Cand2.FinalConversion)) {
5446 case ImplicitConversionSequence::Better:
5447 // Cand1 has a better conversion sequence.
5448 return true;
5449
5450 case ImplicitConversionSequence::Worse:
5451 // Cand1 can't be better than Cand2.
5452 return false;
5453
5454 case ImplicitConversionSequence::Indistinguishable:
5455 // Do nothing
5456 break;
5457 }
5458 }
5459
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005460 return false;
5461}
5462
Mike Stump1eb44332009-09-09 15:08:12 +00005463/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00005464/// within an overload candidate set.
5465///
5466/// \param CandidateSet the set of candidate functions.
5467///
5468/// \param Loc the location of the function name (or operator symbol) for
5469/// which overload resolution occurs.
5470///
Mike Stump1eb44332009-09-09 15:08:12 +00005471/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00005472/// function, Best points to the candidate function found.
5473///
5474/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00005475OverloadingResult
5476OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005477 iterator& Best,
5478 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005479 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00005480 Best = end();
5481 for (iterator Cand = begin(); Cand != end(); ++Cand) {
5482 if (Cand->Viable)
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005483 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
5484 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005485 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005486 }
5487
5488 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00005489 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005490 return OR_No_Viable_Function;
5491
5492 // Make sure that this function is better than every other viable
5493 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00005494 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00005495 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005496 Cand != Best &&
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005497 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
5498 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00005499 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005500 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005501 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005502 }
Mike Stump1eb44332009-09-09 15:08:12 +00005503
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005504 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005505 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00005506 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005507 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005508 return OR_Deleted;
5509
Douglas Gregore0762c92009-06-19 23:52:42 +00005510 // C++ [basic.def.odr]p2:
5511 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00005512 // when referred to from a potentially-evaluated expression. [Note: this
5513 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00005514 // (clause 13), user-defined conversions (12.3.2), allocation function for
5515 // placement new (5.3.4), as well as non-default initialization (8.5).
5516 if (Best->Function)
John McCall120d63c2010-08-24 20:38:10 +00005517 S.MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor9b623632010-10-12 23:32:35 +00005518
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005519 return OR_Success;
5520}
5521
John McCall3c80f572010-01-12 02:15:36 +00005522namespace {
5523
5524enum OverloadCandidateKind {
5525 oc_function,
5526 oc_method,
5527 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00005528 oc_function_template,
5529 oc_method_template,
5530 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00005531 oc_implicit_default_constructor,
5532 oc_implicit_copy_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00005533 oc_implicit_copy_assignment
John McCall3c80f572010-01-12 02:15:36 +00005534};
5535
John McCall220ccbf2010-01-13 00:25:19 +00005536OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5537 FunctionDecl *Fn,
5538 std::string &Description) {
5539 bool isTemplate = false;
5540
5541 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5542 isTemplate = true;
5543 Description = S.getTemplateArgumentBindingsText(
5544 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5545 }
John McCallb1622a12010-01-06 09:43:14 +00005546
5547 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00005548 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00005549 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00005550
John McCall3c80f572010-01-12 02:15:36 +00005551 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5552 : oc_implicit_default_constructor;
John McCallb1622a12010-01-06 09:43:14 +00005553 }
5554
5555 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5556 // This actually gets spelled 'candidate function' for now, but
5557 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00005558 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00005559 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00005560
Douglas Gregor3e9438b2010-09-27 22:37:28 +00005561 assert(Meth->isCopyAssignmentOperator()
John McCallb1622a12010-01-06 09:43:14 +00005562 && "implicit method is not copy assignment operator?");
John McCall3c80f572010-01-12 02:15:36 +00005563 return oc_implicit_copy_assignment;
5564 }
5565
John McCall220ccbf2010-01-13 00:25:19 +00005566 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00005567}
5568
5569} // end anonymous namespace
5570
5571// Notes the location of an overload candidate.
5572void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCall220ccbf2010-01-13 00:25:19 +00005573 std::string FnDesc;
5574 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5575 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5576 << (unsigned) K << FnDesc;
John McCallb1622a12010-01-06 09:43:14 +00005577}
5578
John McCall1d318332010-01-12 00:44:57 +00005579/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5580/// "lead" diagnostic; it will be given two arguments, the source and
5581/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00005582void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
5583 Sema &S,
5584 SourceLocation CaretLoc,
5585 const PartialDiagnostic &PDiag) const {
5586 S.Diag(CaretLoc, PDiag)
5587 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall1d318332010-01-12 00:44:57 +00005588 for (AmbiguousConversionSequence::const_iterator
John McCall120d63c2010-08-24 20:38:10 +00005589 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
5590 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00005591 }
John McCall81201622010-01-08 04:41:39 +00005592}
5593
John McCall1d318332010-01-12 00:44:57 +00005594namespace {
5595
John McCalladbb8f82010-01-13 09:16:55 +00005596void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5597 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5598 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00005599 assert(Cand->Function && "for now, candidate must be a function");
5600 FunctionDecl *Fn = Cand->Function;
5601
5602 // There's a conversion slot for the object argument if this is a
5603 // non-constructor method. Note that 'I' corresponds the
5604 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00005605 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00005606 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00005607 if (I == 0)
5608 isObjectArgument = true;
5609 else
5610 I--;
John McCall220ccbf2010-01-13 00:25:19 +00005611 }
5612
John McCall220ccbf2010-01-13 00:25:19 +00005613 std::string FnDesc;
5614 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5615
John McCalladbb8f82010-01-13 09:16:55 +00005616 Expr *FromExpr = Conv.Bad.FromExpr;
5617 QualType FromTy = Conv.Bad.getFromType();
5618 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00005619
John McCall5920dbb2010-02-02 02:42:52 +00005620 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00005621 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00005622 Expr *E = FromExpr->IgnoreParens();
5623 if (isa<UnaryOperator>(E))
5624 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00005625 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00005626
5627 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5628 << (unsigned) FnKind << FnDesc
5629 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5630 << ToTy << Name << I+1;
5631 return;
5632 }
5633
John McCall258b2032010-01-23 08:10:49 +00005634 // Do some hand-waving analysis to see if the non-viability is due
5635 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00005636 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5637 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5638 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5639 CToTy = RT->getPointeeType();
5640 else {
5641 // TODO: detect and diagnose the full richness of const mismatches.
5642 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5643 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5644 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5645 }
5646
5647 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5648 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5649 // It is dumb that we have to do this here.
5650 while (isa<ArrayType>(CFromTy))
5651 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5652 while (isa<ArrayType>(CToTy))
5653 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5654
5655 Qualifiers FromQs = CFromTy.getQualifiers();
5656 Qualifiers ToQs = CToTy.getQualifiers();
5657
5658 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5659 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5660 << (unsigned) FnKind << FnDesc
5661 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5662 << FromTy
5663 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5664 << (unsigned) isObjectArgument << I+1;
5665 return;
5666 }
5667
5668 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5669 assert(CVR && "unexpected qualifiers mismatch");
5670
5671 if (isObjectArgument) {
5672 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5673 << (unsigned) FnKind << FnDesc
5674 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5675 << FromTy << (CVR - 1);
5676 } else {
5677 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5678 << (unsigned) FnKind << FnDesc
5679 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5680 << FromTy << (CVR - 1) << I+1;
5681 }
5682 return;
5683 }
5684
John McCall258b2032010-01-23 08:10:49 +00005685 // Diagnose references or pointers to incomplete types differently,
5686 // since it's far from impossible that the incompleteness triggered
5687 // the failure.
5688 QualType TempFromTy = FromTy.getNonReferenceType();
5689 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5690 TempFromTy = PTy->getPointeeType();
5691 if (TempFromTy->isIncompleteType()) {
5692 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5693 << (unsigned) FnKind << FnDesc
5694 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5695 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5696 return;
5697 }
5698
Douglas Gregor85789812010-06-30 23:01:39 +00005699 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005700 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00005701 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
5702 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
5703 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5704 FromPtrTy->getPointeeType()) &&
5705 !FromPtrTy->getPointeeType()->isIncompleteType() &&
5706 !ToPtrTy->getPointeeType()->isIncompleteType() &&
5707 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
5708 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005709 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00005710 }
5711 } else if (const ObjCObjectPointerType *FromPtrTy
5712 = FromTy->getAs<ObjCObjectPointerType>()) {
5713 if (const ObjCObjectPointerType *ToPtrTy
5714 = ToTy->getAs<ObjCObjectPointerType>())
5715 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
5716 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
5717 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5718 FromPtrTy->getPointeeType()) &&
5719 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005720 BaseToDerivedConversion = 2;
5721 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
5722 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
5723 !FromTy->isIncompleteType() &&
5724 !ToRefTy->getPointeeType()->isIncompleteType() &&
5725 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
5726 BaseToDerivedConversion = 3;
5727 }
5728
5729 if (BaseToDerivedConversion) {
Douglas Gregor85789812010-06-30 23:01:39 +00005730 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005731 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00005732 << (unsigned) FnKind << FnDesc
5733 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005734 << (BaseToDerivedConversion - 1)
Douglas Gregor85789812010-06-30 23:01:39 +00005735 << FromTy << ToTy << I+1;
5736 return;
5737 }
5738
John McCall651f3ee2010-01-14 03:28:57 +00005739 // TODO: specialize more based on the kind of mismatch
John McCall220ccbf2010-01-13 00:25:19 +00005740 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5741 << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00005742 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalle81e15e2010-01-14 00:56:20 +00005743 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCalladbb8f82010-01-13 09:16:55 +00005744}
5745
5746void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5747 unsigned NumFormalArgs) {
5748 // TODO: treat calls to a missing default constructor as a special case
5749
5750 FunctionDecl *Fn = Cand->Function;
5751 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5752
5753 unsigned MinParams = Fn->getMinRequiredArguments();
5754
5755 // at least / at most / exactly
Douglas Gregora18592e2010-05-08 18:13:28 +00005756 // FIXME: variadic templates "at most" should account for parameter packs
John McCalladbb8f82010-01-13 09:16:55 +00005757 unsigned mode, modeCount;
5758 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00005759 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5760 (Cand->FailureKind == ovl_fail_bad_deduction &&
5761 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCalladbb8f82010-01-13 09:16:55 +00005762 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5763 mode = 0; // "at least"
5764 else
5765 mode = 2; // "exactly"
5766 modeCount = MinParams;
5767 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00005768 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5769 (Cand->FailureKind == ovl_fail_bad_deduction &&
5770 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00005771 if (MinParams != FnTy->getNumArgs())
5772 mode = 1; // "at most"
5773 else
5774 mode = 2; // "exactly"
5775 modeCount = FnTy->getNumArgs();
5776 }
5777
5778 std::string Description;
5779 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5780
5781 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregora18592e2010-05-08 18:13:28 +00005782 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5783 << modeCount << NumFormalArgs;
John McCall220ccbf2010-01-13 00:25:19 +00005784}
5785
John McCall342fec42010-02-01 18:53:26 +00005786/// Diagnose a failed template-argument deduction.
5787void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5788 Expr **Args, unsigned NumArgs) {
5789 FunctionDecl *Fn = Cand->Function; // pattern
5790
Douglas Gregora9333192010-05-08 17:41:32 +00005791 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00005792 NamedDecl *ParamD;
5793 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5794 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5795 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00005796 switch (Cand->DeductionFailure.Result) {
5797 case Sema::TDK_Success:
5798 llvm_unreachable("TDK_success while diagnosing bad deduction");
5799
5800 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00005801 assert(ParamD && "no parameter found for incomplete deduction result");
5802 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5803 << ParamD->getDeclName();
5804 return;
5805 }
5806
John McCall57e97782010-08-05 09:05:08 +00005807 case Sema::TDK_Underqualified: {
5808 assert(ParamD && "no parameter found for bad qualifiers deduction result");
5809 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
5810
5811 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
5812
5813 // Param will have been canonicalized, but it should just be a
5814 // qualified version of ParamD, so move the qualifiers to that.
5815 QualifierCollector Qs(S.Context);
5816 Qs.strip(Param);
5817 QualType NonCanonParam = Qs.apply(TParam->getTypeForDecl());
5818 assert(S.Context.hasSameType(Param, NonCanonParam));
5819
5820 // Arg has also been canonicalized, but there's nothing we can do
5821 // about that. It also doesn't matter as much, because it won't
5822 // have any template parameters in it (because deduction isn't
5823 // done on dependent types).
5824 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
5825
5826 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
5827 << ParamD->getDeclName() << Arg << NonCanonParam;
5828 return;
5829 }
5830
5831 case Sema::TDK_Inconsistent: {
Douglas Gregorf1a84452010-05-08 19:15:54 +00005832 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00005833 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00005834 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00005835 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00005836 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00005837 which = 1;
5838 else {
Douglas Gregora9333192010-05-08 17:41:32 +00005839 which = 2;
5840 }
5841
5842 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5843 << which << ParamD->getDeclName()
5844 << *Cand->DeductionFailure.getFirstArg()
5845 << *Cand->DeductionFailure.getSecondArg();
5846 return;
5847 }
Douglas Gregora18592e2010-05-08 18:13:28 +00005848
Douglas Gregorf1a84452010-05-08 19:15:54 +00005849 case Sema::TDK_InvalidExplicitArguments:
5850 assert(ParamD && "no parameter found for invalid explicit arguments");
5851 if (ParamD->getDeclName())
5852 S.Diag(Fn->getLocation(),
5853 diag::note_ovl_candidate_explicit_arg_mismatch_named)
5854 << ParamD->getDeclName();
5855 else {
5856 int index = 0;
5857 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5858 index = TTP->getIndex();
5859 else if (NonTypeTemplateParmDecl *NTTP
5860 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5861 index = NTTP->getIndex();
5862 else
5863 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
5864 S.Diag(Fn->getLocation(),
5865 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
5866 << (index + 1);
5867 }
5868 return;
5869
Douglas Gregora18592e2010-05-08 18:13:28 +00005870 case Sema::TDK_TooManyArguments:
5871 case Sema::TDK_TooFewArguments:
5872 DiagnoseArityMismatch(S, Cand, NumArgs);
5873 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00005874
5875 case Sema::TDK_InstantiationDepth:
5876 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
5877 return;
5878
5879 case Sema::TDK_SubstitutionFailure: {
5880 std::string ArgString;
5881 if (TemplateArgumentList *Args
5882 = Cand->DeductionFailure.getTemplateArgumentList())
5883 ArgString = S.getTemplateArgumentBindingsText(
5884 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
5885 *Args);
5886 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
5887 << ArgString;
5888 return;
5889 }
Douglas Gregora9333192010-05-08 17:41:32 +00005890
John McCall342fec42010-02-01 18:53:26 +00005891 // TODO: diagnose these individually, then kill off
5892 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00005893 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00005894 case Sema::TDK_FailedOverloadResolution:
5895 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
5896 return;
5897 }
5898}
5899
5900/// Generates a 'note' diagnostic for an overload candidate. We've
5901/// already generated a primary error at the call site.
5902///
5903/// It really does need to be a single diagnostic with its caret
5904/// pointed at the candidate declaration. Yes, this creates some
5905/// major challenges of technical writing. Yes, this makes pointing
5906/// out problems with specific arguments quite awkward. It's still
5907/// better than generating twenty screens of text for every failed
5908/// overload.
5909///
5910/// It would be great to be able to express per-candidate problems
5911/// more richly for those diagnostic clients that cared, but we'd
5912/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00005913void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
5914 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00005915 FunctionDecl *Fn = Cand->Function;
5916
John McCall81201622010-01-08 04:41:39 +00005917 // Note deleted candidates, but only if they're viable.
John McCall3c80f572010-01-12 02:15:36 +00005918 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCall220ccbf2010-01-13 00:25:19 +00005919 std::string FnDesc;
5920 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00005921
5922 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00005923 << FnKind << FnDesc << Fn->isDeleted();
John McCalla1d7d622010-01-08 00:58:21 +00005924 return;
John McCall81201622010-01-08 04:41:39 +00005925 }
5926
John McCall220ccbf2010-01-13 00:25:19 +00005927 // We don't really have anything else to say about viable candidates.
5928 if (Cand->Viable) {
5929 S.NoteOverloadCandidate(Fn);
5930 return;
5931 }
John McCall1d318332010-01-12 00:44:57 +00005932
John McCalladbb8f82010-01-13 09:16:55 +00005933 switch (Cand->FailureKind) {
5934 case ovl_fail_too_many_arguments:
5935 case ovl_fail_too_few_arguments:
5936 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00005937
John McCalladbb8f82010-01-13 09:16:55 +00005938 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00005939 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5940
John McCall717e8912010-01-23 05:17:32 +00005941 case ovl_fail_trivial_conversion:
5942 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00005943 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00005944 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00005945
John McCallb1bdc622010-02-25 01:37:24 +00005946 case ovl_fail_bad_conversion: {
5947 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5948 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00005949 if (Cand->Conversions[I].isBad())
5950 return DiagnoseBadConversion(S, Cand, I);
5951
5952 // FIXME: this currently happens when we're called from SemaInit
5953 // when user-conversion overload fails. Figure out how to handle
5954 // those conditions and diagnose them well.
5955 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00005956 }
John McCallb1bdc622010-02-25 01:37:24 +00005957 }
John McCalla1d7d622010-01-08 00:58:21 +00005958}
5959
5960void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5961 // Desugar the type of the surrogate down to a function type,
5962 // retaining as many typedefs as possible while still showing
5963 // the function type (and, therefore, its parameter types).
5964 QualType FnType = Cand->Surrogate->getConversionType();
5965 bool isLValueReference = false;
5966 bool isRValueReference = false;
5967 bool isPointer = false;
5968 if (const LValueReferenceType *FnTypeRef =
5969 FnType->getAs<LValueReferenceType>()) {
5970 FnType = FnTypeRef->getPointeeType();
5971 isLValueReference = true;
5972 } else if (const RValueReferenceType *FnTypeRef =
5973 FnType->getAs<RValueReferenceType>()) {
5974 FnType = FnTypeRef->getPointeeType();
5975 isRValueReference = true;
5976 }
5977 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5978 FnType = FnTypePtr->getPointeeType();
5979 isPointer = true;
5980 }
5981 // Desugar down to a function type.
5982 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5983 // Reconstruct the pointer/reference as appropriate.
5984 if (isPointer) FnType = S.Context.getPointerType(FnType);
5985 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5986 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5987
5988 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5989 << FnType;
5990}
5991
5992void NoteBuiltinOperatorCandidate(Sema &S,
5993 const char *Opc,
5994 SourceLocation OpLoc,
5995 OverloadCandidate *Cand) {
5996 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5997 std::string TypeStr("operator");
5998 TypeStr += Opc;
5999 TypeStr += "(";
6000 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6001 if (Cand->Conversions.size() == 1) {
6002 TypeStr += ")";
6003 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6004 } else {
6005 TypeStr += ", ";
6006 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6007 TypeStr += ")";
6008 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
6009 }
6010}
6011
6012void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
6013 OverloadCandidate *Cand) {
6014 unsigned NoOperands = Cand->Conversions.size();
6015 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
6016 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00006017 if (ICS.isBad()) break; // all meaningless after first invalid
6018 if (!ICS.isAmbiguous()) continue;
6019
John McCall120d63c2010-08-24 20:38:10 +00006020 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006021 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00006022 }
6023}
6024
John McCall1b77e732010-01-15 23:32:50 +00006025SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
6026 if (Cand->Function)
6027 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00006028 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00006029 return Cand->Surrogate->getLocation();
6030 return SourceLocation();
6031}
6032
John McCallbf65c0b2010-01-12 00:48:53 +00006033struct CompareOverloadCandidatesForDisplay {
6034 Sema &S;
6035 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00006036
6037 bool operator()(const OverloadCandidate *L,
6038 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00006039 // Fast-path this check.
6040 if (L == R) return false;
6041
John McCall81201622010-01-08 04:41:39 +00006042 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00006043 if (L->Viable) {
6044 if (!R->Viable) return true;
6045
6046 // TODO: introduce a tri-valued comparison for overload
6047 // candidates. Would be more worthwhile if we had a sort
6048 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00006049 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6050 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00006051 } else if (R->Viable)
6052 return false;
John McCall81201622010-01-08 04:41:39 +00006053
John McCall1b77e732010-01-15 23:32:50 +00006054 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00006055
John McCall1b77e732010-01-15 23:32:50 +00006056 // Criteria by which we can sort non-viable candidates:
6057 if (!L->Viable) {
6058 // 1. Arity mismatches come after other candidates.
6059 if (L->FailureKind == ovl_fail_too_many_arguments ||
6060 L->FailureKind == ovl_fail_too_few_arguments)
6061 return false;
6062 if (R->FailureKind == ovl_fail_too_many_arguments ||
6063 R->FailureKind == ovl_fail_too_few_arguments)
6064 return true;
John McCall81201622010-01-08 04:41:39 +00006065
John McCall717e8912010-01-23 05:17:32 +00006066 // 2. Bad conversions come first and are ordered by the number
6067 // of bad conversions and quality of good conversions.
6068 if (L->FailureKind == ovl_fail_bad_conversion) {
6069 if (R->FailureKind != ovl_fail_bad_conversion)
6070 return true;
6071
6072 // If there's any ordering between the defined conversions...
6073 // FIXME: this might not be transitive.
6074 assert(L->Conversions.size() == R->Conversions.size());
6075
6076 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00006077 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6078 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00006079 switch (CompareImplicitConversionSequences(S,
6080 L->Conversions[I],
6081 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00006082 case ImplicitConversionSequence::Better:
6083 leftBetter++;
6084 break;
6085
6086 case ImplicitConversionSequence::Worse:
6087 leftBetter--;
6088 break;
6089
6090 case ImplicitConversionSequence::Indistinguishable:
6091 break;
6092 }
6093 }
6094 if (leftBetter > 0) return true;
6095 if (leftBetter < 0) return false;
6096
6097 } else if (R->FailureKind == ovl_fail_bad_conversion)
6098 return false;
6099
John McCall1b77e732010-01-15 23:32:50 +00006100 // TODO: others?
6101 }
6102
6103 // Sort everything else by location.
6104 SourceLocation LLoc = GetLocationForCandidate(L);
6105 SourceLocation RLoc = GetLocationForCandidate(R);
6106
6107 // Put candidates without locations (e.g. builtins) at the end.
6108 if (LLoc.isInvalid()) return false;
6109 if (RLoc.isInvalid()) return true;
6110
6111 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00006112 }
6113};
6114
John McCall717e8912010-01-23 05:17:32 +00006115/// CompleteNonViableCandidate - Normally, overload resolution only
6116/// computes up to the first
6117void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6118 Expr **Args, unsigned NumArgs) {
6119 assert(!Cand->Viable);
6120
6121 // Don't do anything on failures other than bad conversion.
6122 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6123
6124 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00006125 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCall717e8912010-01-23 05:17:32 +00006126 unsigned ConvCount = Cand->Conversions.size();
6127 while (true) {
6128 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6129 ConvIdx++;
6130 if (Cand->Conversions[ConvIdx - 1].isBad())
6131 break;
6132 }
6133
6134 if (ConvIdx == ConvCount)
6135 return;
6136
John McCallb1bdc622010-02-25 01:37:24 +00006137 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6138 "remaining conversion is initialized?");
6139
Douglas Gregor23ef6c02010-04-16 17:45:54 +00006140 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00006141 // operation somehow.
6142 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00006143
6144 const FunctionProtoType* Proto;
6145 unsigned ArgIdx = ConvIdx;
6146
6147 if (Cand->IsSurrogate) {
6148 QualType ConvType
6149 = Cand->Surrogate->getConversionType().getNonReferenceType();
6150 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6151 ConvType = ConvPtrType->getPointeeType();
6152 Proto = ConvType->getAs<FunctionProtoType>();
6153 ArgIdx--;
6154 } else if (Cand->Function) {
6155 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6156 if (isa<CXXMethodDecl>(Cand->Function) &&
6157 !isa<CXXConstructorDecl>(Cand->Function))
6158 ArgIdx--;
6159 } else {
6160 // Builtin binary operator with a bad first conversion.
6161 assert(ConvCount <= 3);
6162 for (; ConvIdx != ConvCount; ++ConvIdx)
6163 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006164 = TryCopyInitialization(S, Args[ConvIdx],
6165 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6166 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00006167 /*InOverloadResolution*/ true);
John McCall717e8912010-01-23 05:17:32 +00006168 return;
6169 }
6170
6171 // Fill in the rest of the conversions.
6172 unsigned NumArgsInProto = Proto->getNumArgs();
6173 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6174 if (ArgIdx < NumArgsInProto)
6175 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006176 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6177 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00006178 /*InOverloadResolution=*/true);
John McCall717e8912010-01-23 05:17:32 +00006179 else
6180 Cand->Conversions[ConvIdx].setEllipsis();
6181 }
6182}
6183
John McCalla1d7d622010-01-08 00:58:21 +00006184} // end anonymous namespace
6185
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006186/// PrintOverloadCandidates - When overload resolution fails, prints
6187/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00006188/// set.
John McCall120d63c2010-08-24 20:38:10 +00006189void OverloadCandidateSet::NoteCandidates(Sema &S,
6190 OverloadCandidateDisplayKind OCD,
6191 Expr **Args, unsigned NumArgs,
6192 const char *Opc,
6193 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00006194 // Sort the candidates by viability and position. Sorting directly would
6195 // be prohibitive, so we make a set of pointers and sort those.
6196 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00006197 if (OCD == OCD_AllCandidates) Cands.reserve(size());
6198 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00006199 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00006200 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00006201 else if (OCD == OCD_AllCandidates) {
John McCall120d63c2010-08-24 20:38:10 +00006202 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006203 if (Cand->Function || Cand->IsSurrogate)
6204 Cands.push_back(Cand);
6205 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6206 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00006207 }
6208 }
6209
John McCallbf65c0b2010-01-12 00:48:53 +00006210 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00006211 CompareOverloadCandidatesForDisplay(S));
John McCall81201622010-01-08 04:41:39 +00006212
John McCall1d318332010-01-12 00:44:57 +00006213 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00006214
John McCall81201622010-01-08 04:41:39 +00006215 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall120d63c2010-08-24 20:38:10 +00006216 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006217 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00006218 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6219 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00006220
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006221 // Set an arbitrary limit on the number of candidate functions we'll spam
6222 // the user with. FIXME: This limit should depend on details of the
6223 // candidate list.
6224 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6225 break;
6226 }
6227 ++CandsShown;
6228
John McCalla1d7d622010-01-08 00:58:21 +00006229 if (Cand->Function)
John McCall120d63c2010-08-24 20:38:10 +00006230 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00006231 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00006232 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006233 else {
6234 assert(Cand->Viable &&
6235 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00006236 // Generally we only see ambiguities including viable builtin
6237 // operators if overload resolution got screwed up by an
6238 // ambiguous user-defined conversion.
6239 //
6240 // FIXME: It's quite possible for different conversions to see
6241 // different ambiguities, though.
6242 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00006243 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00006244 ReportedAmbiguousConversions = true;
6245 }
John McCalla1d7d622010-01-08 00:58:21 +00006246
John McCall1d318332010-01-12 00:44:57 +00006247 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00006248 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006249 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006250 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006251
6252 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00006253 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006254}
6255
John McCall9aa472c2010-03-19 07:35:19 +00006256static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCallc373d482010-01-27 01:50:18 +00006257 if (isa<UnresolvedLookupExpr>(E))
John McCall9aa472c2010-03-19 07:35:19 +00006258 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00006259
John McCall9aa472c2010-03-19 07:35:19 +00006260 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00006261}
6262
Douglas Gregor904eed32008-11-10 20:40:00 +00006263/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6264/// an overloaded function (C++ [over.over]), where @p From is an
6265/// expression with overloaded function type and @p ToType is the type
6266/// we're trying to resolve to. For example:
6267///
6268/// @code
6269/// int f(double);
6270/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00006271///
Douglas Gregor904eed32008-11-10 20:40:00 +00006272/// int (*pfd)(double) = f; // selects f(double)
6273/// @endcode
6274///
6275/// This routine returns the resulting FunctionDecl if it could be
6276/// resolved, and NULL otherwise. When @p Complain is true, this
6277/// routine will emit diagnostics if there is an error.
6278FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00006279Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall6bb80172010-03-30 21:47:33 +00006280 bool Complain,
6281 DeclAccessPair &FoundResult) {
Douglas Gregor904eed32008-11-10 20:40:00 +00006282 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00006283 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00006284 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00006285 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00006286 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00006287 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00006288 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00006289 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00006290 FunctionType = MemTypePtr->getPointeeType();
6291 IsMember = true;
6292 }
Douglas Gregor904eed32008-11-10 20:40:00 +00006293
Douglas Gregor904eed32008-11-10 20:40:00 +00006294 // C++ [over.over]p1:
6295 // [...] [Note: any redundant set of parentheses surrounding the
6296 // overloaded function name is ignored (5.1). ]
Douglas Gregor904eed32008-11-10 20:40:00 +00006297 // C++ [over.over]p1:
6298 // [...] The overloaded function name can be preceded by the &
6299 // operator.
John McCallc988fab2010-08-24 23:26:21 +00006300 // However, remember whether the expression has member-pointer form:
6301 // C++ [expr.unary.op]p4:
6302 // A pointer to member is only formed when an explicit & is used
6303 // and its operand is a qualified-id not enclosed in
6304 // parentheses.
John McCall9c72c602010-08-27 09:08:28 +00006305 OverloadExpr::FindResult Ovl = OverloadExpr::find(From);
6306 OverloadExpr *OvlExpr = Ovl.Expression;
John McCallc988fab2010-08-24 23:26:21 +00006307
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006308 // We expect a pointer or reference to function, or a function pointer.
6309 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6310 if (!FunctionType->isFunctionType()) {
6311 if (Complain)
6312 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6313 << OvlExpr->getName() << ToType;
6314
6315 return 0;
6316 }
6317
John McCallfb97e752010-08-24 22:52:39 +00006318 // If the overload expression doesn't have the form of a pointer to
John McCallc988fab2010-08-24 23:26:21 +00006319 // member, don't try to convert it to a pointer-to-member type.
John McCall9c72c602010-08-27 09:08:28 +00006320 if (IsMember && !Ovl.HasFormOfMemberPointer) {
John McCallfb97e752010-08-24 22:52:39 +00006321 if (!Complain) return 0;
6322
6323 // TODO: Should we condition this on whether any functions might
6324 // have matched, or is it more appropriate to do that in callers?
6325 // TODO: a fixit wouldn't hurt.
6326 Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
6327 << ToType << OvlExpr->getSourceRange();
6328 return 0;
6329 }
6330
6331 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6332 if (OvlExpr->hasExplicitTemplateArgs()) {
6333 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6334 ExplicitTemplateArgs = &ETABuffer;
6335 }
6336
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006337 assert(From->getType() == Context.OverloadTy);
Douglas Gregor904eed32008-11-10 20:40:00 +00006338
Douglas Gregor904eed32008-11-10 20:40:00 +00006339 // Look through all of the overloaded functions, searching for one
6340 // whose type matches exactly.
John McCall9aa472c2010-03-19 07:35:19 +00006341 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb7a09262010-04-01 18:32:35 +00006342 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
Douglas Gregor9b623632010-10-12 23:32:35 +00006343
Douglas Gregor00aeb522009-07-08 23:33:52 +00006344 bool FoundNonTemplateFunction = false;
John McCall7bb12da2010-02-02 06:20:04 +00006345 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6346 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00006347 // Look through any using declarations to find the underlying function.
6348 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6349
Douglas Gregor904eed32008-11-10 20:40:00 +00006350 // C++ [over.over]p3:
6351 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00006352 // targets of type "pointer-to-function" or "reference-to-function."
6353 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00006354 // type "pointer-to-member-function."
6355 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00006356
Mike Stump1eb44332009-09-09 15:08:12 +00006357 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthbd647292009-12-29 06:17:27 +00006358 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006359 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00006360 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00006361 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00006362 // static when converting to member pointer.
6363 if (Method->isStatic() == IsMember)
6364 continue;
6365 } else if (IsMember)
6366 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00006367
Douglas Gregor00aeb522009-07-08 23:33:52 +00006368 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00006369 // If the name is a function template, template argument deduction is
6370 // done (14.8.2.2), and if the argument deduction succeeds, the
6371 // resulting template argument list is used to generate a single
6372 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00006373 // overloaded functions considered.
Douglas Gregor83314aa2009-07-08 20:55:45 +00006374 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00006375 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor83314aa2009-07-08 20:55:45 +00006376 if (TemplateDeductionResult Result
John McCall7bb12da2010-02-02 06:20:04 +00006377 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00006378 FunctionType, Specialization, Info)) {
6379 // FIXME: make a note of the failed deduction for diagnostics.
6380 (void)Result;
6381 } else {
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00006382 // Template argument deduction ensures that we have an exact match.
6383 // This function template specicalization works.
Douglas Gregor9b623632010-10-12 23:32:35 +00006384 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006385 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00006386 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor9b623632010-10-12 23:32:35 +00006387 Matches.push_back(std::make_pair(I.getPair(), Specialization));
Douglas Gregor83314aa2009-07-08 20:55:45 +00006388 }
John McCallba135432009-11-21 08:51:07 +00006389
6390 continue;
Douglas Gregor83314aa2009-07-08 20:55:45 +00006391 }
Mike Stump1eb44332009-09-09 15:08:12 +00006392
Chandler Carruthbd647292009-12-29 06:17:27 +00006393 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00006394 // Skip non-static functions when converting to pointer, and static
6395 // when converting to member pointer.
6396 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00006397 continue;
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006398
6399 // If we have explicit template arguments, skip non-templates.
John McCall7bb12da2010-02-02 06:20:04 +00006400 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006401 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00006402 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00006403 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00006404
Chandler Carruthbd647292009-12-29 06:17:27 +00006405 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00006406 QualType ResultTy;
6407 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6408 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6409 ResultTy)) {
John McCall9aa472c2010-03-19 07:35:19 +00006410 Matches.push_back(std::make_pair(I.getPair(),
6411 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00006412 FoundNonTemplateFunction = true;
6413 }
Mike Stump1eb44332009-09-09 15:08:12 +00006414 }
Douglas Gregor904eed32008-11-10 20:40:00 +00006415 }
6416
Douglas Gregor00aeb522009-07-08 23:33:52 +00006417 // If there were 0 or 1 matches, we're done.
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006418 if (Matches.empty()) {
6419 if (Complain) {
6420 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6421 << OvlExpr->getName() << FunctionType;
6422 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6423 E = OvlExpr->decls_end();
6424 I != E; ++I)
6425 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6426 NoteOverloadCandidate(F);
6427 }
6428
Douglas Gregor00aeb522009-07-08 23:33:52 +00006429 return 0;
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006430 } else if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00006431 FunctionDecl *Result = Matches[0].second;
Douglas Gregor9b623632010-10-12 23:32:35 +00006432 FoundResult = Matches[0].first;
Sebastian Redl07ab2022009-10-17 21:12:09 +00006433 MarkDeclarationReferenced(From->getLocStart(), Result);
Douglas Gregor9b623632010-10-12 23:32:35 +00006434 if (Complain) {
John McCall6bb80172010-03-30 21:47:33 +00006435 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Douglas Gregor9b623632010-10-12 23:32:35 +00006436 }
Sebastian Redl07ab2022009-10-17 21:12:09 +00006437 return Result;
6438 }
Douglas Gregor00aeb522009-07-08 23:33:52 +00006439
6440 // C++ [over.over]p4:
6441 // If more than one function is selected, [...]
Douglas Gregor312a2022009-09-26 03:56:17 +00006442 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006443 // [...] and any given function template specialization F1 is
6444 // eliminated if the set contains a second function template
6445 // specialization whose function template is more specialized
6446 // than the function template of F1 according to the partial
6447 // ordering rules of 14.5.5.2.
6448
6449 // The algorithm specified above is quadratic. We instead use a
6450 // two-pass algorithm (similar to the one used to identify the
6451 // best viable function in an overload set) that identifies the
6452 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00006453
6454 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6455 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6456 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCallc373d482010-01-27 01:50:18 +00006457
6458 UnresolvedSetIterator Result =
John McCall9aa472c2010-03-19 07:35:19 +00006459 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redl07ab2022009-10-17 21:12:09 +00006460 TPOC_Other, From->getLocStart(),
6461 PDiag(),
6462 PDiag(diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00006463 << Matches[0].second->getDeclName(),
John McCall220ccbf2010-01-13 00:25:19 +00006464 PDiag(diag::note_ovl_candidate)
6465 << (unsigned) oc_function_template);
Douglas Gregor78c057e2010-09-12 08:16:09 +00006466 if (Result == MatchesCopy.end())
6467 return 0;
6468
John McCallc373d482010-01-27 01:50:18 +00006469 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall6bb80172010-03-30 21:47:33 +00006470 FoundResult = Matches[Result - MatchesCopy.begin()].first;
Douglas Gregor9b623632010-10-12 23:32:35 +00006471 if (Complain)
John McCall6bb80172010-03-30 21:47:33 +00006472 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCallc373d482010-01-27 01:50:18 +00006473 return cast<FunctionDecl>(*Result);
Douglas Gregor00aeb522009-07-08 23:33:52 +00006474 }
Mike Stump1eb44332009-09-09 15:08:12 +00006475
Douglas Gregor312a2022009-09-26 03:56:17 +00006476 // [...] any function template specializations in the set are
6477 // eliminated if the set also contains a non-template function, [...]
John McCallc373d482010-01-27 01:50:18 +00006478 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCall9aa472c2010-03-19 07:35:19 +00006479 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCallc373d482010-01-27 01:50:18 +00006480 ++I;
6481 else {
John McCall9aa472c2010-03-19 07:35:19 +00006482 Matches[I] = Matches[--N];
6483 Matches.set_size(N);
John McCallc373d482010-01-27 01:50:18 +00006484 }
6485 }
Douglas Gregor312a2022009-09-26 03:56:17 +00006486
Mike Stump1eb44332009-09-09 15:08:12 +00006487 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00006488 // selected function.
John McCallc373d482010-01-27 01:50:18 +00006489 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00006490 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall6bb80172010-03-30 21:47:33 +00006491 FoundResult = Matches[0].first;
Douglas Gregor9b623632010-10-12 23:32:35 +00006492 if (Complain)
John McCall9aa472c2010-03-19 07:35:19 +00006493 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
6494 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redl07ab2022009-10-17 21:12:09 +00006495 }
Mike Stump1eb44332009-09-09 15:08:12 +00006496
Douglas Gregor00aeb522009-07-08 23:33:52 +00006497 // FIXME: We should probably return the same thing that BestViableFunction
6498 // returns (even if we issue the diagnostics here).
6499 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00006500 << Matches[0].second->getDeclName();
6501 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6502 NoteOverloadCandidate(Matches[I].second);
Douglas Gregor904eed32008-11-10 20:40:00 +00006503 return 0;
6504}
6505
Douglas Gregor4b52e252009-12-21 23:17:24 +00006506/// \brief Given an expression that refers to an overloaded function, try to
6507/// resolve that overloaded function expression down to a single function.
6508///
6509/// This routine can only resolve template-ids that refer to a single function
6510/// template, where that template-id refers to a single template whose template
6511/// arguments are either provided by the template-id or have defaults,
6512/// as described in C++0x [temp.arg.explicit]p3.
6513FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6514 // C++ [over.over]p1:
6515 // [...] [Note: any redundant set of parentheses surrounding the
6516 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00006517 // C++ [over.over]p1:
6518 // [...] The overloaded function name can be preceded by the &
6519 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00006520
6521 if (From->getType() != Context.OverloadTy)
6522 return 0;
6523
John McCall9c72c602010-08-27 09:08:28 +00006524 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
Douglas Gregor4b52e252009-12-21 23:17:24 +00006525
6526 // If we didn't actually find any template-ids, we're done.
John McCall7bb12da2010-02-02 06:20:04 +00006527 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00006528 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00006529
6530 TemplateArgumentListInfo ExplicitTemplateArgs;
6531 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor4b52e252009-12-21 23:17:24 +00006532
6533 // Look through all of the overloaded functions, searching for one
6534 // whose type matches exactly.
6535 FunctionDecl *Matched = 0;
John McCall7bb12da2010-02-02 06:20:04 +00006536 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6537 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00006538 // C++0x [temp.arg.explicit]p3:
6539 // [...] In contexts where deduction is done and fails, or in contexts
6540 // where deduction is not done, if a template argument list is
6541 // specified and it, along with any default template arguments,
6542 // identifies a single function template specialization, then the
6543 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00006544 FunctionTemplateDecl *FunctionTemplate
6545 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor4b52e252009-12-21 23:17:24 +00006546
6547 // C++ [over.over]p2:
6548 // If the name is a function template, template argument deduction is
6549 // done (14.8.2.2), and if the argument deduction succeeds, the
6550 // resulting template argument list is used to generate a single
6551 // function template specialization, which is added to the set of
6552 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00006553 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00006554 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00006555 if (TemplateDeductionResult Result
6556 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6557 Specialization, Info)) {
6558 // FIXME: make a note of the failed deduction for diagnostics.
6559 (void)Result;
6560 continue;
6561 }
6562
6563 // Multiple matches; we can't resolve to a single declaration.
6564 if (Matched)
6565 return 0;
6566
6567 Matched = Specialization;
6568 }
Douglas Gregor9b623632010-10-12 23:32:35 +00006569
Douglas Gregor4b52e252009-12-21 23:17:24 +00006570 return Matched;
6571}
6572
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006573/// \brief Add a single candidate to the overload set.
6574static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00006575 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00006576 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006577 Expr **Args, unsigned NumArgs,
6578 OverloadCandidateSet &CandidateSet,
6579 bool PartialOverloading) {
John McCall9aa472c2010-03-19 07:35:19 +00006580 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00006581 if (isa<UsingShadowDecl>(Callee))
6582 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6583
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006584 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00006585 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCall9aa472c2010-03-19 07:35:19 +00006586 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00006587 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006588 return;
John McCallba135432009-11-21 08:51:07 +00006589 }
6590
6591 if (FunctionTemplateDecl *FuncTemplate
6592 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00006593 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6594 ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00006595 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00006596 return;
6597 }
6598
6599 assert(false && "unhandled case in overloaded call candidate");
6600
6601 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006602}
6603
6604/// \brief Add the overload candidates named by callee and/or found by argument
6605/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00006606void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006607 Expr **Args, unsigned NumArgs,
6608 OverloadCandidateSet &CandidateSet,
6609 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00006610
6611#ifndef NDEBUG
6612 // Verify that ArgumentDependentLookup is consistent with the rules
6613 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006614 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006615 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6616 // and let Y be the lookup set produced by argument dependent
6617 // lookup (defined as follows). If X contains
6618 //
6619 // -- a declaration of a class member, or
6620 //
6621 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00006622 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006623 //
6624 // -- a declaration that is neither a function or a function
6625 // template
6626 //
6627 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00006628
John McCall3b4294e2009-12-16 12:17:52 +00006629 if (ULE->requiresADL()) {
6630 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6631 E = ULE->decls_end(); I != E; ++I) {
6632 assert(!(*I)->getDeclContext()->isRecord());
6633 assert(isa<UsingShadowDecl>(*I) ||
6634 !(*I)->getDeclContext()->isFunctionOrMethod());
6635 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00006636 }
6637 }
6638#endif
6639
John McCall3b4294e2009-12-16 12:17:52 +00006640 // It would be nice to avoid this copy.
6641 TemplateArgumentListInfo TABuffer;
6642 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6643 if (ULE->hasExplicitTemplateArgs()) {
6644 ULE->copyTemplateArgumentsInto(TABuffer);
6645 ExplicitTemplateArgs = &TABuffer;
6646 }
6647
6648 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6649 E = ULE->decls_end(); I != E; ++I)
John McCall9aa472c2010-03-19 07:35:19 +00006650 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00006651 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006652 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00006653
John McCall3b4294e2009-12-16 12:17:52 +00006654 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00006655 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6656 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006657 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006658 CandidateSet,
6659 PartialOverloading);
6660}
John McCall578b69b2009-12-16 08:11:27 +00006661
6662/// Attempts to recover from a call where no functions were found.
6663///
6664/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00006665static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006666BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00006667 UnresolvedLookupExpr *ULE,
6668 SourceLocation LParenLoc,
6669 Expr **Args, unsigned NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00006670 SourceLocation RParenLoc) {
John McCall578b69b2009-12-16 08:11:27 +00006671
6672 CXXScopeSpec SS;
6673 if (ULE->getQualifier()) {
6674 SS.setScopeRep(ULE->getQualifier());
6675 SS.setRange(ULE->getQualifierRange());
6676 }
6677
John McCall3b4294e2009-12-16 12:17:52 +00006678 TemplateArgumentListInfo TABuffer;
6679 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6680 if (ULE->hasExplicitTemplateArgs()) {
6681 ULE->copyTemplateArgumentsInto(TABuffer);
6682 ExplicitTemplateArgs = &TABuffer;
6683 }
6684
John McCall578b69b2009-12-16 08:11:27 +00006685 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6686 Sema::LookupOrdinaryName);
Douglas Gregor91f7ac72010-05-18 16:14:23 +00006687 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCallf312b1e2010-08-26 23:41:50 +00006688 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00006689
John McCall3b4294e2009-12-16 12:17:52 +00006690 assert(!R.empty() && "lookup results empty despite recovery");
6691
6692 // Build an implicit member call if appropriate. Just drop the
6693 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00006694 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00006695 if ((*R.begin())->isCXXClassMember())
6696 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6697 else if (ExplicitTemplateArgs)
6698 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6699 else
6700 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6701
6702 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00006703 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00006704
6705 // This shouldn't cause an infinite loop because we're giving it
6706 // an expression with non-empty lookup results, which should never
6707 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00006708 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +00006709 MultiExprArg(Args, NumArgs), RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00006710}
Douglas Gregord7a95972010-06-08 17:35:15 +00006711
Douglas Gregorf6b89692008-11-26 05:54:23 +00006712/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00006713/// (which eventually refers to the declaration Func) and the call
6714/// arguments Args/NumArgs, attempt to resolve the function call down
6715/// to a specific function. If overload resolution succeeds, returns
6716/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00006717/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00006718/// arguments and Fn, and returns NULL.
John McCall60d7b3a2010-08-24 06:29:42 +00006719ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006720Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00006721 SourceLocation LParenLoc,
6722 Expr **Args, unsigned NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00006723 SourceLocation RParenLoc) {
6724#ifndef NDEBUG
6725 if (ULE->requiresADL()) {
6726 // To do ADL, we must have found an unqualified name.
6727 assert(!ULE->getQualifier() && "qualified name with ADL");
6728
6729 // We don't perform ADL for implicit declarations of builtins.
6730 // Verify that this was correctly set up.
6731 FunctionDecl *F;
6732 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6733 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6734 F->getBuiltinID() && F->isImplicit())
6735 assert(0 && "performing ADL for builtin");
6736
6737 // We don't perform ADL in C.
6738 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6739 }
6740#endif
6741
John McCall5769d612010-02-08 23:07:23 +00006742 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00006743
John McCall3b4294e2009-12-16 12:17:52 +00006744 // Add the functions denoted by the callee to the set of candidate
6745 // functions, including those from argument-dependent lookup.
6746 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00006747
6748 // If we found nothing, try to recover.
6749 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6750 // bailout out if it fails.
John McCall3b4294e2009-12-16 12:17:52 +00006751 if (CandidateSet.empty())
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006752 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00006753 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00006754
Douglas Gregorf6b89692008-11-26 05:54:23 +00006755 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00006756 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00006757 case OR_Success: {
6758 FunctionDecl *FDecl = Best->Function;
John McCall9aa472c2010-03-19 07:35:19 +00006759 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00006760 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(), ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00006761 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall3b4294e2009-12-16 12:17:52 +00006762 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6763 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00006764
6765 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00006766 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00006767 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00006768 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00006769 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00006770 break;
6771
6772 case OR_Ambiguous:
6773 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00006774 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00006775 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00006776 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006777
6778 case OR_Deleted:
6779 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6780 << Best->Function->isDeleted()
John McCall3b4294e2009-12-16 12:17:52 +00006781 << ULE->getName()
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006782 << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00006783 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006784 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00006785 }
6786
Douglas Gregorff331c12010-07-25 18:17:45 +00006787 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00006788 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00006789}
6790
John McCall6e266892010-01-26 03:27:55 +00006791static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00006792 return Functions.size() > 1 ||
6793 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6794}
6795
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006796/// \brief Create a unary operation that may resolve to an overloaded
6797/// operator.
6798///
6799/// \param OpLoc The location of the operator itself (e.g., '*').
6800///
6801/// \param OpcIn The UnaryOperator::Opcode that describes this
6802/// operator.
6803///
6804/// \param Functions The set of non-member functions that will be
6805/// considered by overload resolution. The caller needs to build this
6806/// set based on the context using, e.g.,
6807/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6808/// set should not contain any member functions; those will be added
6809/// by CreateOverloadedUnaryOp().
6810///
6811/// \param input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +00006812ExprResult
John McCall6e266892010-01-26 03:27:55 +00006813Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6814 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +00006815 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006816 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006817
6818 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6819 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6820 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00006821 // TODO: provide better source location info.
6822 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006823
6824 Expr *Args[2] = { Input, 0 };
6825 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00006826
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006827 // For post-increment and post-decrement, add the implicit '0' as
6828 // the second argument, so that we know this is a post-increment or
6829 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +00006830 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006831 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00006832 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
6833 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006834 NumArgs = 2;
6835 }
6836
6837 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00006838 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +00006839 return Owned(new (Context) UnaryOperator(Input,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00006840 Opc,
6841 Context.DependentTy,
6842 OpLoc));
6843
John McCallc373d482010-01-27 01:50:18 +00006844 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00006845 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00006846 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00006847 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00006848 /*ADL*/ true, IsOverloaded(Fns),
6849 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006850 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6851 &Args[0], NumArgs,
6852 Context.DependentTy,
6853 OpLoc));
6854 }
6855
6856 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00006857 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006858
6859 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00006860 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006861
6862 // Add operator candidates that are member functions.
6863 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6864
John McCall6e266892010-01-26 03:27:55 +00006865 // Add candidates from ADL.
6866 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregordc81c882010-02-05 05:15:43 +00006867 Args, NumArgs,
John McCall6e266892010-01-26 03:27:55 +00006868 /*ExplicitTemplateArgs*/ 0,
6869 CandidateSet);
6870
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006871 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00006872 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006873
6874 // Perform overload resolution.
6875 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00006876 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006877 case OR_Success: {
6878 // We found a built-in operator or an overloaded operator.
6879 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00006880
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006881 if (FnDecl) {
6882 // We matched an overloaded operator. Build a call to that
6883 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00006884
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006885 // Convert the arguments.
6886 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00006887 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00006888
John McCall6bb80172010-03-30 21:47:33 +00006889 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6890 Best->FoundDecl, Method))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006891 return ExprError();
6892 } else {
6893 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00006894 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +00006895 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00006896 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +00006897 FnDecl->getParamDecl(0)),
Douglas Gregore1a5c172009-12-23 17:40:29 +00006898 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +00006899 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +00006900 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006901 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00006902 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006903 }
6904
John McCallb697e082010-05-06 18:15:07 +00006905 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6906
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006907 // Determine the result type
Douglas Gregor5291c3c2010-07-13 08:18:22 +00006908 QualType ResultTy = FnDecl->getCallResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006909
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006910 // Build the actual expression node.
6911 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6912 SourceLocation());
6913 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00006914
Eli Friedman4c3b8962009-11-18 03:58:17 +00006915 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +00006916 CallExpr *TheCall =
Anders Carlsson26a2a072009-10-13 21:19:37 +00006917 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall9ae2f072010-08-23 23:25:46 +00006918 Args, NumArgs, ResultTy, OpLoc);
John McCallb697e082010-05-06 18:15:07 +00006919
John McCall9ae2f072010-08-23 23:25:46 +00006920 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +00006921 FnDecl))
6922 return ExprError();
6923
John McCall9ae2f072010-08-23 23:25:46 +00006924 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006925 } else {
6926 // We matched a built-in operator. Convert the arguments, then
6927 // break out so that we will build the appropriate built-in
6928 // operator node.
6929 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00006930 Best->Conversions[0], AA_Passing))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006931 return ExprError();
6932
6933 break;
6934 }
6935 }
6936
6937 case OR_No_Viable_Function:
6938 // No viable function; fall through to handling this as a
6939 // built-in operator, which will produce an error message for us.
6940 break;
6941
6942 case OR_Ambiguous:
6943 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6944 << UnaryOperator::getOpcodeStr(Opc)
6945 << Input->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00006946 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
6947 Args, NumArgs,
6948 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006949 return ExprError();
6950
6951 case OR_Deleted:
6952 Diag(OpLoc, diag::err_ovl_deleted_oper)
6953 << Best->Function->isDeleted()
6954 << UnaryOperator::getOpcodeStr(Opc)
6955 << Input->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00006956 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006957 return ExprError();
6958 }
6959
6960 // Either we found no viable overloaded operator or we matched a
6961 // built-in operator. In either case, fall through to trying to
6962 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +00006963 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006964}
6965
Douglas Gregor063daf62009-03-13 18:40:31 +00006966/// \brief Create a binary operation that may resolve to an overloaded
6967/// operator.
6968///
6969/// \param OpLoc The location of the operator itself (e.g., '+').
6970///
6971/// \param OpcIn The BinaryOperator::Opcode that describes this
6972/// operator.
6973///
6974/// \param Functions The set of non-member functions that will be
6975/// considered by overload resolution. The caller needs to build this
6976/// set based on the context using, e.g.,
6977/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6978/// set should not contain any member functions; those will be added
6979/// by CreateOverloadedBinOp().
6980///
6981/// \param LHS Left-hand argument.
6982/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +00006983ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00006984Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006985 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00006986 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00006987 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00006988 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006989 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00006990
6991 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6992 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6993 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6994
6995 // If either side is type-dependent, create an appropriate dependent
6996 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006997 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00006998 if (Fns.empty()) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006999 // If there are no functions to store, just build a dependent
7000 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +00007001 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007002 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
7003 Context.DependentTy, OpLoc));
7004
7005 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
7006 Context.DependentTy,
7007 Context.DependentTy,
7008 Context.DependentTy,
7009 OpLoc));
7010 }
John McCall6e266892010-01-26 03:27:55 +00007011
7012 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00007013 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00007014 // TODO: provide better source location info in DNLoc component.
7015 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +00007016 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00007017 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00007018 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00007019 /*ADL*/ true, IsOverloaded(Fns),
7020 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00007021 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00007022 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00007023 Context.DependentTy,
7024 OpLoc));
7025 }
7026
7027 // If this is the .* operator, which is not overloadable, just
7028 // create a built-in binary operator.
John McCall2de56d12010-08-25 11:45:40 +00007029 if (Opc == BO_PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007030 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00007031
Sebastian Redl275c2b42009-11-18 23:10:33 +00007032 // If this is the assignment operator, we only perform overload resolution
7033 // if the left-hand side is a class or enumeration type. This is actually
7034 // a hack. The standard requires that we do overload resolution between the
7035 // various built-in candidates, but as DR507 points out, this can lead to
7036 // problems. So we do it this way, which pretty much follows what GCC does.
7037 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +00007038 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007039 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00007040
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007041 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00007042 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00007043
7044 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00007045 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00007046
7047 // Add operator candidates that are member functions.
7048 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
7049
John McCall6e266892010-01-26 03:27:55 +00007050 // Add candidates from ADL.
7051 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
7052 Args, 2,
7053 /*ExplicitTemplateArgs*/ 0,
7054 CandidateSet);
7055
Douglas Gregor063daf62009-03-13 18:40:31 +00007056 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00007057 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00007058
7059 // Perform overload resolution.
7060 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007061 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007062 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00007063 // We found a built-in operator or an overloaded operator.
7064 FunctionDecl *FnDecl = Best->Function;
7065
7066 if (FnDecl) {
7067 // We matched an overloaded operator. Build a call to that
7068 // operator.
7069
7070 // Convert the arguments.
7071 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00007072 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +00007073 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00007074
John McCall60d7b3a2010-08-24 06:29:42 +00007075 ExprResult Arg1
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007076 = PerformCopyInitialization(
7077 InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007078 Context,
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007079 FnDecl->getParamDecl(0)),
7080 SourceLocation(),
7081 Owned(Args[1]));
7082 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00007083 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007084
Douglas Gregor5fccd362010-03-03 23:55:11 +00007085 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007086 Best->FoundDecl, Method))
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007087 return ExprError();
7088
7089 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00007090 } else {
7091 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00007092 ExprResult Arg0
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007093 = PerformCopyInitialization(
7094 InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007095 Context,
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007096 FnDecl->getParamDecl(0)),
7097 SourceLocation(),
7098 Owned(Args[0]));
7099 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00007100 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007101
John McCall60d7b3a2010-08-24 06:29:42 +00007102 ExprResult Arg1
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007103 = PerformCopyInitialization(
7104 InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007105 Context,
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007106 FnDecl->getParamDecl(1)),
7107 SourceLocation(),
7108 Owned(Args[1]));
7109 if (Arg1.isInvalid())
7110 return ExprError();
7111 Args[0] = LHS = Arg0.takeAs<Expr>();
7112 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00007113 }
7114
John McCallb697e082010-05-06 18:15:07 +00007115 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7116
Douglas Gregor063daf62009-03-13 18:40:31 +00007117 // Determine the result type
7118 QualType ResultTy
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007119 = FnDecl->getType()->getAs<FunctionType>()
7120 ->getCallResultType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +00007121
7122 // Build the actual expression node.
7123 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00007124 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00007125 UsualUnaryConversions(FnExpr);
7126
John McCall9ae2f072010-08-23 23:25:46 +00007127 CXXOperatorCallExpr *TheCall =
7128 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
7129 Args, 2, ResultTy, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +00007130
John McCall9ae2f072010-08-23 23:25:46 +00007131 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00007132 FnDecl))
7133 return ExprError();
7134
John McCall9ae2f072010-08-23 23:25:46 +00007135 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +00007136 } else {
7137 // We matched a built-in operator. Convert the arguments, then
7138 // break out so that we will build the appropriate built-in
7139 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007140 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00007141 Best->Conversions[0], AA_Passing) ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007142 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00007143 Best->Conversions[1], AA_Passing))
Douglas Gregor063daf62009-03-13 18:40:31 +00007144 return ExprError();
7145
7146 break;
7147 }
7148 }
7149
Douglas Gregor33074752009-09-30 21:46:01 +00007150 case OR_No_Viable_Function: {
7151 // C++ [over.match.oper]p9:
7152 // If the operator is the operator , [...] and there are no
7153 // viable functions, then the operator is assumed to be the
7154 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +00007155 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +00007156 break;
7157
Sebastian Redl8593c782009-05-21 11:50:50 +00007158 // For class as left operand for assignment or compound assigment operator
7159 // do not fall through to handling in built-in, but report that no overloaded
7160 // assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +00007161 ExprResult Result = ExprError();
Douglas Gregor33074752009-09-30 21:46:01 +00007162 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +00007163 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00007164 Diag(OpLoc, diag::err_ovl_no_viable_oper)
7165 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007166 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00007167 } else {
7168 // No viable function; try to create a built-in operation, which will
7169 // produce an error. Then, show the non-viable candidates.
7170 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00007171 }
Douglas Gregor33074752009-09-30 21:46:01 +00007172 assert(Result.isInvalid() &&
7173 "C++ binary operator overloading is missing candidates!");
7174 if (Result.isInvalid())
John McCall120d63c2010-08-24 20:38:10 +00007175 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7176 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00007177 return move(Result);
7178 }
Douglas Gregor063daf62009-03-13 18:40:31 +00007179
7180 case OR_Ambiguous:
7181 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
7182 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007183 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007184 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7185 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00007186 return ExprError();
7187
7188 case OR_Deleted:
7189 Diag(OpLoc, diag::err_ovl_deleted_oper)
7190 << Best->Function->isDeleted()
7191 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007192 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007193 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor063daf62009-03-13 18:40:31 +00007194 return ExprError();
John McCall1d318332010-01-12 00:44:57 +00007195 }
Douglas Gregor063daf62009-03-13 18:40:31 +00007196
Douglas Gregor33074752009-09-30 21:46:01 +00007197 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007198 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00007199}
7200
John McCall60d7b3a2010-08-24 06:29:42 +00007201ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +00007202Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7203 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +00007204 Expr *Base, Expr *Idx) {
7205 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +00007206 DeclarationName OpName =
7207 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7208
7209 // If either side is type-dependent, create an appropriate dependent
7210 // expression.
7211 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7212
John McCallc373d482010-01-27 01:50:18 +00007213 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00007214 // CHECKME: no 'operator' keyword?
7215 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7216 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +00007217 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00007218 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00007219 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00007220 /*ADL*/ true, /*Overloaded*/ false,
7221 UnresolvedSetIterator(),
7222 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +00007223 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00007224
Sebastian Redlf322ed62009-10-29 20:17:01 +00007225 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7226 Args, 2,
7227 Context.DependentTy,
7228 RLoc));
7229 }
7230
7231 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00007232 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007233
7234 // Subscript can only be overloaded as a member function.
7235
7236 // Add operator candidates that are member functions.
7237 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7238
7239 // Add builtin operator candidates.
7240 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7241
7242 // Perform overload resolution.
7243 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007244 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00007245 case OR_Success: {
7246 // We found a built-in operator or an overloaded operator.
7247 FunctionDecl *FnDecl = Best->Function;
7248
7249 if (FnDecl) {
7250 // We matched an overloaded operator. Build a call to that
7251 // operator.
7252
John McCall9aa472c2010-03-19 07:35:19 +00007253 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007254 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +00007255
Sebastian Redlf322ed62009-10-29 20:17:01 +00007256 // Convert the arguments.
7257 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007258 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007259 Best->FoundDecl, Method))
Sebastian Redlf322ed62009-10-29 20:17:01 +00007260 return ExprError();
7261
Anders Carlsson38f88ab2010-01-29 18:37:50 +00007262 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00007263 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +00007264 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007265 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +00007266 FnDecl->getParamDecl(0)),
7267 SourceLocation(),
7268 Owned(Args[1]));
7269 if (InputInit.isInvalid())
7270 return ExprError();
7271
7272 Args[1] = InputInit.takeAs<Expr>();
7273
Sebastian Redlf322ed62009-10-29 20:17:01 +00007274 // Determine the result type
7275 QualType ResultTy
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007276 = FnDecl->getType()->getAs<FunctionType>()
7277 ->getCallResultType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007278
7279 // Build the actual expression node.
7280 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7281 LLoc);
7282 UsualUnaryConversions(FnExpr);
7283
John McCall9ae2f072010-08-23 23:25:46 +00007284 CXXOperatorCallExpr *TheCall =
7285 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7286 FnExpr, Args, 2,
7287 ResultTy, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007288
John McCall9ae2f072010-08-23 23:25:46 +00007289 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +00007290 FnDecl))
7291 return ExprError();
7292
John McCall9ae2f072010-08-23 23:25:46 +00007293 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007294 } else {
7295 // We matched a built-in operator. Convert the arguments, then
7296 // break out so that we will build the appropriate built-in
7297 // operator node.
7298 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00007299 Best->Conversions[0], AA_Passing) ||
Sebastian Redlf322ed62009-10-29 20:17:01 +00007300 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00007301 Best->Conversions[1], AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00007302 return ExprError();
7303
7304 break;
7305 }
7306 }
7307
7308 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00007309 if (CandidateSet.empty())
7310 Diag(LLoc, diag::err_ovl_no_oper)
7311 << Args[0]->getType() << /*subscript*/ 0
7312 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7313 else
7314 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7315 << Args[0]->getType()
7316 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007317 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7318 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +00007319 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00007320 }
7321
7322 case OR_Ambiguous:
7323 Diag(LLoc, diag::err_ovl_ambiguous_oper)
7324 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007325 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7326 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007327 return ExprError();
7328
7329 case OR_Deleted:
7330 Diag(LLoc, diag::err_ovl_deleted_oper)
7331 << Best->Function->isDeleted() << "[]"
7332 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007333 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7334 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007335 return ExprError();
7336 }
7337
7338 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +00007339 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007340}
7341
Douglas Gregor88a35142008-12-22 05:46:06 +00007342/// BuildCallToMemberFunction - Build a call to a member
7343/// function. MemExpr is the expression that refers to the member
7344/// function (and includes the object parameter), Args/NumArgs are the
7345/// arguments to the function call (not including the object
7346/// parameter). The caller needs to validate that the member
7347/// expression refers to a member function or an overloaded member
7348/// function.
John McCall60d7b3a2010-08-24 06:29:42 +00007349ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00007350Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7351 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +00007352 unsigned NumArgs, SourceLocation RParenLoc) {
Douglas Gregor88a35142008-12-22 05:46:06 +00007353 // Dig out the member expression. This holds both the object
7354 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00007355 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7356
John McCall129e2df2009-11-30 22:42:35 +00007357 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00007358 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +00007359 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007360 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +00007361 if (isa<MemberExpr>(NakedMemExpr)) {
7362 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00007363 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +00007364 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +00007365 Qualifier = MemExpr->getQualifier();
John McCall129e2df2009-11-30 22:42:35 +00007366 } else {
7367 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007368 Qualifier = UnresExpr->getQualifier();
7369
John McCall701c89e2009-12-03 04:06:58 +00007370 QualType ObjectType = UnresExpr->getBaseType();
John McCall129e2df2009-11-30 22:42:35 +00007371
Douglas Gregor88a35142008-12-22 05:46:06 +00007372 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +00007373 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00007374
John McCallaa81e162009-12-01 22:10:20 +00007375 // FIXME: avoid copy.
7376 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7377 if (UnresExpr->hasExplicitTemplateArgs()) {
7378 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7379 TemplateArgs = &TemplateArgsBuffer;
7380 }
7381
John McCall129e2df2009-11-30 22:42:35 +00007382 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7383 E = UnresExpr->decls_end(); I != E; ++I) {
7384
John McCall701c89e2009-12-03 04:06:58 +00007385 NamedDecl *Func = *I;
7386 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7387 if (isa<UsingShadowDecl>(Func))
7388 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7389
John McCall129e2df2009-11-30 22:42:35 +00007390 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00007391 // If explicit template arguments were provided, we can't call a
7392 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00007393 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00007394 continue;
7395
John McCall9aa472c2010-03-19 07:35:19 +00007396 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCall86820f52010-01-26 01:37:31 +00007397 Args, NumArgs,
John McCall701c89e2009-12-03 04:06:58 +00007398 CandidateSet, /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00007399 } else {
John McCall129e2df2009-11-30 22:42:35 +00007400 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +00007401 I.getPair(), ActingDC, TemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00007402 ObjectType, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00007403 CandidateSet,
7404 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00007405 }
Douglas Gregordec06662009-08-21 18:42:58 +00007406 }
Mike Stump1eb44332009-09-09 15:08:12 +00007407
John McCall129e2df2009-11-30 22:42:35 +00007408 DeclarationName DeclName = UnresExpr->getMemberName();
7409
Douglas Gregor88a35142008-12-22 05:46:06 +00007410 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007411 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
7412 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00007413 case OR_Success:
7414 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00007415 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +00007416 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007417 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +00007418 break;
7419
7420 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00007421 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00007422 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00007423 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007424 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00007425 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007426 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007427
7428 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00007429 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00007430 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007431 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00007432 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007433 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007434
7435 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00007436 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007437 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00007438 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007439 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007440 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007441 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007442 }
7443
John McCall6bb80172010-03-30 21:47:33 +00007444 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +00007445
John McCallaa81e162009-12-01 22:10:20 +00007446 // If overload resolution picked a static member, build a
7447 // non-member call based on that function.
7448 if (Method->isStatic()) {
7449 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7450 Args, NumArgs, RParenLoc);
7451 }
7452
John McCall129e2df2009-11-30 22:42:35 +00007453 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00007454 }
7455
7456 assert(Method && "Member call to something that isn't a method?");
John McCall9ae2f072010-08-23 23:25:46 +00007457 CXXMemberCallExpr *TheCall =
7458 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
7459 Method->getCallResultType(),
7460 RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +00007461
Anders Carlssoneed3e692009-10-10 00:06:20 +00007462 // Check for a valid return type.
7463 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +00007464 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +00007465 return ExprError();
Anders Carlssoneed3e692009-10-10 00:06:20 +00007466
Douglas Gregor88a35142008-12-22 05:46:06 +00007467 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +00007468 // We only need to do this if there was actually an overload; otherwise
7469 // it was done at lookup.
John McCallaa81e162009-12-01 22:10:20 +00007470 Expr *ObjectArg = MemExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00007471 if (!Method->isStatic() &&
John McCall6bb80172010-03-30 21:47:33 +00007472 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7473 FoundDecl, Method))
John McCallaa81e162009-12-01 22:10:20 +00007474 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007475 MemExpr->setBase(ObjectArg);
7476
7477 // Convert the rest of the arguments
Douglas Gregor5f970ee2010-05-04 18:18:31 +00007478 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +00007479 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00007480 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00007481 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007482
John McCall9ae2f072010-08-23 23:25:46 +00007483 if (CheckFunctionCall(Method, TheCall))
John McCallaa81e162009-12-01 22:10:20 +00007484 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00007485
John McCall9ae2f072010-08-23 23:25:46 +00007486 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +00007487}
7488
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007489/// BuildCallToObjectOfClassType - Build a call to an object of class
7490/// type (C++ [over.call.object]), which can end up invoking an
7491/// overloaded function call operator (@c operator()) or performing a
7492/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +00007493ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00007494Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00007495 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007496 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007497 SourceLocation RParenLoc) {
7498 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00007499 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00007500
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007501 // C++ [over.call.object]p1:
7502 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00007503 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007504 // candidate functions includes at least the function call
7505 // operators of T. The function call operators of T are obtained by
7506 // ordinary lookup of the name operator() in the context of
7507 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +00007508 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00007509 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00007510
7511 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007512 PDiag(diag::err_incomplete_object_call)
Douglas Gregor593564b2009-11-15 07:48:03 +00007513 << Object->getSourceRange()))
7514 return true;
7515
John McCalla24dc2e2009-11-17 02:14:36 +00007516 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7517 LookupQualifiedName(R, Record->getDecl());
7518 R.suppressDiagnostics();
7519
Douglas Gregor593564b2009-11-15 07:48:03 +00007520 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00007521 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00007522 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCall86820f52010-01-26 01:37:31 +00007523 Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00007524 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00007525 }
Douglas Gregor4a27d702009-10-21 06:18:39 +00007526
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007527 // C++ [over.call.object]p2:
7528 // In addition, for each conversion function declared in T of the
7529 // form
7530 //
7531 // operator conversion-type-id () cv-qualifier;
7532 //
7533 // where cv-qualifier is the same cv-qualification as, or a
7534 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00007535 // denotes the type "pointer to function of (P1,...,Pn) returning
7536 // R", or the type "reference to pointer to function of
7537 // (P1,...,Pn) returning R", or the type "reference to function
7538 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007539 // is also considered as a candidate function. Similarly,
7540 // surrogate call functions are added to the set of candidate
7541 // functions for each conversion function declared in an
7542 // accessible base class provided the function is not hidden
7543 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +00007544 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00007545 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00007546 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00007547 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00007548 NamedDecl *D = *I;
7549 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7550 if (isa<UsingShadowDecl>(D))
7551 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7552
Douglas Gregor4a27d702009-10-21 06:18:39 +00007553 // Skip over templated conversion functions; they aren't
7554 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00007555 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00007556 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007557
John McCall701c89e2009-12-03 04:06:58 +00007558 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCallba135432009-11-21 08:51:07 +00007559
Douglas Gregor4a27d702009-10-21 06:18:39 +00007560 // Strip the reference type (if any) and then the pointer type (if
7561 // any) to get down to what might be a function type.
7562 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7563 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7564 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007565
Douglas Gregor4a27d702009-10-21 06:18:39 +00007566 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall9aa472c2010-03-19 07:35:19 +00007567 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall701c89e2009-12-03 04:06:58 +00007568 Object->getType(), Args, NumArgs,
7569 CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007570 }
Mike Stump1eb44332009-09-09 15:08:12 +00007571
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007572 // Perform overload resolution.
7573 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007574 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
7575 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007576 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007577 // Overload resolution succeeded; we'll build the appropriate call
7578 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007579 break;
7580
7581 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00007582 if (CandidateSet.empty())
7583 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7584 << Object->getType() << /*call*/ 1
7585 << Object->getSourceRange();
7586 else
7587 Diag(Object->getSourceRange().getBegin(),
7588 diag::err_ovl_no_viable_object_call)
7589 << Object->getType() << Object->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007590 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007591 break;
7592
7593 case OR_Ambiguous:
7594 Diag(Object->getSourceRange().getBegin(),
7595 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00007596 << Object->getType() << Object->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007597 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007598 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007599
7600 case OR_Deleted:
7601 Diag(Object->getSourceRange().getBegin(),
7602 diag::err_ovl_deleted_object_call)
7603 << Best->Function->isDeleted()
7604 << Object->getType() << Object->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007605 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007606 break;
Mike Stump1eb44332009-09-09 15:08:12 +00007607 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007608
Douglas Gregorff331c12010-07-25 18:17:45 +00007609 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007610 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007611
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007612 if (Best->Function == 0) {
7613 // Since there is no function declaration, this is one of the
7614 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00007615 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007616 = cast<CXXConversionDecl>(
7617 Best->Conversions[0].UserDefined.ConversionFunction);
7618
John McCall9aa472c2010-03-19 07:35:19 +00007619 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007620 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00007621
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007622 // We selected one of the surrogate functions that converts the
7623 // object parameter to a function pointer. Perform the conversion
7624 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00007625
7626 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00007627 // and then call it.
John McCall6bb80172010-03-30 21:47:33 +00007628 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7629 Conv);
Fariborz Jahanianb7400232009-09-28 23:23:40 +00007630
John McCallf312b1e2010-08-26 23:41:50 +00007631 return ActOnCallExpr(S, CE, LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007632 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007633 }
7634
John McCall9aa472c2010-03-19 07:35:19 +00007635 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007636 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00007637
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007638 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7639 // that calls this method, using Object for the implicit object
7640 // parameter and passing along the remaining arguments.
7641 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall183700f2009-09-21 23:43:11 +00007642 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007643
7644 unsigned NumArgsInProto = Proto->getNumArgs();
7645 unsigned NumArgsToCheck = NumArgs;
7646
7647 // Build the full argument list for the method call (the
7648 // implicit object parameter is placed at the beginning of the
7649 // list).
7650 Expr **MethodArgs;
7651 if (NumArgs < NumArgsInProto) {
7652 NumArgsToCheck = NumArgsInProto;
7653 MethodArgs = new Expr*[NumArgsInProto + 1];
7654 } else {
7655 MethodArgs = new Expr*[NumArgs + 1];
7656 }
7657 MethodArgs[0] = Object;
7658 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7659 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00007660
7661 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00007662 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007663 UsualUnaryConversions(NewFn);
7664
7665 // Once we've built TheCall, all of the expressions are properly
7666 // owned.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007667 QualType ResultTy = Method->getCallResultType();
John McCall9ae2f072010-08-23 23:25:46 +00007668 CXXOperatorCallExpr *TheCall =
7669 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
7670 MethodArgs, NumArgs + 1,
7671 ResultTy, RParenLoc);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007672 delete [] MethodArgs;
7673
John McCall9ae2f072010-08-23 23:25:46 +00007674 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +00007675 Method))
7676 return true;
7677
Douglas Gregor518fda12009-01-13 05:10:00 +00007678 // We may have default arguments. If so, we need to allocate more
7679 // slots in the call for them.
7680 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00007681 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00007682 else if (NumArgs > NumArgsInProto)
7683 NumArgsToCheck = NumArgsInProto;
7684
Chris Lattner312531a2009-04-12 08:11:20 +00007685 bool IsError = false;
7686
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007687 // Initialize the implicit object parameter.
Douglas Gregor5fccd362010-03-03 23:55:11 +00007688 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007689 Best->FoundDecl, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007690 TheCall->setArg(0, Object);
7691
Chris Lattner312531a2009-04-12 08:11:20 +00007692
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007693 // Check the argument types.
7694 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007695 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00007696 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007697 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00007698
Douglas Gregor518fda12009-01-13 05:10:00 +00007699 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +00007700
John McCall60d7b3a2010-08-24 06:29:42 +00007701 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +00007702 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007703 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +00007704 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +00007705 SourceLocation(), Arg);
Anders Carlsson3faa4862010-01-29 18:43:53 +00007706
7707 IsError |= InputInit.isInvalid();
7708 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00007709 } else {
John McCall60d7b3a2010-08-24 06:29:42 +00007710 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +00007711 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7712 if (DefArg.isInvalid()) {
7713 IsError = true;
7714 break;
7715 }
7716
7717 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00007718 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007719
7720 TheCall->setArg(i + 1, Arg);
7721 }
7722
7723 // If this is a variadic call, handle args passed through "...".
7724 if (Proto->isVariadic()) {
7725 // Promote the arguments (C99 6.5.2.2p7).
7726 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7727 Expr *Arg = Args[i];
Chris Lattner40378332010-05-16 04:01:30 +00007728 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007729 TheCall->setArg(i + 1, Arg);
7730 }
7731 }
7732
Chris Lattner312531a2009-04-12 08:11:20 +00007733 if (IsError) return true;
7734
John McCall9ae2f072010-08-23 23:25:46 +00007735 if (CheckFunctionCall(Method, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00007736 return true;
7737
John McCall182f7092010-08-24 06:09:16 +00007738 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007739}
7740
Douglas Gregor8ba10742008-11-20 16:27:02 +00007741/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00007742/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00007743/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +00007744ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00007745Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00007746 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00007747
John McCall5769d612010-02-08 23:07:23 +00007748 SourceLocation Loc = Base->getExprLoc();
7749
Douglas Gregor8ba10742008-11-20 16:27:02 +00007750 // C++ [over.ref]p1:
7751 //
7752 // [...] An expression x->m is interpreted as (x.operator->())->m
7753 // for a class object x of type T if T::operator->() exists and if
7754 // the operator is selected as the best match function by the
7755 // overload resolution mechanism (13.3).
Douglas Gregor8ba10742008-11-20 16:27:02 +00007756 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +00007757 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +00007758 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007759
John McCall5769d612010-02-08 23:07:23 +00007760 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +00007761 PDiag(diag::err_typecheck_incomplete_tag)
7762 << Base->getSourceRange()))
7763 return ExprError();
7764
John McCalla24dc2e2009-11-17 02:14:36 +00007765 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7766 LookupQualifiedName(R, BaseRecord->getDecl());
7767 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00007768
7769 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00007770 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00007771 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00007772 /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00007773 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00007774
7775 // Perform overload resolution.
7776 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007777 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00007778 case OR_Success:
7779 // Overload resolution succeeded; we'll build the call below.
7780 break;
7781
7782 case OR_No_Viable_Function:
7783 if (CandidateSet.empty())
7784 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007785 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007786 else
7787 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007788 << "operator->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007789 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007790 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007791
7792 case OR_Ambiguous:
7793 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlssone30572a2009-09-10 23:18:36 +00007794 << "->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007795 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007796 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007797
7798 case OR_Deleted:
7799 Diag(OpLoc, diag::err_ovl_deleted_oper)
7800 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00007801 << "->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007802 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007803 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007804 }
7805
John McCall9aa472c2010-03-19 07:35:19 +00007806 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007807 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +00007808
Douglas Gregor8ba10742008-11-20 16:27:02 +00007809 // Convert the object parameter.
7810 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00007811 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7812 Best->FoundDecl, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007813 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00007814
Douglas Gregor8ba10742008-11-20 16:27:02 +00007815 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00007816 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7817 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00007818 UsualUnaryConversions(FnExpr);
Anders Carlsson15ea3782009-10-13 22:43:21 +00007819
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007820 QualType ResultTy = Method->getCallResultType();
John McCall9ae2f072010-08-23 23:25:46 +00007821 CXXOperatorCallExpr *TheCall =
7822 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7823 &Base, 1, ResultTy, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +00007824
John McCall9ae2f072010-08-23 23:25:46 +00007825 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00007826 Method))
7827 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00007828 return Owned(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00007829}
7830
Douglas Gregor904eed32008-11-10 20:40:00 +00007831/// FixOverloadedFunctionReference - E is an expression that refers to
7832/// a C++ overloaded function (possibly with some parentheses and
7833/// perhaps a '&' around it). We have resolved the overloaded function
7834/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00007835/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +00007836Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +00007837 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00007838 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00007839 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7840 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00007841 if (SubExpr == PE->getSubExpr())
7842 return PE->Retain();
7843
7844 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7845 }
7846
7847 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00007848 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7849 Found, Fn);
Douglas Gregor097bfb12009-10-23 22:18:25 +00007850 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00007851 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00007852 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +00007853 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +00007854 if (SubExpr == ICE->getSubExpr())
7855 return ICE->Retain();
7856
John McCallf871d0c2010-08-07 06:22:56 +00007857 return ImplicitCastExpr::Create(Context, ICE->getType(),
7858 ICE->getCastKind(),
7859 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +00007860 ICE->getValueKind());
Douglas Gregor699ee522009-11-20 19:42:02 +00007861 }
7862
7863 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00007864 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00007865 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00007866 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7867 if (Method->isStatic()) {
7868 // Do nothing: static member functions aren't any different
7869 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00007870 } else {
John McCallf7a1a742009-11-24 19:00:30 +00007871 // Fix the sub expression, which really has to be an
7872 // UnresolvedLookupExpr holding an overloaded member function
7873 // or template.
John McCall6bb80172010-03-30 21:47:33 +00007874 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7875 Found, Fn);
John McCallba135432009-11-21 08:51:07 +00007876 if (SubExpr == UnOp->getSubExpr())
7877 return UnOp->Retain();
Douglas Gregor699ee522009-11-20 19:42:02 +00007878
John McCallba135432009-11-21 08:51:07 +00007879 assert(isa<DeclRefExpr>(SubExpr)
7880 && "fixed to something other than a decl ref");
7881 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7882 && "fixed to a member ref with no nested name qualifier");
7883
7884 // We have taken the address of a pointer to member
7885 // function. Perform the computation here so that we get the
7886 // appropriate pointer to member type.
7887 QualType ClassType
7888 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7889 QualType MemPtrType
7890 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7891
John McCall2de56d12010-08-25 11:45:40 +00007892 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
John McCallba135432009-11-21 08:51:07 +00007893 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00007894 }
7895 }
John McCall6bb80172010-03-30 21:47:33 +00007896 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7897 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00007898 if (SubExpr == UnOp->getSubExpr())
7899 return UnOp->Retain();
Anders Carlsson96ad5332009-10-21 17:16:23 +00007900
John McCall2de56d12010-08-25 11:45:40 +00007901 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +00007902 Context.getPointerType(SubExpr->getType()),
7903 UnOp->getOperatorLoc());
Douglas Gregor699ee522009-11-20 19:42:02 +00007904 }
John McCallba135432009-11-21 08:51:07 +00007905
7906 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00007907 // FIXME: avoid copy.
7908 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00007909 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00007910 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7911 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00007912 }
7913
John McCallba135432009-11-21 08:51:07 +00007914 return DeclRefExpr::Create(Context,
7915 ULE->getQualifier(),
7916 ULE->getQualifierRange(),
7917 Fn,
7918 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00007919 Fn->getType(),
7920 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00007921 }
7922
John McCall129e2df2009-11-30 22:42:35 +00007923 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00007924 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00007925 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7926 if (MemExpr->hasExplicitTemplateArgs()) {
7927 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7928 TemplateArgs = &TemplateArgsBuffer;
7929 }
John McCalld5532b62009-11-23 01:53:49 +00007930
John McCallaa81e162009-12-01 22:10:20 +00007931 Expr *Base;
7932
7933 // If we're filling in
7934 if (MemExpr->isImplicitAccess()) {
7935 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7936 return DeclRefExpr::Create(Context,
7937 MemExpr->getQualifier(),
7938 MemExpr->getQualifierRange(),
7939 Fn,
7940 MemExpr->getMemberLoc(),
7941 Fn->getType(),
7942 TemplateArgs);
Douglas Gregor828a1972010-01-07 23:12:05 +00007943 } else {
7944 SourceLocation Loc = MemExpr->getMemberLoc();
7945 if (MemExpr->getQualifier())
7946 Loc = MemExpr->getQualifierRange().getBegin();
7947 Base = new (Context) CXXThisExpr(Loc,
7948 MemExpr->getBaseType(),
7949 /*isImplicit=*/true);
7950 }
John McCallaa81e162009-12-01 22:10:20 +00007951 } else
7952 Base = MemExpr->getBase()->Retain();
7953
7954 return MemberExpr::Create(Context, Base,
Douglas Gregor699ee522009-11-20 19:42:02 +00007955 MemExpr->isArrow(),
7956 MemExpr->getQualifier(),
7957 MemExpr->getQualifierRange(),
7958 Fn,
John McCall6bb80172010-03-30 21:47:33 +00007959 Found,
Abramo Bagnara25777432010-08-11 22:01:17 +00007960 MemExpr->getMemberNameInfo(),
John McCallaa81e162009-12-01 22:10:20 +00007961 TemplateArgs,
Douglas Gregor699ee522009-11-20 19:42:02 +00007962 Fn->getType());
7963 }
7964
Douglas Gregor699ee522009-11-20 19:42:02 +00007965 assert(false && "Invalid reference to overloaded function");
7966 return E->Retain();
Douglas Gregor904eed32008-11-10 20:40:00 +00007967}
7968
John McCall60d7b3a2010-08-24 06:29:42 +00007969ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
7970 DeclAccessPair Found,
7971 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +00007972 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +00007973}
7974
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007975} // end namespace clang