blob: 65d6bc8f7a02a9d80365d781c5a2e0c477c5fa0b [file] [log] [blame]
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCall7cd088e2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000021#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000024#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000026#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000027#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor661b4932010-09-12 04:28:07 +000028#include "llvm/ADT/DenseSet.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000029#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000030#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000031#include <algorithm>
32
33namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000034using namespace sema;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000035
John McCall120d63c2010-08-24 20:38:10 +000036static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
37 bool InOverloadResolution,
38 StandardConversionSequence &SCS);
39static OverloadingResult
40IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
41 UserDefinedConversionSequence& User,
42 OverloadCandidateSet& Conversions,
43 bool AllowExplicit);
44
45
46static ImplicitConversionSequence::CompareKind
47CompareStandardConversionSequences(Sema &S,
48 const StandardConversionSequence& SCS1,
49 const StandardConversionSequence& SCS2);
50
51static ImplicitConversionSequence::CompareKind
52CompareQualificationConversions(Sema &S,
53 const StandardConversionSequence& SCS1,
54 const StandardConversionSequence& SCS2);
55
56static ImplicitConversionSequence::CompareKind
57CompareDerivedToBaseConversions(Sema &S,
58 const StandardConversionSequence& SCS1,
59 const StandardConversionSequence& SCS2);
60
61
62
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000063/// GetConversionCategory - Retrieve the implicit conversion
64/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000065ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000066GetConversionCategory(ImplicitConversionKind Kind) {
67 static const ImplicitConversionCategory
68 Category[(int)ICK_Num_Conversion_Kinds] = {
69 ICC_Identity,
70 ICC_Lvalue_Transformation,
71 ICC_Lvalue_Transformation,
72 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +000073 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000074 ICC_Qualification_Adjustment,
75 ICC_Promotion,
76 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000077 ICC_Promotion,
78 ICC_Conversion,
79 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000080 ICC_Conversion,
81 ICC_Conversion,
82 ICC_Conversion,
83 ICC_Conversion,
84 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000085 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000086 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +000087 ICC_Conversion,
88 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000089 ICC_Conversion
90 };
91 return Category[(int)Kind];
92}
93
94/// GetConversionRank - Retrieve the implicit conversion rank
95/// corresponding to the given implicit conversion kind.
96ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
97 static const ImplicitConversionRank
98 Rank[(int)ICK_Num_Conversion_Kinds] = {
99 ICR_Exact_Match,
100 ICR_Exact_Match,
101 ICR_Exact_Match,
102 ICR_Exact_Match,
103 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +0000104 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000105 ICR_Promotion,
106 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000107 ICR_Promotion,
108 ICR_Conversion,
109 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000110 ICR_Conversion,
111 ICR_Conversion,
112 ICR_Conversion,
113 ICR_Conversion,
114 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000115 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000116 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000117 ICR_Conversion,
118 ICR_Conversion,
Chandler Carruth23a370f2010-02-25 07:20:54 +0000119 ICR_Complex_Real_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000120 };
121 return Rank[(int)Kind];
122}
123
124/// GetImplicitConversionName - Return the name of this kind of
125/// implicit conversion.
126const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +0000127 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000128 "No conversion",
129 "Lvalue-to-rvalue",
130 "Array-to-pointer",
131 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000132 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000133 "Qualification",
134 "Integral promotion",
135 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000136 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000137 "Integral conversion",
138 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000139 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000140 "Floating-integral conversion",
141 "Pointer conversion",
142 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000143 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000144 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000145 "Derived-to-base conversion",
146 "Vector conversion",
147 "Vector splat",
148 "Complex-real conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000149 };
150 return Name[Kind];
151}
152
Douglas Gregor60d62c22008-10-31 16:23:19 +0000153/// StandardConversionSequence - Set the standard conversion
154/// sequence to the identity conversion.
155void StandardConversionSequence::setAsIdentityConversion() {
156 First = ICK_Identity;
157 Second = ICK_Identity;
158 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000159 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000160 ReferenceBinding = false;
161 DirectBinding = false;
Sebastian Redl85002392009-03-29 22:46:24 +0000162 RRefBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000163 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000164}
165
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000166/// getRank - Retrieve the rank of this standard conversion sequence
167/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
168/// implicit conversions.
169ImplicitConversionRank StandardConversionSequence::getRank() const {
170 ImplicitConversionRank Rank = ICR_Exact_Match;
171 if (GetConversionRank(First) > Rank)
172 Rank = GetConversionRank(First);
173 if (GetConversionRank(Second) > Rank)
174 Rank = GetConversionRank(Second);
175 if (GetConversionRank(Third) > Rank)
176 Rank = GetConversionRank(Third);
177 return Rank;
178}
179
180/// isPointerConversionToBool - Determines whether this conversion is
181/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000182/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000183/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000184bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000185 // Note that FromType has not necessarily been transformed by the
186 // array-to-pointer or function-to-pointer implicit conversions, so
187 // check for their presence as well as checking whether FromType is
188 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000189 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000190 (getFromType()->isPointerType() ||
191 getFromType()->isObjCObjectPointerType() ||
192 getFromType()->isBlockPointerType() ||
Anders Carlssonc8df0b62010-11-05 00:12:09 +0000193 getFromType()->isNullPtrType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000194 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
195 return true;
196
197 return false;
198}
199
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000200/// isPointerConversionToVoidPointer - Determines whether this
201/// conversion is a conversion of a pointer to a void pointer. This is
202/// used as part of the ranking of standard conversion sequences (C++
203/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000204bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000205StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000206isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000207 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000208 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000209
210 // Note that FromType has not necessarily been transformed by the
211 // array-to-pointer implicit conversion, so check for its presence
212 // and redo the conversion to get a pointer.
213 if (First == ICK_Array_To_Pointer)
214 FromType = Context.getArrayDecayedType(FromType);
215
John McCall202422e2010-10-26 06:40:27 +0000216 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000217 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000218 return ToPtrType->getPointeeType()->isVoidType();
219
220 return false;
221}
222
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000223/// DebugPrint - Print this standard conversion sequence to standard
224/// error. Useful for debugging overloading issues.
225void StandardConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000226 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000227 bool PrintedSomething = false;
228 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000229 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000230 PrintedSomething = true;
231 }
232
233 if (Second != ICK_Identity) {
234 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000235 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000236 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000237 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000238
239 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000240 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000241 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000242 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000243 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000244 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000245 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000246 PrintedSomething = true;
247 }
248
249 if (Third != ICK_Identity) {
250 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000251 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000252 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000253 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000254 PrintedSomething = true;
255 }
256
257 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000258 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000259 }
260}
261
262/// DebugPrint - Print this user-defined conversion sequence to standard
263/// error. Useful for debugging overloading issues.
264void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000265 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000266 if (Before.First || Before.Second || Before.Third) {
267 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000268 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000269 }
Benjamin Kramer900fc632010-04-17 09:33:03 +0000270 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000271 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000272 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000273 After.DebugPrint();
274 }
275}
276
277/// DebugPrint - Print this implicit conversion sequence to standard
278/// error. Useful for debugging overloading issues.
279void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000280 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000281 switch (ConversionKind) {
282 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000283 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000284 Standard.DebugPrint();
285 break;
286 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000287 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000288 UserDefined.DebugPrint();
289 break;
290 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000291 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000292 break;
John McCall1d318332010-01-12 00:44:57 +0000293 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000294 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000295 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000296 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000297 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000298 break;
299 }
300
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000301 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000302}
303
John McCall1d318332010-01-12 00:44:57 +0000304void AmbiguousConversionSequence::construct() {
305 new (&conversions()) ConversionSet();
306}
307
308void AmbiguousConversionSequence::destruct() {
309 conversions().~ConversionSet();
310}
311
312void
313AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
314 FromTypePtr = O.FromTypePtr;
315 ToTypePtr = O.ToTypePtr;
316 new (&conversions()) ConversionSet(O.conversions());
317}
318
Douglas Gregora9333192010-05-08 17:41:32 +0000319namespace {
320 // Structure used by OverloadCandidate::DeductionFailureInfo to store
321 // template parameter and template argument information.
322 struct DFIParamWithArguments {
323 TemplateParameter Param;
324 TemplateArgument FirstArg;
325 TemplateArgument SecondArg;
326 };
327}
328
329/// \brief Convert from Sema's representation of template deduction information
330/// to the form used in overload-candidate information.
331OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000332static MakeDeductionFailureInfo(ASTContext &Context,
333 Sema::TemplateDeductionResult TDK,
John McCall2a7fb272010-08-25 05:32:35 +0000334 TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000335 OverloadCandidate::DeductionFailureInfo Result;
336 Result.Result = static_cast<unsigned>(TDK);
337 Result.Data = 0;
338 switch (TDK) {
339 case Sema::TDK_Success:
340 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000341 case Sema::TDK_TooManyArguments:
342 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000343 break;
344
345 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000346 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000347 Result.Data = Info.Param.getOpaqueValue();
348 break;
349
Douglas Gregora9333192010-05-08 17:41:32 +0000350 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000351 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000352 // FIXME: Should allocate from normal heap so that we can free this later.
353 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000354 Saved->Param = Info.Param;
355 Saved->FirstArg = Info.FirstArg;
356 Saved->SecondArg = Info.SecondArg;
357 Result.Data = Saved;
358 break;
359 }
360
361 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000362 Result.Data = Info.take();
363 break;
364
Douglas Gregora9333192010-05-08 17:41:32 +0000365 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000366 case Sema::TDK_FailedOverloadResolution:
367 break;
368 }
369
370 return Result;
371}
John McCall1d318332010-01-12 00:44:57 +0000372
Douglas Gregora9333192010-05-08 17:41:32 +0000373void OverloadCandidate::DeductionFailureInfo::Destroy() {
374 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
375 case Sema::TDK_Success:
376 case Sema::TDK_InstantiationDepth:
377 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000378 case Sema::TDK_TooManyArguments:
379 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000380 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000381 break;
382
Douglas Gregora9333192010-05-08 17:41:32 +0000383 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000384 case Sema::TDK_Underqualified:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000385 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000386 Data = 0;
387 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000388
389 case Sema::TDK_SubstitutionFailure:
390 // FIXME: Destroy the template arugment list?
391 Data = 0;
392 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000393
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000394 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000395 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000396 case Sema::TDK_FailedOverloadResolution:
397 break;
398 }
399}
400
401TemplateParameter
402OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
403 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
404 case Sema::TDK_Success:
405 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000406 case Sema::TDK_TooManyArguments:
407 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000408 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000409 return TemplateParameter();
410
411 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000412 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000413 return TemplateParameter::getFromOpaqueValue(Data);
414
415 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000416 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000417 return static_cast<DFIParamWithArguments*>(Data)->Param;
418
419 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000420 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000421 case Sema::TDK_FailedOverloadResolution:
422 break;
423 }
424
425 return TemplateParameter();
426}
Douglas Gregorec20f462010-05-08 20:07:26 +0000427
428TemplateArgumentList *
429OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
430 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
431 case Sema::TDK_Success:
432 case Sema::TDK_InstantiationDepth:
433 case Sema::TDK_TooManyArguments:
434 case Sema::TDK_TooFewArguments:
435 case Sema::TDK_Incomplete:
436 case Sema::TDK_InvalidExplicitArguments:
437 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000438 case Sema::TDK_Underqualified:
Douglas Gregorec20f462010-05-08 20:07:26 +0000439 return 0;
440
441 case Sema::TDK_SubstitutionFailure:
442 return static_cast<TemplateArgumentList*>(Data);
443
444 // Unhandled
445 case Sema::TDK_NonDeducedMismatch:
446 case Sema::TDK_FailedOverloadResolution:
447 break;
448 }
449
450 return 0;
451}
452
Douglas Gregora9333192010-05-08 17:41:32 +0000453const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
454 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
455 case Sema::TDK_Success:
456 case Sema::TDK_InstantiationDepth:
457 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000458 case Sema::TDK_TooManyArguments:
459 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000460 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000461 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000462 return 0;
463
Douglas Gregora9333192010-05-08 17:41:32 +0000464 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000465 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000466 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
467
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000468 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000469 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000470 case Sema::TDK_FailedOverloadResolution:
471 break;
472 }
473
474 return 0;
475}
476
477const TemplateArgument *
478OverloadCandidate::DeductionFailureInfo::getSecondArg() {
479 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
480 case Sema::TDK_Success:
481 case Sema::TDK_InstantiationDepth:
482 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000483 case Sema::TDK_TooManyArguments:
484 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000485 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000486 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000487 return 0;
488
Douglas Gregora9333192010-05-08 17:41:32 +0000489 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000490 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000491 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
492
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000493 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000494 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000495 case Sema::TDK_FailedOverloadResolution:
496 break;
497 }
498
499 return 0;
500}
501
502void OverloadCandidateSet::clear() {
Douglas Gregora9333192010-05-08 17:41:32 +0000503 inherited::clear();
504 Functions.clear();
505}
506
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000507// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000508// overload of the declarations in Old. This routine returns false if
509// New and Old cannot be overloaded, e.g., if New has the same
510// signature as some function in Old (C++ 1.3.10) or if the Old
511// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000512// it does return false, MatchedDecl will point to the decl that New
513// cannot be overloaded with. This decl may be a UsingShadowDecl on
514// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000515//
516// Example: Given the following input:
517//
518// void f(int, float); // #1
519// void f(int, int); // #2
520// int f(int, int); // #3
521//
522// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000523// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000524//
John McCall51fa86f2009-12-02 08:47:38 +0000525// When we process #2, Old contains only the FunctionDecl for #1. By
526// comparing the parameter types, we see that #1 and #2 are overloaded
527// (since they have different signatures), so this routine returns
528// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000529//
John McCall51fa86f2009-12-02 08:47:38 +0000530// When we process #3, Old is an overload set containing #1 and #2. We
531// compare the signatures of #3 to #1 (they're overloaded, so we do
532// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
533// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000534// signature), IsOverload returns false and MatchedDecl will be set to
535// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000536//
537// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
538// into a class by a using declaration. The rules for whether to hide
539// shadow declarations ignore some properties which otherwise figure
540// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000541Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000542Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
543 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000544 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000545 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000546 NamedDecl *OldD = *I;
547
548 bool OldIsUsingDecl = false;
549 if (isa<UsingShadowDecl>(OldD)) {
550 OldIsUsingDecl = true;
551
552 // We can always introduce two using declarations into the same
553 // context, even if they have identical signatures.
554 if (NewIsUsingDecl) continue;
555
556 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
557 }
558
559 // If either declaration was introduced by a using declaration,
560 // we'll need to use slightly different rules for matching.
561 // Essentially, these rules are the normal rules, except that
562 // function templates hide function templates with different
563 // return types or template parameter lists.
564 bool UseMemberUsingDeclRules =
565 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
566
John McCall51fa86f2009-12-02 08:47:38 +0000567 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000568 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
569 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
570 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
571 continue;
572 }
573
John McCall871b2e72009-12-09 03:35:25 +0000574 Match = *I;
575 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000576 }
John McCall51fa86f2009-12-02 08:47:38 +0000577 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000578 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
579 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
580 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
581 continue;
582 }
583
John McCall871b2e72009-12-09 03:35:25 +0000584 Match = *I;
585 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000586 }
John McCalld7945c62010-11-10 03:01:53 +0000587 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000588 // We can overload with these, which can show up when doing
589 // redeclaration checks for UsingDecls.
590 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000591 } else if (isa<TagDecl>(OldD)) {
592 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000593 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
594 // Optimistically assume that an unresolved using decl will
595 // overload; if it doesn't, we'll have to diagnose during
596 // template instantiation.
597 } else {
John McCall68263142009-11-18 22:49:29 +0000598 // (C++ 13p1):
599 // Only function declarations can be overloaded; object and type
600 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000601 Match = *I;
602 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000603 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000604 }
John McCall68263142009-11-18 22:49:29 +0000605
John McCall871b2e72009-12-09 03:35:25 +0000606 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000607}
608
John McCallad00b772010-06-16 08:42:20 +0000609bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
610 bool UseUsingDeclRules) {
John McCall7b492022010-08-12 07:09:11 +0000611 // If both of the functions are extern "C", then they are not
612 // overloads.
613 if (Old->isExternC() && New->isExternC())
614 return false;
615
John McCall68263142009-11-18 22:49:29 +0000616 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
617 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
618
619 // C++ [temp.fct]p2:
620 // A function template can be overloaded with other function templates
621 // and with normal (non-template) functions.
622 if ((OldTemplate == 0) != (NewTemplate == 0))
623 return true;
624
625 // Is the function New an overload of the function Old?
626 QualType OldQType = Context.getCanonicalType(Old->getType());
627 QualType NewQType = Context.getCanonicalType(New->getType());
628
629 // Compare the signatures (C++ 1.3.10) of the two functions to
630 // determine whether they are overloads. If we find any mismatch
631 // in the signature, they are overloads.
632
633 // If either of these functions is a K&R-style function (no
634 // prototype), then we consider them to have matching signatures.
635 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
636 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
637 return false;
638
639 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
640 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
641
642 // The signature of a function includes the types of its
643 // parameters (C++ 1.3.10), which includes the presence or absence
644 // of the ellipsis; see C++ DR 357).
645 if (OldQType != NewQType &&
646 (OldType->getNumArgs() != NewType->getNumArgs() ||
647 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000648 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000649 return true;
650
651 // C++ [temp.over.link]p4:
652 // The signature of a function template consists of its function
653 // signature, its return type and its template parameter list. The names
654 // of the template parameters are significant only for establishing the
655 // relationship between the template parameters and the rest of the
656 // signature.
657 //
658 // We check the return type and template parameter lists for function
659 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +0000660 //
661 // However, we don't consider either of these when deciding whether
662 // a member introduced by a shadow declaration is hidden.
663 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +0000664 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
665 OldTemplate->getTemplateParameters(),
666 false, TPL_TemplateMatch) ||
667 OldType->getResultType() != NewType->getResultType()))
668 return true;
669
670 // If the function is a class member, its signature includes the
671 // cv-qualifiers (if any) on the function itself.
672 //
673 // As part of this, also check whether one of the member functions
674 // is static, in which case they are not overloads (C++
675 // 13.1p2). While not part of the definition of the signature,
676 // this check is important to determine whether these functions
677 // can be overloaded.
678 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
679 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
680 if (OldMethod && NewMethod &&
681 !OldMethod->isStatic() && !NewMethod->isStatic() &&
682 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
683 return true;
684
685 // The signatures match; this is not an overload.
686 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000687}
688
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000689/// TryImplicitConversion - Attempt to perform an implicit conversion
690/// from the given expression (Expr) to the given type (ToType). This
691/// function returns an implicit conversion sequence that can be used
692/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000693///
694/// void f(float f);
695/// void g(int i) { f(i); }
696///
697/// this routine would produce an implicit conversion sequence to
698/// describe the initialization of f from i, which will be a standard
699/// conversion sequence containing an lvalue-to-rvalue conversion (C++
700/// 4.1) followed by a floating-integral conversion (C++ 4.9).
701//
702/// Note that this routine only determines how the conversion can be
703/// performed; it does not actually perform the conversion. As such,
704/// it will not produce any diagnostics if no conversion is available,
705/// but will instead return an implicit conversion sequence of kind
706/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000707///
708/// If @p SuppressUserConversions, then user-defined conversions are
709/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000710/// If @p AllowExplicit, then explicit user-defined conversions are
711/// permitted.
John McCall120d63c2010-08-24 20:38:10 +0000712static ImplicitConversionSequence
713TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
714 bool SuppressUserConversions,
715 bool AllowExplicit,
716 bool InOverloadResolution) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000717 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +0000718 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
719 ICS.Standard)) {
John McCall1d318332010-01-12 00:44:57 +0000720 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +0000721 return ICS;
722 }
723
John McCall120d63c2010-08-24 20:38:10 +0000724 if (!S.getLangOptions().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +0000725 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +0000726 return ICS;
727 }
728
Douglas Gregor604eb652010-08-11 02:15:33 +0000729 // C++ [over.ics.user]p4:
730 // A conversion of an expression of class type to the same class
731 // type is given Exact Match rank, and a conversion of an
732 // expression of class type to a base class of that type is
733 // given Conversion rank, in spite of the fact that a copy/move
734 // constructor (i.e., a user-defined conversion function) is
735 // called for those cases.
736 QualType FromType = From->getType();
737 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +0000738 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
739 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000740 ICS.setStandard();
741 ICS.Standard.setAsIdentityConversion();
742 ICS.Standard.setFromType(FromType);
743 ICS.Standard.setAllToTypes(ToType);
744
745 // We don't actually check at this point whether there is a valid
746 // copy/move constructor, since overloading just assumes that it
747 // exists. When we actually perform initialization, we'll find the
748 // appropriate constructor to copy the returned object, if needed.
749 ICS.Standard.CopyConstructor = 0;
Douglas Gregor604eb652010-08-11 02:15:33 +0000750
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000751 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +0000752 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000753 ICS.Standard.Second = ICK_Derived_To_Base;
Douglas Gregor604eb652010-08-11 02:15:33 +0000754
755 return ICS;
756 }
757
758 if (SuppressUserConversions) {
759 // We're not in the case above, so there is no conversion that
760 // we can perform.
761 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000762 return ICS;
763 }
764
765 // Attempt user-defined conversion.
John McCall5769d612010-02-08 23:07:23 +0000766 OverloadCandidateSet Conversions(From->getExprLoc());
767 OverloadingResult UserDefResult
John McCall120d63c2010-08-24 20:38:10 +0000768 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000769 AllowExplicit);
John McCall5769d612010-02-08 23:07:23 +0000770
771 if (UserDefResult == OR_Success) {
John McCall1d318332010-01-12 00:44:57 +0000772 ICS.setUserDefined();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000773 // C++ [over.ics.user]p4:
774 // A conversion of an expression of class type to the same class
775 // type is given Exact Match rank, and a conversion of an
776 // expression of class type to a base class of that type is
777 // given Conversion rank, in spite of the fact that a copy
778 // constructor (i.e., a user-defined conversion function) is
779 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000780 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000781 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000782 QualType FromCanon
John McCall120d63c2010-08-24 20:38:10 +0000783 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
784 QualType ToCanon
785 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor9e9199d2009-12-22 00:34:07 +0000786 if (Constructor->isCopyConstructor() &&
John McCall120d63c2010-08-24 20:38:10 +0000787 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000788 // Turn this into a "standard" conversion sequence, so that it
789 // gets ranked with standard conversion sequences.
John McCall1d318332010-01-12 00:44:57 +0000790 ICS.setStandard();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000791 ICS.Standard.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +0000792 ICS.Standard.setFromType(From->getType());
Douglas Gregorad323a82010-01-27 03:51:04 +0000793 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000794 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000795 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000796 ICS.Standard.Second = ICK_Derived_To_Base;
797 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000798 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000799
800 // C++ [over.best.ics]p4:
801 // However, when considering the argument of a user-defined
802 // conversion function that is a candidate by 13.3.1.3 when
803 // invoked for the copying of the temporary in the second step
804 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
805 // 13.3.1.6 in all cases, only standard conversion sequences and
806 // ellipsis conversion sequences are allowed.
John McCalladbb8f82010-01-13 09:16:55 +0000807 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCallb1bdc622010-02-25 01:37:24 +0000808 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCalladbb8f82010-01-13 09:16:55 +0000809 }
John McCallcefd3ad2010-01-13 22:30:33 +0000810 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall1d318332010-01-12 00:44:57 +0000811 ICS.setAmbiguous();
812 ICS.Ambiguous.setFromType(From->getType());
813 ICS.Ambiguous.setToType(ToType);
814 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
815 Cand != Conversions.end(); ++Cand)
816 if (Cand->Viable)
817 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000818 } else {
John McCallb1bdc622010-02-25 01:37:24 +0000819 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000820 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000821
822 return ICS;
823}
824
John McCall120d63c2010-08-24 20:38:10 +0000825bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
826 const InitializedEntity &Entity,
827 Expr *Initializer,
828 bool SuppressUserConversions,
829 bool AllowExplicitConversions,
830 bool InOverloadResolution) {
831 ImplicitConversionSequence ICS
832 = clang::TryImplicitConversion(*this, Initializer, Entity.getType(),
833 SuppressUserConversions,
834 AllowExplicitConversions,
835 InOverloadResolution);
836 if (ICS.isBad()) return true;
837
838 // Perform the actual conversion.
839 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
840 return false;
841}
842
Douglas Gregor575c63a2010-04-16 22:27:05 +0000843/// PerformImplicitConversion - Perform an implicit conversion of the
844/// expression From to the type ToType. Returns true if there was an
845/// error, false otherwise. The expression From is replaced with the
846/// converted expression. Flavor is the kind of conversion we're
847/// performing, used in the error message. If @p AllowExplicit,
848/// explicit user-defined conversions are permitted.
849bool
850Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
851 AssignmentAction Action, bool AllowExplicit) {
852 ImplicitConversionSequence ICS;
853 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
854}
855
856bool
857Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
858 AssignmentAction Action, bool AllowExplicit,
859 ImplicitConversionSequence& ICS) {
John McCall120d63c2010-08-24 20:38:10 +0000860 ICS = clang::TryImplicitConversion(*this, From, ToType,
861 /*SuppressUserConversions=*/false,
862 AllowExplicit,
863 /*InOverloadResolution=*/false);
Douglas Gregor575c63a2010-04-16 22:27:05 +0000864 return PerformImplicitConversion(From, ToType, ICS, Action);
865}
866
Douglas Gregor43c79c22009-12-09 00:47:37 +0000867/// \brief Determine whether the conversion from FromType to ToType is a valid
868/// conversion that strips "noreturn" off the nested function type.
869static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
870 QualType ToType, QualType &ResultTy) {
871 if (Context.hasSameUnqualifiedType(FromType, ToType))
872 return false;
873
874 // Strip the noreturn off the type we're converting from; noreturn can
875 // safely be removed.
876 FromType = Context.getNoReturnType(FromType, false);
877 if (!Context.hasSameUnqualifiedType(FromType, ToType))
878 return false;
879
880 ResultTy = FromType;
881 return true;
882}
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000883
884/// \brief Determine whether the conversion from FromType to ToType is a valid
885/// vector conversion.
886///
887/// \param ICK Will be set to the vector conversion kind, if this is a vector
888/// conversion.
889static bool IsVectorConversion(ASTContext &Context, QualType FromType,
890 QualType ToType, ImplicitConversionKind &ICK) {
891 // We need at least one of these types to be a vector type to have a vector
892 // conversion.
893 if (!ToType->isVectorType() && !FromType->isVectorType())
894 return false;
895
896 // Identical types require no conversions.
897 if (Context.hasSameUnqualifiedType(FromType, ToType))
898 return false;
899
900 // There are no conversions between extended vector types, only identity.
901 if (ToType->isExtVectorType()) {
902 // There are no conversions between extended vector types other than the
903 // identity conversion.
904 if (FromType->isExtVectorType())
905 return false;
906
907 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +0000908 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000909 ICK = ICK_Vector_Splat;
910 return true;
911 }
912 }
Douglas Gregor255210e2010-08-06 10:14:59 +0000913
914 // We can perform the conversion between vector types in the following cases:
915 // 1)vector types are equivalent AltiVec and GCC vector types
916 // 2)lax vector conversions are permitted and the vector types are of the
917 // same size
918 if (ToType->isVectorType() && FromType->isVectorType()) {
919 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruthc45eb9c2010-08-08 05:02:51 +0000920 (Context.getLangOptions().LaxVectorConversions &&
921 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +0000922 ICK = ICK_Vector_Conversion;
923 return true;
924 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000925 }
Douglas Gregor255210e2010-08-06 10:14:59 +0000926
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000927 return false;
928}
Douglas Gregor43c79c22009-12-09 00:47:37 +0000929
Douglas Gregor60d62c22008-10-31 16:23:19 +0000930/// IsStandardConversion - Determines whether there is a standard
931/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
932/// expression From to the type ToType. Standard conversion sequences
933/// only consider non-class types; for conversions that involve class
934/// types, use TryImplicitConversion. If a conversion exists, SCS will
935/// contain the standard conversion sequence required to perform this
936/// conversion and this routine will return true. Otherwise, this
937/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +0000938static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
939 bool InOverloadResolution,
940 StandardConversionSequence &SCS) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000941 QualType FromType = From->getType();
John McCall120d63c2010-08-24 20:38:10 +0000942
Douglas Gregor60d62c22008-10-31 16:23:19 +0000943 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000944 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +0000945 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000946 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +0000947 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000948 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000949
Douglas Gregorf9201e02009-02-11 23:02:49 +0000950 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +0000951 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +0000952 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall120d63c2010-08-24 20:38:10 +0000953 if (S.getLangOptions().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +0000954 return false;
955
Mike Stump1eb44332009-09-09 15:08:12 +0000956 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000957 }
958
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000959 // The first conversion can be an lvalue-to-rvalue conversion,
960 // array-to-pointer conversion, or function-to-pointer conversion
961 // (C++ 4p1).
962
John McCall120d63c2010-08-24 20:38:10 +0000963 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000964 DeclAccessPair AccessPair;
965 if (FunctionDecl *Fn
John McCall120d63c2010-08-24 20:38:10 +0000966 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
967 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000968 // We were able to resolve the address of the overloaded function,
969 // so we can convert to the type of that function.
970 FromType = Fn->getType();
971 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
972 if (!Method->isStatic()) {
973 Type *ClassType
John McCall120d63c2010-08-24 20:38:10 +0000974 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
975 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000976 }
977 }
978
979 // If the "from" expression takes the address of the overloaded
980 // function, update the type of the resulting expression accordingly.
981 if (FromType->getAs<FunctionType>())
982 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
John McCall2de56d12010-08-25 11:45:40 +0000983 if (UnOp->getOpcode() == UO_AddrOf)
John McCall120d63c2010-08-24 20:38:10 +0000984 FromType = S.Context.getPointerType(FromType);
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000985
986 // Check that we've computed the proper type after overload resolution.
John McCall120d63c2010-08-24 20:38:10 +0000987 assert(S.Context.hasSameType(FromType,
988 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000989 } else {
990 return false;
991 }
Anders Carlsson2bd62502010-11-04 05:28:09 +0000992 }
Mike Stump1eb44332009-09-09 15:08:12 +0000993 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000994 // An lvalue (3.10) of a non-function, non-array type T can be
995 // converted to an rvalue.
John McCall120d63c2010-08-24 20:38:10 +0000996 Expr::isLvalueResult argIsLvalue = From->isLvalue(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000997 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000998 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +0000999 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001000 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001001
1002 // If T is a non-class type, the type of the rvalue is the
1003 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001004 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1005 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001006 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001007 } else if (FromType->isArrayType()) {
1008 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001009 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001010
1011 // An lvalue or rvalue of type "array of N T" or "array of unknown
1012 // bound of T" can be converted to an rvalue of type "pointer to
1013 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001014 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001015
John McCall120d63c2010-08-24 20:38:10 +00001016 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001017 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001018 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001019
1020 // For the purpose of ranking in overload resolution
1021 // (13.3.3.1.1), this conversion is considered an
1022 // array-to-pointer conversion followed by a qualification
1023 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001024 SCS.Second = ICK_Identity;
1025 SCS.Third = ICK_Qualification;
Douglas Gregorad323a82010-01-27 03:51:04 +00001026 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001027 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001028 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001029 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
1030 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001031 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001032
1033 // An lvalue of function type T can be converted to an rvalue of
1034 // type "pointer to T." The result is a pointer to the
1035 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001036 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001037 } else {
1038 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001039 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001040 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001041 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001042
1043 // The second conversion can be an integral promotion, floating
1044 // point promotion, integral conversion, floating point conversion,
1045 // floating-integral conversion, pointer conversion,
1046 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001047 // For overloading in C, this can also be a "compatible-type"
1048 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001049 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001050 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001051 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001052 // The unqualified versions of the types are the same: there's no
1053 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001054 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001055 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001056 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001057 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001058 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001059 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001060 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001061 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001062 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001063 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001064 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001065 SCS.Second = ICK_Complex_Promotion;
1066 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001067 } else if (ToType->isBooleanType() &&
1068 (FromType->isArithmeticType() ||
1069 FromType->isAnyPointerType() ||
1070 FromType->isBlockPointerType() ||
1071 FromType->isMemberPointerType() ||
1072 FromType->isNullPtrType())) {
1073 // Boolean conversions (C++ 4.12).
1074 SCS.Second = ICK_Boolean_Conversion;
1075 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001076 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001077 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001078 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001079 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001080 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001081 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001082 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001083 SCS.Second = ICK_Complex_Conversion;
1084 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001085 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1086 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001087 // Complex-real conversions (C99 6.3.1.7)
1088 SCS.Second = ICK_Complex_Real;
1089 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001090 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001091 // Floating point conversions (C++ 4.8).
1092 SCS.Second = ICK_Floating_Conversion;
1093 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001094 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001095 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001096 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001097 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001098 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001099 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001100 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001101 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1102 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001103 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001104 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001105 SCS.IncompatibleObjC = IncompatibleObjC;
John McCall120d63c2010-08-24 20:38:10 +00001106 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1107 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001108 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001109 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001110 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001111 SCS.Second = SecondICK;
1112 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001113 } else if (!S.getLangOptions().CPlusPlus &&
1114 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001115 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001116 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001117 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001118 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001119 // Treat a conversion that strips "noreturn" as an identity conversion.
1120 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001121 } else {
1122 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001123 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001124 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001125 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001126
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001127 QualType CanonFrom;
1128 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001129 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall120d63c2010-08-24 20:38:10 +00001130 if (S.IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001131 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001132 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001133 CanonFrom = S.Context.getCanonicalType(FromType);
1134 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001135 } else {
1136 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001137 SCS.Third = ICK_Identity;
1138
Mike Stump1eb44332009-09-09 15:08:12 +00001139 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001140 // [...] Any difference in top-level cv-qualification is
1141 // subsumed by the initialization itself and does not constitute
1142 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001143 CanonFrom = S.Context.getCanonicalType(FromType);
1144 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00001145 if (CanonFrom.getLocalUnqualifiedType()
1146 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001147 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1148 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001149 FromType = ToType;
1150 CanonFrom = CanonTo;
1151 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001152 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001153 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001154
1155 // If we have not converted the argument type to the parameter type,
1156 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001157 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001158 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001159
Douglas Gregor60d62c22008-10-31 16:23:19 +00001160 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001161}
1162
1163/// IsIntegralPromotion - Determines whether the conversion from the
1164/// expression From (whose potentially-adjusted type is FromType) to
1165/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1166/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001167bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001168 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001169 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001170 if (!To) {
1171 return false;
1172 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001173
1174 // An rvalue of type char, signed char, unsigned char, short int, or
1175 // unsigned short int can be converted to an rvalue of type int if
1176 // int can represent all the values of the source type; otherwise,
1177 // the source rvalue can be converted to an rvalue of type unsigned
1178 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001179 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1180 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001181 if (// We can promote any signed, promotable integer type to an int
1182 (FromType->isSignedIntegerType() ||
1183 // We can promote any unsigned integer type whose size is
1184 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001185 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001186 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001187 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001188 }
1189
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001190 return To->getKind() == BuiltinType::UInt;
1191 }
1192
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001193 // C++0x [conv.prom]p3:
1194 // A prvalue of an unscoped enumeration type whose underlying type is not
1195 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1196 // following types that can represent all the values of the enumeration
1197 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1198 // unsigned int, long int, unsigned long int, long long int, or unsigned
1199 // long long int. If none of the types in that list can represent all the
1200 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1201 // type can be converted to an rvalue a prvalue of the extended integer type
1202 // with lowest integer conversion rank (4.13) greater than the rank of long
1203 // long in which all the values of the enumeration can be represented. If
1204 // there are two such extended types, the signed one is chosen.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001205 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1206 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1207 // provided for a scoped enumeration.
1208 if (FromEnumType->getDecl()->isScoped())
1209 return false;
1210
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001211 // We have already pre-calculated the promotion type, so this is trivial.
Douglas Gregor5dde1602010-09-12 03:38:25 +00001212 if (ToType->isIntegerType() &&
1213 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall842aef82009-12-09 09:09:27 +00001214 return Context.hasSameUnqualifiedType(ToType,
1215 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001216 }
John McCall842aef82009-12-09 09:09:27 +00001217
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001218 // C++0x [conv.prom]p2:
1219 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1220 // to an rvalue a prvalue of the first of the following types that can
1221 // represent all the values of its underlying type: int, unsigned int,
1222 // long int, unsigned long int, long long int, or unsigned long long int.
1223 // If none of the types in that list can represent all the values of its
1224 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
1225 // or wchar_t can be converted to an rvalue a prvalue of its underlying
1226 // type.
1227 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1228 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001229 // Determine whether the type we're converting from is signed or
1230 // unsigned.
1231 bool FromIsSigned;
1232 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall842aef82009-12-09 09:09:27 +00001233
1234 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1235 FromIsSigned = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001236
1237 // The types we'll try to promote to, in the appropriate
1238 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001239 QualType PromoteTypes[6] = {
1240 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001241 Context.LongTy, Context.UnsignedLongTy ,
1242 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001243 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001244 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001245 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1246 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001247 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001248 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1249 // We found the type that we can promote to. If this is the
1250 // type we wanted, we have a promotion. Otherwise, no
1251 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001252 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001253 }
1254 }
1255 }
1256
1257 // An rvalue for an integral bit-field (9.6) can be converted to an
1258 // rvalue of type int if int can represent all the values of the
1259 // bit-field; otherwise, it can be converted to unsigned int if
1260 // unsigned int can represent all the values of the bit-field. If
1261 // the bit-field is larger yet, no integral promotion applies to
1262 // it. If the bit-field has an enumerated type, it is treated as any
1263 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001264 // FIXME: We should delay checking of bit-fields until we actually perform the
1265 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001266 using llvm::APSInt;
1267 if (From)
1268 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001269 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001270 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001271 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1272 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1273 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001274
Douglas Gregor86f19402008-12-20 23:49:58 +00001275 // Are we promoting to an int from a bitfield that fits in an int?
1276 if (BitWidth < ToSize ||
1277 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1278 return To->getKind() == BuiltinType::Int;
1279 }
Mike Stump1eb44332009-09-09 15:08:12 +00001280
Douglas Gregor86f19402008-12-20 23:49:58 +00001281 // Are we promoting to an unsigned int from an unsigned bitfield
1282 // that fits into an unsigned int?
1283 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1284 return To->getKind() == BuiltinType::UInt;
1285 }
Mike Stump1eb44332009-09-09 15:08:12 +00001286
Douglas Gregor86f19402008-12-20 23:49:58 +00001287 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001288 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001289 }
Mike Stump1eb44332009-09-09 15:08:12 +00001290
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001291 // An rvalue of type bool can be converted to an rvalue of type int,
1292 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001293 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001294 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001295 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001296
1297 return false;
1298}
1299
1300/// IsFloatingPointPromotion - Determines whether the conversion from
1301/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1302/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001303bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001304 /// An rvalue of type float can be converted to an rvalue of type
1305 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +00001306 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1307 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001308 if (FromBuiltin->getKind() == BuiltinType::Float &&
1309 ToBuiltin->getKind() == BuiltinType::Double)
1310 return true;
1311
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001312 // C99 6.3.1.5p1:
1313 // When a float is promoted to double or long double, or a
1314 // double is promoted to long double [...].
1315 if (!getLangOptions().CPlusPlus &&
1316 (FromBuiltin->getKind() == BuiltinType::Float ||
1317 FromBuiltin->getKind() == BuiltinType::Double) &&
1318 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1319 return true;
1320 }
1321
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001322 return false;
1323}
1324
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001325/// \brief Determine if a conversion is a complex promotion.
1326///
1327/// A complex promotion is defined as a complex -> complex conversion
1328/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001329/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001330bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001331 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001332 if (!FromComplex)
1333 return false;
1334
John McCall183700f2009-09-21 23:43:11 +00001335 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001336 if (!ToComplex)
1337 return false;
1338
1339 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001340 ToComplex->getElementType()) ||
1341 IsIntegralPromotion(0, FromComplex->getElementType(),
1342 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001343}
1344
Douglas Gregorcb7de522008-11-26 23:31:11 +00001345/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1346/// the pointer type FromPtr to a pointer to type ToPointee, with the
1347/// same type qualifiers as FromPtr has on its pointee type. ToType,
1348/// if non-empty, will be a pointer to ToType that may or may not have
1349/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +00001350static QualType
1351BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001352 QualType ToPointee, QualType ToType,
1353 ASTContext &Context) {
1354 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1355 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001356 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001357
1358 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001359 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001360 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001361 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001362 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001363
1364 // Build a pointer to ToPointee. It has the right qualifiers
1365 // already.
1366 return Context.getPointerType(ToPointee);
1367 }
1368
1369 // Just build a canonical type that has the right qualifiers.
John McCall0953e762009-09-24 19:53:00 +00001370 return Context.getPointerType(
Douglas Gregora4923eb2009-11-16 21:35:15 +00001371 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1372 Quals));
Douglas Gregorcb7de522008-11-26 23:31:11 +00001373}
1374
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001375/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1376/// the FromType, which is an objective-c pointer, to ToType, which may or may
1377/// not have the right set of qualifiers.
1378static QualType
1379BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1380 QualType ToType,
1381 ASTContext &Context) {
1382 QualType CanonFromType = Context.getCanonicalType(FromType);
1383 QualType CanonToType = Context.getCanonicalType(ToType);
1384 Qualifiers Quals = CanonFromType.getQualifiers();
1385
1386 // Exact qualifier match -> return the pointer type we're converting to.
1387 if (CanonToType.getLocalQualifiers() == Quals)
1388 return ToType;
1389
1390 // Just build a canonical type that has the right qualifiers.
1391 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1392}
1393
Mike Stump1eb44332009-09-09 15:08:12 +00001394static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001395 bool InOverloadResolution,
1396 ASTContext &Context) {
1397 // Handle value-dependent integral null pointer constants correctly.
1398 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1399 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001400 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001401 return !InOverloadResolution;
1402
Douglas Gregorce940492009-09-25 04:25:58 +00001403 return Expr->isNullPointerConstant(Context,
1404 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1405 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001406}
Mike Stump1eb44332009-09-09 15:08:12 +00001407
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001408/// IsPointerConversion - Determines whether the conversion of the
1409/// expression From, which has the (possibly adjusted) type FromType,
1410/// can be converted to the type ToType via a pointer conversion (C++
1411/// 4.10). If so, returns true and places the converted type (that
1412/// might differ from ToType in its cv-qualifiers at some level) into
1413/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001414///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001415/// This routine also supports conversions to and from block pointers
1416/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1417/// pointers to interfaces. FIXME: Once we've determined the
1418/// appropriate overloading rules for Objective-C, we may want to
1419/// split the Objective-C checks into a different routine; however,
1420/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001421/// conversions, so for now they live here. IncompatibleObjC will be
1422/// set if the conversion is an allowed Objective-C conversion that
1423/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001424bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001425 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001426 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001427 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001428 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +00001429 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1430 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001431
Mike Stump1eb44332009-09-09 15:08:12 +00001432 // Conversion from a null pointer constant to any Objective-C pointer type.
1433 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001434 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001435 ConvertedType = ToType;
1436 return true;
1437 }
1438
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001439 // Blocks: Block pointers can be converted to void*.
1440 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001441 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001442 ConvertedType = ToType;
1443 return true;
1444 }
1445 // Blocks: A null pointer constant can be converted to a block
1446 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001447 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001448 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001449 ConvertedType = ToType;
1450 return true;
1451 }
1452
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001453 // If the left-hand-side is nullptr_t, the right side can be a null
1454 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001455 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001456 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001457 ConvertedType = ToType;
1458 return true;
1459 }
1460
Ted Kremenek6217b802009-07-29 21:53:49 +00001461 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001462 if (!ToTypePtr)
1463 return false;
1464
1465 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001466 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001467 ConvertedType = ToType;
1468 return true;
1469 }
Sebastian Redl07779722008-10-31 14:43:28 +00001470
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001471 // Beyond this point, both types need to be pointers
1472 // , including objective-c pointers.
1473 QualType ToPointeeType = ToTypePtr->getPointeeType();
1474 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1475 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1476 ToType, Context);
1477 return true;
1478
1479 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001480 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001481 if (!FromTypePtr)
1482 return false;
1483
1484 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001485
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00001486 // If the unqualified pointee types are the same, this can't be a
1487 // pointer conversion, so don't do all of the work below.
1488 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1489 return false;
1490
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001491 // An rvalue of type "pointer to cv T," where T is an object type,
1492 // can be converted to an rvalue of type "pointer to cv void" (C++
1493 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00001494 if (FromPointeeType->isIncompleteOrObjectType() &&
1495 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001496 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001497 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001498 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001499 return true;
1500 }
1501
Douglas Gregorf9201e02009-02-11 23:02:49 +00001502 // When we're overloading in C, we allow a special kind of pointer
1503 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001504 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001505 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001506 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001507 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001508 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001509 return true;
1510 }
1511
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001512 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001513 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001514 // An rvalue of type "pointer to cv D," where D is a class type,
1515 // can be converted to an rvalue of type "pointer to cv B," where
1516 // B is a base class (clause 10) of D. If B is an inaccessible
1517 // (clause 11) or ambiguous (10.2) base class of D, a program that
1518 // necessitates this conversion is ill-formed. The result of the
1519 // conversion is a pointer to the base class sub-object of the
1520 // derived class object. The null pointer value is converted to
1521 // the null pointer value of the destination type.
1522 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001523 // Note that we do not check for ambiguity or inaccessibility
1524 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001525 if (getLangOptions().CPlusPlus &&
1526 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001527 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001528 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001529 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001530 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001531 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001532 ToType, Context);
1533 return true;
1534 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001535
Douglas Gregorc7887512008-12-19 19:13:09 +00001536 return false;
1537}
1538
1539/// isObjCPointerConversion - Determines whether this is an
1540/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1541/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001542bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001543 QualType& ConvertedType,
1544 bool &IncompatibleObjC) {
1545 if (!getLangOptions().ObjC1)
1546 return false;
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001547
Steve Naroff14108da2009-07-10 23:34:53 +00001548 // First, we handle all conversions on ObjC object pointer types.
John McCall183700f2009-09-21 23:43:11 +00001549 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001550 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001551 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001552
Steve Naroff14108da2009-07-10 23:34:53 +00001553 if (ToObjCPtr && FromObjCPtr) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00001554 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001555 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001556 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001557 ConvertedType = ToType;
1558 return true;
1559 }
1560 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001561 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001562 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001563 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001564 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001565 ConvertedType = ToType;
1566 return true;
1567 }
1568 // Objective C++: We're able to convert from a pointer to an
1569 // interface to a pointer to a different interface.
1570 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00001571 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1572 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1573 if (getLangOptions().CPlusPlus && LHS && RHS &&
1574 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1575 FromObjCPtr->getPointeeType()))
1576 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00001577 ConvertedType = ToType;
1578 return true;
1579 }
1580
1581 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1582 // Okay: this is some kind of implicit downcast of Objective-C
1583 // interfaces, which is permitted. However, we're going to
1584 // complain about it.
1585 IncompatibleObjC = true;
1586 ConvertedType = FromType;
1587 return true;
1588 }
Mike Stump1eb44332009-09-09 15:08:12 +00001589 }
Steve Naroff14108da2009-07-10 23:34:53 +00001590 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001591 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001592 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001593 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001594 else if (const BlockPointerType *ToBlockPtr =
1595 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00001596 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001597 // to a block pointer type.
1598 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1599 ConvertedType = ToType;
1600 return true;
1601 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001602 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001603 }
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001604 else if (FromType->getAs<BlockPointerType>() &&
1605 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1606 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00001607 // pointer to any object.
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001608 ConvertedType = ToType;
1609 return true;
1610 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001611 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001612 return false;
1613
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001614 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001615 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001616 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001617 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001618 FromPointeeType = FromBlockPtr->getPointeeType();
1619 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001620 return false;
1621
Douglas Gregorc7887512008-12-19 19:13:09 +00001622 // If we have pointers to pointers, recursively check whether this
1623 // is an Objective-C conversion.
1624 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1625 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1626 IncompatibleObjC)) {
1627 // We always complain about this conversion.
1628 IncompatibleObjC = true;
1629 ConvertedType = ToType;
1630 return true;
1631 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001632 // Allow conversion of pointee being objective-c pointer to another one;
1633 // as in I* to id.
1634 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1635 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1636 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1637 IncompatibleObjC)) {
1638 ConvertedType = ToType;
1639 return true;
1640 }
1641
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001642 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001643 // differences in the argument and result types are in Objective-C
1644 // pointer conversions. If so, we permit the conversion (but
1645 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001646 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001647 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001648 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001649 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001650 if (FromFunctionType && ToFunctionType) {
1651 // If the function types are exactly the same, this isn't an
1652 // Objective-C pointer conversion.
1653 if (Context.getCanonicalType(FromPointeeType)
1654 == Context.getCanonicalType(ToPointeeType))
1655 return false;
1656
1657 // Perform the quick checks that will tell us whether these
1658 // function types are obviously different.
1659 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1660 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1661 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1662 return false;
1663
1664 bool HasObjCConversion = false;
1665 if (Context.getCanonicalType(FromFunctionType->getResultType())
1666 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1667 // Okay, the types match exactly. Nothing to do.
1668 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1669 ToFunctionType->getResultType(),
1670 ConvertedType, IncompatibleObjC)) {
1671 // Okay, we have an Objective-C pointer conversion.
1672 HasObjCConversion = true;
1673 } else {
1674 // Function types are too different. Abort.
1675 return false;
1676 }
Mike Stump1eb44332009-09-09 15:08:12 +00001677
Douglas Gregorc7887512008-12-19 19:13:09 +00001678 // Check argument types.
1679 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1680 ArgIdx != NumArgs; ++ArgIdx) {
1681 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1682 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1683 if (Context.getCanonicalType(FromArgType)
1684 == Context.getCanonicalType(ToArgType)) {
1685 // Okay, the types match exactly. Nothing to do.
1686 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1687 ConvertedType, IncompatibleObjC)) {
1688 // Okay, we have an Objective-C pointer conversion.
1689 HasObjCConversion = true;
1690 } else {
1691 // Argument types are too different. Abort.
1692 return false;
1693 }
1694 }
1695
1696 if (HasObjCConversion) {
1697 // We had an Objective-C conversion. Allow this pointer
1698 // conversion, but complain about it.
1699 ConvertedType = ToType;
1700 IncompatibleObjC = true;
1701 return true;
1702 }
1703 }
1704
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001705 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001706}
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001707
1708/// FunctionArgTypesAreEqual - This routine checks two function proto types
1709/// for equlity of their argument types. Caller has already checked that
1710/// they have same number of arguments. This routine assumes that Objective-C
1711/// pointer types which only differ in their protocol qualifiers are equal.
1712bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1713 FunctionProtoType* NewType){
1714 if (!getLangOptions().ObjC1)
1715 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1716 NewType->arg_type_begin());
1717
1718 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1719 N = NewType->arg_type_begin(),
1720 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1721 QualType ToType = (*O);
1722 QualType FromType = (*N);
1723 if (ToType != FromType) {
1724 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1725 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00001726 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1727 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1728 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1729 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001730 continue;
1731 }
John McCallc12c5bb2010-05-15 11:32:37 +00001732 else if (const ObjCObjectPointerType *PTTo =
1733 ToType->getAs<ObjCObjectPointerType>()) {
1734 if (const ObjCObjectPointerType *PTFr =
1735 FromType->getAs<ObjCObjectPointerType>())
1736 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1737 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001738 }
1739 return false;
1740 }
1741 }
1742 return true;
1743}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001744
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001745/// CheckPointerConversion - Check the pointer conversion from the
1746/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001747/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001748/// conversions for which IsPointerConversion has already returned
1749/// true. It returns true and produces a diagnostic if there was an
1750/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001751bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00001752 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001753 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001754 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001755 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00001756 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001757
John McCalldaa8e4e2010-11-15 09:13:47 +00001758 Kind = CK_BitCast;
1759
Douglas Gregord7a95972010-06-08 17:35:15 +00001760 if (CXXBoolLiteralExpr* LitBool
1761 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00001762 if (!IsCStyleOrFunctionalCast && LitBool->getValue() == false)
Douglas Gregord7a95972010-06-08 17:35:15 +00001763 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1764 << ToType;
1765
Ted Kremenek6217b802009-07-29 21:53:49 +00001766 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1767 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001768 QualType FromPointeeType = FromPtrType->getPointeeType(),
1769 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001770
Douglas Gregor5fccd362010-03-03 23:55:11 +00001771 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1772 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001773 // We must have a derived-to-base conversion. Check an
1774 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001775 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1776 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001777 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001778 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001779 return true;
1780
1781 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00001782 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001783 }
1784 }
Mike Stump1eb44332009-09-09 15:08:12 +00001785 if (const ObjCObjectPointerType *FromPtrType =
John McCalldaa8e4e2010-11-15 09:13:47 +00001786 FromType->getAs<ObjCObjectPointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001787 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00001788 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001789 // Objective-C++ conversions are always okay.
1790 // FIXME: We should have a different class of conversions for the
1791 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001792 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001793 return false;
John McCalldaa8e4e2010-11-15 09:13:47 +00001794 }
Steve Naroff14108da2009-07-10 23:34:53 +00001795 }
John McCalldaa8e4e2010-11-15 09:13:47 +00001796
1797 // We shouldn't fall into this case unless it's valid for other
1798 // reasons.
1799 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
1800 Kind = CK_NullToPointer;
1801
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001802 return false;
1803}
1804
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001805/// IsMemberPointerConversion - Determines whether the conversion of the
1806/// expression From, which has the (possibly adjusted) type FromType, can be
1807/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1808/// If so, returns true and places the converted type (that might differ from
1809/// ToType in its cv-qualifiers at some level) into ConvertedType.
1810bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregorce940492009-09-25 04:25:58 +00001811 QualType ToType,
1812 bool InOverloadResolution,
1813 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001814 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001815 if (!ToTypePtr)
1816 return false;
1817
1818 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00001819 if (From->isNullPointerConstant(Context,
1820 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1821 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001822 ConvertedType = ToType;
1823 return true;
1824 }
1825
1826 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001827 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001828 if (!FromTypePtr)
1829 return false;
1830
1831 // A pointer to member of B can be converted to a pointer to member of D,
1832 // where D is derived from B (C++ 4.11p2).
1833 QualType FromClass(FromTypePtr->getClass(), 0);
1834 QualType ToClass(ToTypePtr->getClass(), 0);
1835 // FIXME: What happens when these are dependent? Is this function even called?
1836
1837 if (IsDerivedFrom(ToClass, FromClass)) {
1838 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1839 ToClass.getTypePtr());
1840 return true;
1841 }
1842
1843 return false;
1844}
Douglas Gregor43c79c22009-12-09 00:47:37 +00001845
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001846/// CheckMemberPointerConversion - Check the member pointer conversion from the
1847/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00001848/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001849/// for which IsMemberPointerConversion has already returned true. It returns
1850/// true and produces a diagnostic if there was an error, or returns false
1851/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001852bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00001853 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001854 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001855 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001856 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001857 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001858 if (!FromPtrType) {
1859 // This must be a null pointer to member pointer conversion
Douglas Gregorce940492009-09-25 04:25:58 +00001860 assert(From->isNullPointerConstant(Context,
1861 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001862 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00001863 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001864 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001865 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001866
Ted Kremenek6217b802009-07-29 21:53:49 +00001867 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001868 assert(ToPtrType && "No member pointer cast has a target type "
1869 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001870
Sebastian Redl21593ac2009-01-28 18:33:18 +00001871 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1872 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001873
Sebastian Redl21593ac2009-01-28 18:33:18 +00001874 // FIXME: What about dependent types?
1875 assert(FromClass->isRecordType() && "Pointer into non-class.");
1876 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001877
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001878 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001879 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00001880 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1881 assert(DerivationOkay &&
1882 "Should not have been called if derivation isn't OK.");
1883 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001884
Sebastian Redl21593ac2009-01-28 18:33:18 +00001885 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1886 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001887 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1888 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1889 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1890 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001891 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001892
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001893 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001894 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1895 << FromClass << ToClass << QualType(VBase, 0)
1896 << From->getSourceRange();
1897 return true;
1898 }
1899
John McCall6b2accb2010-02-10 09:31:12 +00001900 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00001901 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1902 Paths.front(),
1903 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00001904
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001905 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001906 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00001907 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001908 return false;
1909}
1910
Douglas Gregor98cd5992008-10-21 23:43:52 +00001911/// IsQualificationConversion - Determines whether the conversion from
1912/// an rvalue of type FromType to ToType is a qualification conversion
1913/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001914bool
1915Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001916 FromType = Context.getCanonicalType(FromType);
1917 ToType = Context.getCanonicalType(ToType);
1918
1919 // If FromType and ToType are the same type, this is not a
1920 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00001921 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00001922 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001923
Douglas Gregor98cd5992008-10-21 23:43:52 +00001924 // (C++ 4.4p4):
1925 // A conversion can add cv-qualifiers at levels other than the first
1926 // in multi-level pointers, subject to the following rules: [...]
1927 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001928 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00001929 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001930 // Within each iteration of the loop, we check the qualifiers to
1931 // determine if this still looks like a qualification
1932 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001933 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001934 // until there are no more pointers or pointers-to-members left to
1935 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001936 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001937
1938 // -- for every j > 0, if const is in cv 1,j then const is in cv
1939 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001940 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001941 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001942
Douglas Gregor98cd5992008-10-21 23:43:52 +00001943 // -- if the cv 1,j and cv 2,j are different, then const is in
1944 // every cv for 0 < k < j.
1945 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001946 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001947 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001948
Douglas Gregor98cd5992008-10-21 23:43:52 +00001949 // Keep track of whether all prior cv-qualifiers in the "to" type
1950 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00001951 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00001952 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001953 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001954
1955 // We are left with FromType and ToType being the pointee types
1956 // after unwrapping the original FromType and ToType the same number
1957 // of types. If we unwrapped any pointers, and if FromType and
1958 // ToType have the same unqualified type (since we checked
1959 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001960 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00001961}
1962
Douglas Gregor734d9862009-01-30 23:27:23 +00001963/// Determines whether there is a user-defined conversion sequence
1964/// (C++ [over.ics.user]) that converts expression From to the type
1965/// ToType. If such a conversion exists, User will contain the
1966/// user-defined conversion sequence that performs such a conversion
1967/// and this routine will return true. Otherwise, this routine returns
1968/// false and User is unspecified.
1969///
Douglas Gregor734d9862009-01-30 23:27:23 +00001970/// \param AllowExplicit true if the conversion should consider C++0x
1971/// "explicit" conversion functions as well as non-explicit conversion
1972/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00001973static OverloadingResult
1974IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1975 UserDefinedConversionSequence& User,
1976 OverloadCandidateSet& CandidateSet,
1977 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001978 // Whether we will only visit constructors.
1979 bool ConstructorsOnly = false;
1980
1981 // If the type we are conversion to is a class type, enumerate its
1982 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00001983 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001984 // C++ [over.match.ctor]p1:
1985 // When objects of class type are direct-initialized (8.5), or
1986 // copy-initialized from an expression of the same or a
1987 // derived class type (8.5), overload resolution selects the
1988 // constructor. [...] For copy-initialization, the candidate
1989 // functions are all the converting constructors (12.3.1) of
1990 // that class. The argument list is the expression-list within
1991 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00001992 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001993 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00001994 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001995 ConstructorsOnly = true;
1996
John McCall120d63c2010-08-24 20:38:10 +00001997 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag())) {
Douglas Gregor393896f2009-11-05 13:06:35 +00001998 // We're not going to find any constructors.
1999 } else if (CXXRecordDecl *ToRecordDecl
2000 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002001 DeclContext::lookup_iterator Con, ConEnd;
John McCall120d63c2010-08-24 20:38:10 +00002002 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002003 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002004 NamedDecl *D = *Con;
2005 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2006
Douglas Gregordec06662009-08-21 18:42:58 +00002007 // Find the constructor (which may be a template).
2008 CXXConstructorDecl *Constructor = 0;
2009 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00002010 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00002011 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00002012 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00002013 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2014 else
John McCall9aa472c2010-03-19 07:35:19 +00002015 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor66724ea2009-11-14 01:20:54 +00002016
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00002017 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00002018 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00002019 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00002020 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2021 /*ExplicitArgs*/ 0,
2022 &From, 1, CandidateSet,
2023 /*SuppressUserConversions=*/
2024 !ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00002025 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00002026 // Allow one user-defined conversion when user specifies a
2027 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00002028 S.AddOverloadCandidate(Constructor, FoundDecl,
2029 &From, 1, CandidateSet,
2030 /*SuppressUserConversions=*/
2031 !ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00002032 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002033 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002034 }
2035 }
2036
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002037 // Enumerate conversion functions, if we're allowed to.
2038 if (ConstructorsOnly) {
John McCall120d63c2010-08-24 20:38:10 +00002039 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2040 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00002041 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00002042 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002043 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002044 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002045 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2046 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00002047 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002048 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002049 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00002050 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00002051 DeclAccessPair FoundDecl = I.getPair();
2052 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00002053 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2054 if (isa<UsingShadowDecl>(D))
2055 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2056
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002057 CXXConversionDecl *Conv;
2058 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00002059 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2060 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002061 else
John McCall32daa422010-03-31 01:36:47 +00002062 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002063
2064 if (AllowExplicit || !Conv->isExplicit()) {
2065 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00002066 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2067 ActingContext, From, ToType,
2068 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002069 else
John McCall120d63c2010-08-24 20:38:10 +00002070 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2071 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002072 }
2073 }
2074 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002075 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002076
2077 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002078 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00002079 case OR_Success:
2080 // Record the standard conversion we used and the conversion function.
2081 if (CXXConstructorDecl *Constructor
2082 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
2083 // C++ [over.ics.user]p1:
2084 // If the user-defined conversion is specified by a
2085 // constructor (12.3.1), the initial standard conversion
2086 // sequence converts the source type to the type required by
2087 // the argument of the constructor.
2088 //
2089 QualType ThisType = Constructor->getThisType(S.Context);
2090 if (Best->Conversions[0].isEllipsis())
2091 User.EllipsisConversion = true;
2092 else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002093 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002094 User.EllipsisConversion = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002095 }
John McCall120d63c2010-08-24 20:38:10 +00002096 User.ConversionFunction = Constructor;
2097 User.After.setAsIdentityConversion();
2098 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2099 User.After.setAllToTypes(ToType);
2100 return OR_Success;
2101 } else if (CXXConversionDecl *Conversion
2102 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2103 // C++ [over.ics.user]p1:
2104 //
2105 // [...] If the user-defined conversion is specified by a
2106 // conversion function (12.3.2), the initial standard
2107 // conversion sequence converts the source type to the
2108 // implicit object parameter of the conversion function.
2109 User.Before = Best->Conversions[0].Standard;
2110 User.ConversionFunction = Conversion;
2111 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002112
John McCall120d63c2010-08-24 20:38:10 +00002113 // C++ [over.ics.user]p2:
2114 // The second standard conversion sequence converts the
2115 // result of the user-defined conversion to the target type
2116 // for the sequence. Since an implicit conversion sequence
2117 // is an initialization, the special rules for
2118 // initialization by user-defined conversion apply when
2119 // selecting the best user-defined conversion for a
2120 // user-defined conversion sequence (see 13.3.3 and
2121 // 13.3.3.1).
2122 User.After = Best->FinalConversion;
2123 return OR_Success;
2124 } else {
2125 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002126 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002127 }
2128
John McCall120d63c2010-08-24 20:38:10 +00002129 case OR_No_Viable_Function:
2130 return OR_No_Viable_Function;
2131 case OR_Deleted:
2132 // No conversion here! We're done.
2133 return OR_Deleted;
2134
2135 case OR_Ambiguous:
2136 return OR_Ambiguous;
2137 }
2138
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002139 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002140}
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002141
2142bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002143Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002144 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00002145 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002146 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00002147 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002148 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002149 if (OvResult == OR_Ambiguous)
2150 Diag(From->getSourceRange().getBegin(),
2151 diag::err_typecheck_ambiguous_condition)
2152 << From->getType() << ToType << From->getSourceRange();
2153 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2154 Diag(From->getSourceRange().getBegin(),
2155 diag::err_typecheck_nonviable_condition)
2156 << From->getType() << ToType << From->getSourceRange();
2157 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002158 return false;
John McCall120d63c2010-08-24 20:38:10 +00002159 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002160 return true;
2161}
Douglas Gregor60d62c22008-10-31 16:23:19 +00002162
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002163/// CompareImplicitConversionSequences - Compare two implicit
2164/// conversion sequences to determine whether one is better than the
2165/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00002166static ImplicitConversionSequence::CompareKind
2167CompareImplicitConversionSequences(Sema &S,
2168 const ImplicitConversionSequence& ICS1,
2169 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002170{
2171 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2172 // conversion sequences (as defined in 13.3.3.1)
2173 // -- a standard conversion sequence (13.3.3.1.1) is a better
2174 // conversion sequence than a user-defined conversion sequence or
2175 // an ellipsis conversion sequence, and
2176 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2177 // conversion sequence than an ellipsis conversion sequence
2178 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002179 //
John McCall1d318332010-01-12 00:44:57 +00002180 // C++0x [over.best.ics]p10:
2181 // For the purpose of ranking implicit conversion sequences as
2182 // described in 13.3.3.2, the ambiguous conversion sequence is
2183 // treated as a user-defined sequence that is indistinguishable
2184 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002185 if (ICS1.getKindRank() < ICS2.getKindRank())
2186 return ImplicitConversionSequence::Better;
2187 else if (ICS2.getKindRank() < ICS1.getKindRank())
2188 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002189
Benjamin Kramerb6eee072010-04-18 12:05:54 +00002190 // The following checks require both conversion sequences to be of
2191 // the same kind.
2192 if (ICS1.getKind() != ICS2.getKind())
2193 return ImplicitConversionSequence::Indistinguishable;
2194
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002195 // Two implicit conversion sequences of the same form are
2196 // indistinguishable conversion sequences unless one of the
2197 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00002198 if (ICS1.isStandard())
John McCall120d63c2010-08-24 20:38:10 +00002199 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00002200 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002201 // User-defined conversion sequence U1 is a better conversion
2202 // sequence than another user-defined conversion sequence U2 if
2203 // they contain the same user-defined conversion function or
2204 // constructor and if the second standard conversion sequence of
2205 // U1 is better than the second standard conversion sequence of
2206 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002207 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002208 ICS2.UserDefined.ConversionFunction)
John McCall120d63c2010-08-24 20:38:10 +00002209 return CompareStandardConversionSequences(S,
2210 ICS1.UserDefined.After,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002211 ICS2.UserDefined.After);
2212 }
2213
2214 return ImplicitConversionSequence::Indistinguishable;
2215}
2216
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002217static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2218 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2219 Qualifiers Quals;
2220 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2221 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2222 }
2223
2224 return Context.hasSameUnqualifiedType(T1, T2);
2225}
2226
Douglas Gregorad323a82010-01-27 03:51:04 +00002227// Per 13.3.3.2p3, compare the given standard conversion sequences to
2228// determine if one is a proper subset of the other.
2229static ImplicitConversionSequence::CompareKind
2230compareStandardConversionSubsets(ASTContext &Context,
2231 const StandardConversionSequence& SCS1,
2232 const StandardConversionSequence& SCS2) {
2233 ImplicitConversionSequence::CompareKind Result
2234 = ImplicitConversionSequence::Indistinguishable;
2235
Douglas Gregorae65f4b2010-05-23 22:10:15 +00002236 // the identity conversion sequence is considered to be a subsequence of
2237 // any non-identity conversion sequence
2238 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2239 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2240 return ImplicitConversionSequence::Better;
2241 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2242 return ImplicitConversionSequence::Worse;
2243 }
2244
Douglas Gregorad323a82010-01-27 03:51:04 +00002245 if (SCS1.Second != SCS2.Second) {
2246 if (SCS1.Second == ICK_Identity)
2247 Result = ImplicitConversionSequence::Better;
2248 else if (SCS2.Second == ICK_Identity)
2249 Result = ImplicitConversionSequence::Worse;
2250 else
2251 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002252 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00002253 return ImplicitConversionSequence::Indistinguishable;
2254
2255 if (SCS1.Third == SCS2.Third) {
2256 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2257 : ImplicitConversionSequence::Indistinguishable;
2258 }
2259
2260 if (SCS1.Third == ICK_Identity)
2261 return Result == ImplicitConversionSequence::Worse
2262 ? ImplicitConversionSequence::Indistinguishable
2263 : ImplicitConversionSequence::Better;
2264
2265 if (SCS2.Third == ICK_Identity)
2266 return Result == ImplicitConversionSequence::Better
2267 ? ImplicitConversionSequence::Indistinguishable
2268 : ImplicitConversionSequence::Worse;
2269
2270 return ImplicitConversionSequence::Indistinguishable;
2271}
2272
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002273/// CompareStandardConversionSequences - Compare two standard
2274/// conversion sequences to determine whether one is better than the
2275/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00002276static ImplicitConversionSequence::CompareKind
2277CompareStandardConversionSequences(Sema &S,
2278 const StandardConversionSequence& SCS1,
2279 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002280{
2281 // Standard conversion sequence S1 is a better conversion sequence
2282 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2283
2284 // -- S1 is a proper subsequence of S2 (comparing the conversion
2285 // sequences in the canonical form defined by 13.3.3.1.1,
2286 // excluding any Lvalue Transformation; the identity conversion
2287 // sequence is considered to be a subsequence of any
2288 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00002289 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00002290 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00002291 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002292
2293 // -- the rank of S1 is better than the rank of S2 (by the rules
2294 // defined below), or, if not that,
2295 ImplicitConversionRank Rank1 = SCS1.getRank();
2296 ImplicitConversionRank Rank2 = SCS2.getRank();
2297 if (Rank1 < Rank2)
2298 return ImplicitConversionSequence::Better;
2299 else if (Rank2 < Rank1)
2300 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002301
Douglas Gregor57373262008-10-22 14:17:15 +00002302 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2303 // are indistinguishable unless one of the following rules
2304 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00002305
Douglas Gregor57373262008-10-22 14:17:15 +00002306 // A conversion that is not a conversion of a pointer, or
2307 // pointer to member, to bool is better than another conversion
2308 // that is such a conversion.
2309 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2310 return SCS2.isPointerConversionToBool()
2311 ? ImplicitConversionSequence::Better
2312 : ImplicitConversionSequence::Worse;
2313
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002314 // C++ [over.ics.rank]p4b2:
2315 //
2316 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002317 // conversion of B* to A* is better than conversion of B* to
2318 // void*, and conversion of A* to void* is better than conversion
2319 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00002320 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00002321 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002322 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00002323 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002324 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2325 // Exactly one of the conversion sequences is a conversion to
2326 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002327 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2328 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002329 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2330 // Neither conversion sequence converts to a void pointer; compare
2331 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002332 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00002333 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002334 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002335 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2336 // Both conversion sequences are conversions to void
2337 // pointers. Compare the source types to determine if there's an
2338 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00002339 QualType FromType1 = SCS1.getFromType();
2340 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002341
2342 // Adjust the types we're converting from via the array-to-pointer
2343 // conversion, if we need to.
2344 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002345 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002346 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002347 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002348
Douglas Gregor01919692009-12-13 21:37:05 +00002349 QualType FromPointee1
2350 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2351 QualType FromPointee2
2352 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002353
John McCall120d63c2010-08-24 20:38:10 +00002354 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00002355 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002356 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00002357 return ImplicitConversionSequence::Worse;
2358
2359 // Objective-C++: If one interface is more specific than the
2360 // other, it is the better one.
John McCallc12c5bb2010-05-15 11:32:37 +00002361 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2362 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor01919692009-12-13 21:37:05 +00002363 if (FromIface1 && FromIface1) {
John McCall120d63c2010-08-24 20:38:10 +00002364 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor01919692009-12-13 21:37:05 +00002365 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002366 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor01919692009-12-13 21:37:05 +00002367 return ImplicitConversionSequence::Worse;
2368 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002369 }
Douglas Gregor57373262008-10-22 14:17:15 +00002370
2371 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2372 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00002373 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00002374 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002375 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00002376
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002377 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002378 // C++0x [over.ics.rank]p3b4:
2379 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2380 // implicit object parameter of a non-static member function declared
2381 // without a ref-qualifier, and S1 binds an rvalue reference to an
2382 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00002383 // FIXME: We don't know if we're dealing with the implicit object parameter,
2384 // or if the member function in this case has a ref qualifier.
2385 // (Of course, we don't have ref qualifiers yet.)
2386 if (SCS1.RRefBinding != SCS2.RRefBinding)
2387 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2388 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002389
2390 // C++ [over.ics.rank]p3b4:
2391 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2392 // which the references refer are the same type except for
2393 // top-level cv-qualifiers, and the type to which the reference
2394 // initialized by S2 refers is more cv-qualified than the type
2395 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00002396 QualType T1 = SCS1.getToType(2);
2397 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00002398 T1 = S.Context.getCanonicalType(T1);
2399 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002400 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00002401 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2402 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002403 if (UnqualT1 == UnqualT2) {
2404 // If the type is an array type, promote the element qualifiers to the type
2405 // for comparison.
2406 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00002407 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002408 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00002409 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002410 if (T2.isMoreQualifiedThan(T1))
2411 return ImplicitConversionSequence::Better;
2412 else if (T1.isMoreQualifiedThan(T2))
2413 return ImplicitConversionSequence::Worse;
2414 }
2415 }
Douglas Gregor57373262008-10-22 14:17:15 +00002416
2417 return ImplicitConversionSequence::Indistinguishable;
2418}
2419
2420/// CompareQualificationConversions - Compares two standard conversion
2421/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00002422/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2423ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00002424CompareQualificationConversions(Sema &S,
2425 const StandardConversionSequence& SCS1,
2426 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00002427 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00002428 // -- S1 and S2 differ only in their qualification conversion and
2429 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2430 // cv-qualification signature of type T1 is a proper subset of
2431 // the cv-qualification signature of type T2, and S1 is not the
2432 // deprecated string literal array-to-pointer conversion (4.2).
2433 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2434 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2435 return ImplicitConversionSequence::Indistinguishable;
2436
2437 // FIXME: the example in the standard doesn't use a qualification
2438 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00002439 QualType T1 = SCS1.getToType(2);
2440 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00002441 T1 = S.Context.getCanonicalType(T1);
2442 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002443 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00002444 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2445 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00002446
2447 // If the types are the same, we won't learn anything by unwrapped
2448 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00002449 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00002450 return ImplicitConversionSequence::Indistinguishable;
2451
Chandler Carruth28e318c2009-12-29 07:16:59 +00002452 // If the type is an array type, promote the element qualifiers to the type
2453 // for comparison.
2454 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00002455 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002456 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00002457 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002458
Mike Stump1eb44332009-09-09 15:08:12 +00002459 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00002460 = ImplicitConversionSequence::Indistinguishable;
John McCall120d63c2010-08-24 20:38:10 +00002461 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00002462 // Within each iteration of the loop, we check the qualifiers to
2463 // determine if this still looks like a qualification
2464 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002465 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00002466 // until there are no more pointers or pointers-to-members left
2467 // to unwrap. This essentially mimics what
2468 // IsQualificationConversion does, but here we're checking for a
2469 // strict subset of qualifiers.
2470 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2471 // The qualifiers are the same, so this doesn't tell us anything
2472 // about how the sequences rank.
2473 ;
2474 else if (T2.isMoreQualifiedThan(T1)) {
2475 // T1 has fewer qualifiers, so it could be the better sequence.
2476 if (Result == ImplicitConversionSequence::Worse)
2477 // Neither has qualifiers that are a subset of the other's
2478 // qualifiers.
2479 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002480
Douglas Gregor57373262008-10-22 14:17:15 +00002481 Result = ImplicitConversionSequence::Better;
2482 } else if (T1.isMoreQualifiedThan(T2)) {
2483 // T2 has fewer qualifiers, so it could be the better sequence.
2484 if (Result == ImplicitConversionSequence::Better)
2485 // Neither has qualifiers that are a subset of the other's
2486 // qualifiers.
2487 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002488
Douglas Gregor57373262008-10-22 14:17:15 +00002489 Result = ImplicitConversionSequence::Worse;
2490 } else {
2491 // Qualifiers are disjoint.
2492 return ImplicitConversionSequence::Indistinguishable;
2493 }
2494
2495 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00002496 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00002497 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002498 }
2499
Douglas Gregor57373262008-10-22 14:17:15 +00002500 // Check that the winning standard conversion sequence isn't using
2501 // the deprecated string literal array to pointer conversion.
2502 switch (Result) {
2503 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00002504 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002505 Result = ImplicitConversionSequence::Indistinguishable;
2506 break;
2507
2508 case ImplicitConversionSequence::Indistinguishable:
2509 break;
2510
2511 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00002512 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002513 Result = ImplicitConversionSequence::Indistinguishable;
2514 break;
2515 }
2516
2517 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002518}
2519
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002520/// CompareDerivedToBaseConversions - Compares two standard conversion
2521/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00002522/// various kinds of derived-to-base conversions (C++
2523/// [over.ics.rank]p4b3). As part of these checks, we also look at
2524/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002525ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00002526CompareDerivedToBaseConversions(Sema &S,
2527 const StandardConversionSequence& SCS1,
2528 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00002529 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002530 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00002531 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002532 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002533
2534 // Adjust the types we're converting from via the array-to-pointer
2535 // conversion, if we need to.
2536 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002537 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002538 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002539 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002540
2541 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00002542 FromType1 = S.Context.getCanonicalType(FromType1);
2543 ToType1 = S.Context.getCanonicalType(ToType1);
2544 FromType2 = S.Context.getCanonicalType(FromType2);
2545 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002546
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002547 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002548 //
2549 // If class B is derived directly or indirectly from class A and
2550 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002551 //
2552 // For Objective-C, we let A, B, and C also be Objective-C
2553 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002554
2555 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00002556 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00002557 SCS2.Second == ICK_Pointer_Conversion &&
2558 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2559 FromType1->isPointerType() && FromType2->isPointerType() &&
2560 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002561 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002562 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002563 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002564 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002565 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002566 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002567 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002568 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002569
John McCallc12c5bb2010-05-15 11:32:37 +00002570 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2571 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2572 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2573 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002574
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002575 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002576 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002577 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002578 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002579 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002580 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00002581
2582 if (ToIface1 && ToIface2) {
John McCall120d63c2010-08-24 20:38:10 +00002583 if (S.Context.canAssignObjCInterfaces(ToIface2, ToIface1))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002584 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002585 else if (S.Context.canAssignObjCInterfaces(ToIface1, ToIface2))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002586 return ImplicitConversionSequence::Worse;
2587 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002588 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002589
2590 // -- conversion of B* to A* is better than conversion of C* to A*,
2591 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002592 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002593 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002594 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002595 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00002596
Douglas Gregorcb7de522008-11-26 23:31:11 +00002597 if (FromIface1 && FromIface2) {
John McCall120d63c2010-08-24 20:38:10 +00002598 if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002599 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002600 else if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregorcb7de522008-11-26 23:31:11 +00002601 return ImplicitConversionSequence::Worse;
2602 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002603 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002604 }
2605
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002606 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002607 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2608 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2609 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2610 const MemberPointerType * FromMemPointer1 =
2611 FromType1->getAs<MemberPointerType>();
2612 const MemberPointerType * ToMemPointer1 =
2613 ToType1->getAs<MemberPointerType>();
2614 const MemberPointerType * FromMemPointer2 =
2615 FromType2->getAs<MemberPointerType>();
2616 const MemberPointerType * ToMemPointer2 =
2617 ToType2->getAs<MemberPointerType>();
2618 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2619 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2620 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2621 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2622 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2623 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2624 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2625 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002626 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002627 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002628 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002629 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00002630 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002631 return ImplicitConversionSequence::Better;
2632 }
2633 // conversion of B::* to C::* is better than conversion of A::* to C::*
2634 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00002635 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002636 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002637 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002638 return ImplicitConversionSequence::Worse;
2639 }
2640 }
2641
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002642 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002643 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00002644 // -- binding of an expression of type C to a reference of type
2645 // B& is better than binding an expression of type C to a
2646 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00002647 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2648 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2649 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002650 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002651 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002652 return ImplicitConversionSequence::Worse;
2653 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002654
Douglas Gregor225c41e2008-11-03 19:09:14 +00002655 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00002656 // -- binding of an expression of type B to a reference of type
2657 // A& is better than binding an expression of type C to a
2658 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00002659 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2660 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2661 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002662 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002663 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00002664 return ImplicitConversionSequence::Worse;
2665 }
2666 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002667
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002668 return ImplicitConversionSequence::Indistinguishable;
2669}
2670
Douglas Gregorabe183d2010-04-13 16:31:36 +00002671/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2672/// determine whether they are reference-related,
2673/// reference-compatible, reference-compatible with added
2674/// qualification, or incompatible, for use in C++ initialization by
2675/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2676/// type, and the first type (T1) is the pointee type of the reference
2677/// type being initialized.
2678Sema::ReferenceCompareResult
2679Sema::CompareReferenceRelationship(SourceLocation Loc,
2680 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00002681 bool &DerivedToBase,
2682 bool &ObjCConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002683 assert(!OrigT1->isReferenceType() &&
2684 "T1 must be the pointee type of the reference type");
2685 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2686
2687 QualType T1 = Context.getCanonicalType(OrigT1);
2688 QualType T2 = Context.getCanonicalType(OrigT2);
2689 Qualifiers T1Quals, T2Quals;
2690 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2691 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2692
2693 // C++ [dcl.init.ref]p4:
2694 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2695 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2696 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00002697 DerivedToBase = false;
2698 ObjCConversion = false;
2699 if (UnqualT1 == UnqualT2) {
2700 // Nothing to do.
2701 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00002702 IsDerivedFrom(UnqualT2, UnqualT1))
2703 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00002704 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2705 UnqualT2->isObjCObjectOrInterfaceType() &&
2706 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2707 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002708 else
2709 return Ref_Incompatible;
2710
2711 // At this point, we know that T1 and T2 are reference-related (at
2712 // least).
2713
2714 // If the type is an array type, promote the element qualifiers to the type
2715 // for comparison.
2716 if (isa<ArrayType>(T1) && T1Quals)
2717 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2718 if (isa<ArrayType>(T2) && T2Quals)
2719 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2720
2721 // C++ [dcl.init.ref]p4:
2722 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2723 // reference-related to T2 and cv1 is the same cv-qualification
2724 // as, or greater cv-qualification than, cv2. For purposes of
2725 // overload resolution, cases for which cv1 is greater
2726 // cv-qualification than cv2 are identified as
2727 // reference-compatible with added qualification (see 13.3.3.2).
2728 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2729 return Ref_Compatible;
2730 else if (T1.isMoreQualifiedThan(T2))
2731 return Ref_Compatible_With_Added_Qualification;
2732 else
2733 return Ref_Related;
2734}
2735
Douglas Gregor604eb652010-08-11 02:15:33 +00002736/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00002737/// with DeclType. Return true if something definite is found.
2738static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00002739FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2740 QualType DeclType, SourceLocation DeclLoc,
2741 Expr *Init, QualType T2, bool AllowRvalues,
2742 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00002743 assert(T2->isRecordType() && "Can only find conversions of record types.");
2744 CXXRecordDecl *T2RecordDecl
2745 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2746
Douglas Gregor604eb652010-08-11 02:15:33 +00002747 QualType ToType
2748 = AllowRvalues? DeclType->getAs<ReferenceType>()->getPointeeType()
2749 : DeclType;
2750
Sebastian Redl4680bf22010-06-30 18:13:39 +00002751 OverloadCandidateSet CandidateSet(DeclLoc);
2752 const UnresolvedSetImpl *Conversions
2753 = T2RecordDecl->getVisibleConversionFunctions();
2754 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2755 E = Conversions->end(); I != E; ++I) {
2756 NamedDecl *D = *I;
2757 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2758 if (isa<UsingShadowDecl>(D))
2759 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2760
2761 FunctionTemplateDecl *ConvTemplate
2762 = dyn_cast<FunctionTemplateDecl>(D);
2763 CXXConversionDecl *Conv;
2764 if (ConvTemplate)
2765 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2766 else
2767 Conv = cast<CXXConversionDecl>(D);
2768
Douglas Gregor604eb652010-08-11 02:15:33 +00002769 // If this is an explicit conversion, and we're not allowed to consider
2770 // explicit conversions, skip it.
2771 if (!AllowExplicit && Conv->isExplicit())
2772 continue;
2773
2774 if (AllowRvalues) {
2775 bool DerivedToBase = false;
2776 bool ObjCConversion = false;
2777 if (!ConvTemplate &&
2778 S.CompareReferenceRelationship(DeclLoc,
2779 Conv->getConversionType().getNonReferenceType().getUnqualifiedType(),
2780 DeclType.getNonReferenceType().getUnqualifiedType(),
2781 DerivedToBase, ObjCConversion)
2782 == Sema::Ref_Incompatible)
2783 continue;
2784 } else {
2785 // If the conversion function doesn't return a reference type,
2786 // it can't be considered for this conversion. An rvalue reference
2787 // is only acceptable if its referencee is a function type.
2788
2789 const ReferenceType *RefType =
2790 Conv->getConversionType()->getAs<ReferenceType>();
2791 if (!RefType ||
2792 (!RefType->isLValueReferenceType() &&
2793 !RefType->getPointeeType()->isFunctionType()))
2794 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002795 }
Douglas Gregor604eb652010-08-11 02:15:33 +00002796
2797 if (ConvTemplate)
2798 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2799 Init, ToType, CandidateSet);
2800 else
2801 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2802 ToType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002803 }
2804
2805 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002806 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00002807 case OR_Success:
2808 // C++ [over.ics.ref]p1:
2809 //
2810 // [...] If the parameter binds directly to the result of
2811 // applying a conversion function to the argument
2812 // expression, the implicit conversion sequence is a
2813 // user-defined conversion sequence (13.3.3.1.2), with the
2814 // second standard conversion sequence either an identity
2815 // conversion or, if the conversion function returns an
2816 // entity of a type that is a derived class of the parameter
2817 // type, a derived-to-base Conversion.
2818 if (!Best->FinalConversion.DirectBinding)
2819 return false;
2820
2821 ICS.setUserDefined();
2822 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2823 ICS.UserDefined.After = Best->FinalConversion;
2824 ICS.UserDefined.ConversionFunction = Best->Function;
2825 ICS.UserDefined.EllipsisConversion = false;
2826 assert(ICS.UserDefined.After.ReferenceBinding &&
2827 ICS.UserDefined.After.DirectBinding &&
2828 "Expected a direct reference binding!");
2829 return true;
2830
2831 case OR_Ambiguous:
2832 ICS.setAmbiguous();
2833 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2834 Cand != CandidateSet.end(); ++Cand)
2835 if (Cand->Viable)
2836 ICS.Ambiguous.addConversion(Cand->Function);
2837 return true;
2838
2839 case OR_No_Viable_Function:
2840 case OR_Deleted:
2841 // There was no suitable conversion, or we found a deleted
2842 // conversion; continue with other checks.
2843 return false;
2844 }
Eric Christopher1c3d5022010-06-30 18:36:32 +00002845
2846 return false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002847}
2848
Douglas Gregorabe183d2010-04-13 16:31:36 +00002849/// \brief Compute an implicit conversion sequence for reference
2850/// initialization.
2851static ImplicitConversionSequence
2852TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2853 SourceLocation DeclLoc,
2854 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00002855 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002856 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2857
2858 // Most paths end in a failed conversion.
2859 ImplicitConversionSequence ICS;
2860 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2861
2862 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2863 QualType T2 = Init->getType();
2864
2865 // If the initializer is the address of an overloaded function, try
2866 // to resolve the overloaded function. If all goes well, T2 is the
2867 // type of the resulting function.
2868 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2869 DeclAccessPair Found;
2870 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2871 false, Found))
2872 T2 = Fn->getType();
2873 }
2874
2875 // Compute some basic properties of the types and the initializer.
2876 bool isRValRef = DeclType->isRValueReferenceType();
2877 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002878 bool ObjCConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002879 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002880 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00002881 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
2882 ObjCConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002883
Douglas Gregorabe183d2010-04-13 16:31:36 +00002884
Sebastian Redl4680bf22010-06-30 18:13:39 +00002885 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00002886 // A reference to type "cv1 T1" is initialized by an expression
2887 // of type "cv2 T2" as follows:
2888
Sebastian Redl4680bf22010-06-30 18:13:39 +00002889 // -- If reference is an lvalue reference and the initializer expression
2890 // The next bullet point (T1 is a function) is pretty much equivalent to this
2891 // one, so it's handled here.
2892 if (!isRValRef || T1->isFunctionType()) {
2893 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2894 // reference-compatible with "cv2 T2," or
2895 //
2896 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2897 if (InitCategory.isLValue() &&
2898 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002899 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00002900 // When a parameter of reference type binds directly (8.5.3)
2901 // to an argument expression, the implicit conversion sequence
2902 // is the identity conversion, unless the argument expression
2903 // has a type that is a derived class of the parameter type,
2904 // in which case the implicit conversion sequence is a
2905 // derived-to-base Conversion (13.3.3.1).
2906 ICS.setStandard();
2907 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00002908 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2909 : ObjCConversion? ICK_Compatible_Conversion
2910 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002911 ICS.Standard.Third = ICK_Identity;
2912 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2913 ICS.Standard.setToType(0, T2);
2914 ICS.Standard.setToType(1, T1);
2915 ICS.Standard.setToType(2, T1);
2916 ICS.Standard.ReferenceBinding = true;
2917 ICS.Standard.DirectBinding = true;
2918 ICS.Standard.RRefBinding = isRValRef;
2919 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002920
Sebastian Redl4680bf22010-06-30 18:13:39 +00002921 // Nothing more to do: the inaccessibility/ambiguity check for
2922 // derived-to-base conversions is suppressed when we're
2923 // computing the implicit conversion sequence (C++
2924 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00002925 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002926 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00002927
Sebastian Redl4680bf22010-06-30 18:13:39 +00002928 // -- has a class type (i.e., T2 is a class type), where T1 is
2929 // not reference-related to T2, and can be implicitly
2930 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2931 // is reference-compatible with "cv3 T3" 92) (this
2932 // conversion is selected by enumerating the applicable
2933 // conversion functions (13.3.1.6) and choosing the best
2934 // one through overload resolution (13.3)),
2935 if (!SuppressUserConversions && T2->isRecordType() &&
2936 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2937 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00002938 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2939 Init, T2, /*AllowRvalues=*/false,
2940 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00002941 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002942 }
2943 }
2944
Sebastian Redl4680bf22010-06-30 18:13:39 +00002945 // -- Otherwise, the reference shall be an lvalue reference to a
2946 // non-volatile const type (i.e., cv1 shall be const), or the reference
2947 // shall be an rvalue reference and the initializer expression shall be
2948 // an rvalue or have a function type.
Douglas Gregor66821b52010-04-18 09:22:00 +00002949 //
2950 // We actually handle one oddity of C++ [over.ics.ref] at this
2951 // point, which is that, due to p2 (which short-circuits reference
2952 // binding by only attempting a simple conversion for non-direct
2953 // bindings) and p3's strange wording, we allow a const volatile
2954 // reference to bind to an rvalue. Hence the check for the presence
2955 // of "const" rather than checking for "const" being the only
2956 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00002957 // This is also the point where rvalue references and lvalue inits no longer
2958 // go together.
2959 if ((!isRValRef && !T1.isConstQualified()) ||
2960 (isRValRef && InitCategory.isLValue()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00002961 return ICS;
2962
Sebastian Redl4680bf22010-06-30 18:13:39 +00002963 // -- If T1 is a function type, then
2964 // -- if T2 is the same type as T1, the reference is bound to the
2965 // initializer expression lvalue;
2966 // -- if T2 is a class type and the initializer expression can be
2967 // implicitly converted to an lvalue of type T1 [...], the
2968 // reference is bound to the function lvalue that is the result
2969 // of the conversion;
2970 // This is the same as for the lvalue case above, so it was handled there.
2971 // -- otherwise, the program is ill-formed.
2972 // This is the one difference to the lvalue case.
2973 if (T1->isFunctionType())
2974 return ICS;
2975
2976 // -- Otherwise, if T2 is a class type and
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002977 // -- the initializer expression is an rvalue and "cv1 T1"
2978 // is reference-compatible with "cv2 T2," or
Douglas Gregorabe183d2010-04-13 16:31:36 +00002979 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002980 // -- T1 is not reference-related to T2 and the initializer
2981 // expression can be implicitly converted to an rvalue
2982 // of type "cv3 T3" (this conversion is selected by
2983 // enumerating the applicable conversion functions
2984 // (13.3.1.6) and choosing the best one through overload
2985 // resolution (13.3)),
Douglas Gregorabe183d2010-04-13 16:31:36 +00002986 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002987 // then the reference is bound to the initializer
2988 // expression rvalue in the first case and to the object
2989 // that is the result of the conversion in the second case
2990 // (or, in either case, to the appropriate base class
2991 // subobject of the object).
Douglas Gregor604eb652010-08-11 02:15:33 +00002992 if (T2->isRecordType()) {
2993 // First case: "cv1 T1" is reference-compatible with "cv2 T2". This is a
2994 // direct binding in C++0x but not in C++03.
2995 if (InitCategory.isRValue() &&
2996 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2997 ICS.setStandard();
2998 ICS.Standard.First = ICK_Identity;
2999 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3000 : ObjCConversion? ICK_Compatible_Conversion
3001 : ICK_Identity;
3002 ICS.Standard.Third = ICK_Identity;
3003 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3004 ICS.Standard.setToType(0, T2);
3005 ICS.Standard.setToType(1, T1);
3006 ICS.Standard.setToType(2, T1);
3007 ICS.Standard.ReferenceBinding = true;
3008 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
3009 ICS.Standard.RRefBinding = isRValRef;
3010 ICS.Standard.CopyConstructor = 0;
3011 return ICS;
3012 }
3013
3014 // Second case: not reference-related.
3015 if (RefRelationship == Sema::Ref_Incompatible &&
3016 !S.RequireCompleteType(DeclLoc, T2, 0) &&
3017 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3018 Init, T2, /*AllowRvalues=*/true,
3019 AllowExplicit))
3020 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003021 }
Douglas Gregor604eb652010-08-11 02:15:33 +00003022
Douglas Gregorabe183d2010-04-13 16:31:36 +00003023 // -- Otherwise, a temporary of type "cv1 T1" is created and
3024 // initialized from the initializer expression using the
3025 // rules for a non-reference copy initialization (8.5). The
3026 // reference is then bound to the temporary. If T1 is
3027 // reference-related to T2, cv1 must be the same
3028 // cv-qualification as, or greater cv-qualification than,
3029 // cv2; otherwise, the program is ill-formed.
3030 if (RefRelationship == Sema::Ref_Related) {
3031 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3032 // we would be reference-compatible or reference-compatible with
3033 // added qualification. But that wasn't the case, so the reference
3034 // initialization fails.
3035 return ICS;
3036 }
3037
3038 // If at least one of the types is a class type, the types are not
3039 // related, and we aren't allowed any user conversions, the
3040 // reference binding fails. This case is important for breaking
3041 // recursion, since TryImplicitConversion below will attempt to
3042 // create a temporary through the use of a copy constructor.
3043 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3044 (T1->isRecordType() || T2->isRecordType()))
3045 return ICS;
3046
3047 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00003048 // When a parameter of reference type is not bound directly to
3049 // an argument expression, the conversion sequence is the one
3050 // required to convert the argument expression to the
3051 // underlying type of the reference according to
3052 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3053 // to copy-initializing a temporary of the underlying type with
3054 // the argument expression. Any difference in top-level
3055 // cv-qualification is subsumed by the initialization itself
3056 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00003057 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3058 /*AllowExplicit=*/false,
3059 /*InOverloadResolution=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003060
3061 // Of course, that's still a reference binding.
3062 if (ICS.isStandard()) {
3063 ICS.Standard.ReferenceBinding = true;
3064 ICS.Standard.RRefBinding = isRValRef;
3065 } else if (ICS.isUserDefined()) {
3066 ICS.UserDefined.After.ReferenceBinding = true;
3067 ICS.UserDefined.After.RRefBinding = isRValRef;
3068 }
3069 return ICS;
3070}
3071
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003072/// TryCopyInitialization - Try to copy-initialize a value of type
3073/// ToType from the expression From. Return the implicit conversion
3074/// sequence required to pass this argument, which may be a bad
3075/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00003076/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00003077/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00003078static ImplicitConversionSequence
3079TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregorb7f9e6a2010-04-16 17:53:55 +00003080 bool SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00003081 bool InOverloadResolution) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003082 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00003083 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00003084 /*FIXME:*/From->getLocStart(),
3085 SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00003086 /*AllowExplicit=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003087
John McCall120d63c2010-08-24 20:38:10 +00003088 return TryImplicitConversion(S, From, ToType,
3089 SuppressUserConversions,
3090 /*AllowExplicit=*/false,
3091 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003092}
3093
Douglas Gregor96176b32008-11-18 23:14:02 +00003094/// TryObjectArgumentInitialization - Try to initialize the object
3095/// parameter of the given member function (@c Method) from the
3096/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00003097static ImplicitConversionSequence
3098TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
3099 CXXMethodDecl *Method,
3100 CXXRecordDecl *ActingContext) {
3101 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00003102 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3103 // const volatile object.
3104 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3105 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00003106 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00003107
3108 // Set up the conversion sequence as a "bad" conversion, to allow us
3109 // to exit early.
3110 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00003111
3112 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00003113 QualType FromType = OrigFromType;
Ted Kremenek6217b802009-07-29 21:53:49 +00003114 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00003115 FromType = PT->getPointeeType();
3116
3117 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00003118
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00003119 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor96176b32008-11-18 23:14:02 +00003120 // where X is the class of which the function is a member
3121 // (C++ [over.match.funcs]p4). However, when finding an implicit
3122 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00003123 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00003124 // (C++ [over.match.funcs]p5). We perform a simplified version of
3125 // reference binding here, that allows class rvalues to bind to
3126 // non-constant references.
3127
3128 // First check the qualifiers. We don't care about lvalue-vs-rvalue
3129 // with the implicit object parameter (C++ [over.match.funcs]p5).
John McCall120d63c2010-08-24 20:38:10 +00003130 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00003131 if (ImplicitParamType.getCVRQualifiers()
3132 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00003133 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00003134 ICS.setBad(BadConversionSequence::bad_qualifiers,
3135 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003136 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003137 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003138
3139 // Check that we have either the same type or a derived type. It
3140 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00003141 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00003142 ImplicitConversionKind SecondKind;
3143 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3144 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00003145 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00003146 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00003147 else {
John McCallb1bdc622010-02-25 01:37:24 +00003148 ICS.setBad(BadConversionSequence::unrelated_class,
3149 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003150 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003151 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003152
3153 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00003154 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00003155 ICS.Standard.setAsIdentityConversion();
3156 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00003157 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003158 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003159 ICS.Standard.ReferenceBinding = true;
3160 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00003161 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003162 return ICS;
3163}
3164
3165/// PerformObjectArgumentInitialization - Perform initialization of
3166/// the implicit object parameter for the given Method with the given
3167/// expression.
3168bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00003169Sema::PerformObjectArgumentInitialization(Expr *&From,
3170 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00003171 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00003172 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003173 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00003174 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00003175 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003176
Ted Kremenek6217b802009-07-29 21:53:49 +00003177 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003178 FromRecordType = PT->getPointeeType();
3179 DestType = Method->getThisType(Context);
3180 } else {
3181 FromRecordType = From->getType();
3182 DestType = ImplicitParamRecordType;
3183 }
3184
John McCall701c89e2009-12-03 04:06:58 +00003185 // Note that we always use the true parent context when performing
3186 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003187 ImplicitConversionSequence ICS
John McCall120d63c2010-08-24 20:38:10 +00003188 = TryObjectArgumentInitialization(*this, From->getType(), Method,
John McCall701c89e2009-12-03 04:06:58 +00003189 Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00003190 if (ICS.isBad()) {
3191 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3192 Qualifiers FromQs = FromRecordType.getQualifiers();
3193 Qualifiers ToQs = DestType.getQualifiers();
3194 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3195 if (CVR) {
3196 Diag(From->getSourceRange().getBegin(),
3197 diag::err_member_function_call_bad_cvr)
3198 << Method->getDeclName() << FromRecordType << (CVR - 1)
3199 << From->getSourceRange();
3200 Diag(Method->getLocation(), diag::note_previous_decl)
3201 << Method->getDeclName();
3202 return true;
3203 }
3204 }
3205
Douglas Gregor96176b32008-11-18 23:14:02 +00003206 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003207 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00003208 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00003209 }
Mike Stump1eb44332009-09-09 15:08:12 +00003210
Douglas Gregor5fccd362010-03-03 23:55:11 +00003211 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall6bb80172010-03-30 21:47:33 +00003212 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor96176b32008-11-18 23:14:02 +00003213
Douglas Gregor5fccd362010-03-03 23:55:11 +00003214 if (!Context.hasSameType(From->getType(), DestType))
John McCall2de56d12010-08-25 11:45:40 +00003215 ImpCastExprToType(From, DestType, CK_NoOp,
John McCall5baba9d2010-08-25 10:28:54 +00003216 From->getType()->isPointerType() ? VK_RValue : VK_LValue);
Douglas Gregor96176b32008-11-18 23:14:02 +00003217 return false;
3218}
3219
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003220/// TryContextuallyConvertToBool - Attempt to contextually convert the
3221/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00003222static ImplicitConversionSequence
3223TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00003224 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00003225 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00003226 // FIXME: Are these flags correct?
3227 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00003228 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00003229 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003230}
3231
3232/// PerformContextuallyConvertToBool - Perform a contextual conversion
3233/// of the expression From to bool (C++0x [conv]p3).
3234bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
John McCall120d63c2010-08-24 20:38:10 +00003235 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00003236 if (!ICS.isBad())
3237 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003238
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003239 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003240 return Diag(From->getSourceRange().getBegin(),
3241 diag::err_typecheck_bool_condition)
3242 << From->getType() << From->getSourceRange();
3243 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003244}
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003245
3246/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3247/// expression From to 'id'.
John McCall120d63c2010-08-24 20:38:10 +00003248static ImplicitConversionSequence
3249TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3250 QualType Ty = S.Context.getObjCIdType();
3251 return TryImplicitConversion(S, From, Ty,
3252 // FIXME: Are these flags correct?
3253 /*SuppressUserConversions=*/false,
3254 /*AllowExplicit=*/true,
3255 /*InOverloadResolution=*/false);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003256}
John McCall120d63c2010-08-24 20:38:10 +00003257
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003258/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3259/// of the expression From to 'id'.
3260bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCallc12c5bb2010-05-15 11:32:37 +00003261 QualType Ty = Context.getObjCIdType();
John McCall120d63c2010-08-24 20:38:10 +00003262 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003263 if (!ICS.isBad())
3264 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3265 return true;
3266}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003267
Douglas Gregorc30614b2010-06-29 23:17:37 +00003268/// \brief Attempt to convert the given expression to an integral or
3269/// enumeration type.
3270///
3271/// This routine will attempt to convert an expression of class type to an
3272/// integral or enumeration type, if that class type only has a single
3273/// conversion to an integral or enumeration type.
3274///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003275/// \param Loc The source location of the construct that requires the
3276/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00003277///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003278/// \param FromE The expression we're converting from.
3279///
3280/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3281/// have integral or enumeration type.
3282///
3283/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3284/// incomplete class type.
3285///
3286/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3287/// explicit conversion function (because no implicit conversion functions
3288/// were available). This is a recovery mode.
3289///
3290/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3291/// showing which conversion was picked.
3292///
3293/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3294/// conversion function that could convert to integral or enumeration type.
3295///
3296/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3297/// usable conversion function.
3298///
3299/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3300/// function, which may be an extension in this case.
3301///
3302/// \returns The expression, converted to an integral or enumeration type if
3303/// successful.
John McCall60d7b3a2010-08-24 06:29:42 +00003304ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00003305Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorc30614b2010-06-29 23:17:37 +00003306 const PartialDiagnostic &NotIntDiag,
3307 const PartialDiagnostic &IncompleteDiag,
3308 const PartialDiagnostic &ExplicitConvDiag,
3309 const PartialDiagnostic &ExplicitConvNote,
3310 const PartialDiagnostic &AmbigDiag,
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003311 const PartialDiagnostic &AmbigNote,
3312 const PartialDiagnostic &ConvDiag) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00003313 // We can't perform any more checking for type-dependent expressions.
3314 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00003315 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003316
3317 // If the expression already has integral or enumeration type, we're golden.
3318 QualType T = From->getType();
3319 if (T->isIntegralOrEnumerationType())
John McCall9ae2f072010-08-23 23:25:46 +00003320 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003321
3322 // FIXME: Check for missing '()' if T is a function type?
3323
3324 // If we don't have a class type in C++, there's no way we can get an
3325 // expression of integral or enumeration type.
3326 const RecordType *RecordTy = T->getAs<RecordType>();
3327 if (!RecordTy || !getLangOptions().CPlusPlus) {
3328 Diag(Loc, NotIntDiag)
3329 << T << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00003330 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003331 }
3332
3333 // We must have a complete class type.
3334 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCall9ae2f072010-08-23 23:25:46 +00003335 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003336
3337 // Look for a conversion to an integral or enumeration type.
3338 UnresolvedSet<4> ViableConversions;
3339 UnresolvedSet<4> ExplicitConversions;
3340 const UnresolvedSetImpl *Conversions
3341 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3342
3343 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3344 E = Conversions->end();
3345 I != E;
3346 ++I) {
3347 if (CXXConversionDecl *Conversion
3348 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3349 if (Conversion->getConversionType().getNonReferenceType()
3350 ->isIntegralOrEnumerationType()) {
3351 if (Conversion->isExplicit())
3352 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3353 else
3354 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3355 }
3356 }
3357
3358 switch (ViableConversions.size()) {
3359 case 0:
3360 if (ExplicitConversions.size() == 1) {
3361 DeclAccessPair Found = ExplicitConversions[0];
3362 CXXConversionDecl *Conversion
3363 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3364
3365 // The user probably meant to invoke the given explicit
3366 // conversion; use it.
3367 QualType ConvTy
3368 = Conversion->getConversionType().getNonReferenceType();
3369 std::string TypeStr;
3370 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3371
3372 Diag(Loc, ExplicitConvDiag)
3373 << T << ConvTy
3374 << FixItHint::CreateInsertion(From->getLocStart(),
3375 "static_cast<" + TypeStr + ">(")
3376 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3377 ")");
3378 Diag(Conversion->getLocation(), ExplicitConvNote)
3379 << ConvTy->isEnumeralType() << ConvTy;
3380
3381 // If we aren't in a SFINAE context, build a call to the
3382 // explicit conversion function.
3383 if (isSFINAEContext())
3384 return ExprError();
3385
3386 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
John McCall9ae2f072010-08-23 23:25:46 +00003387 From = BuildCXXMemberCallExpr(From, Found, Conversion);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003388 }
3389
3390 // We'll complain below about a non-integral condition type.
3391 break;
3392
3393 case 1: {
3394 // Apply this conversion.
3395 DeclAccessPair Found = ViableConversions[0];
3396 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003397
3398 CXXConversionDecl *Conversion
3399 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3400 QualType ConvTy
3401 = Conversion->getConversionType().getNonReferenceType();
3402 if (ConvDiag.getDiagID()) {
3403 if (isSFINAEContext())
3404 return ExprError();
3405
3406 Diag(Loc, ConvDiag)
3407 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3408 }
3409
John McCall9ae2f072010-08-23 23:25:46 +00003410 From = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorc30614b2010-06-29 23:17:37 +00003411 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregorc30614b2010-06-29 23:17:37 +00003412 break;
3413 }
3414
3415 default:
3416 Diag(Loc, AmbigDiag)
3417 << T << From->getSourceRange();
3418 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3419 CXXConversionDecl *Conv
3420 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3421 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3422 Diag(Conv->getLocation(), AmbigNote)
3423 << ConvTy->isEnumeralType() << ConvTy;
3424 }
John McCall9ae2f072010-08-23 23:25:46 +00003425 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003426 }
3427
Douglas Gregoracb0bd82010-06-29 23:25:20 +00003428 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorc30614b2010-06-29 23:17:37 +00003429 Diag(Loc, NotIntDiag)
3430 << From->getType() << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00003431
John McCall9ae2f072010-08-23 23:25:46 +00003432 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003433}
3434
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003435/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00003436/// candidate functions, using the given function call arguments. If
3437/// @p SuppressUserConversions, then don't allow user-defined
3438/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003439///
3440/// \para PartialOverloading true if we are performing "partial" overloading
3441/// based on an incomplete set of function arguments. This feature is used by
3442/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00003443void
3444Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00003445 DeclAccessPair FoundDecl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003446 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00003447 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00003448 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003449 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00003450 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003451 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003452 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00003453 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00003454 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00003455
Douglas Gregor88a35142008-12-22 05:46:06 +00003456 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003457 if (!isa<CXXConstructorDecl>(Method)) {
3458 // If we get here, it's because we're calling a member function
3459 // that is named without a member access expression (e.g.,
3460 // "this->f") that was either written explicitly or created
3461 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00003462 // function, e.g., X::f(). We use an empty type for the implied
3463 // object argument (C++ [over.call.func]p3), and the acting context
3464 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00003465 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall701c89e2009-12-03 04:06:58 +00003466 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003467 SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003468 return;
3469 }
3470 // We treat a constructor like a non-member function, since its object
3471 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00003472 }
3473
Douglas Gregorfd476482009-11-13 23:59:09 +00003474 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00003475 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00003476
Douglas Gregor7edfb692009-11-23 12:27:39 +00003477 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003478 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003479
Douglas Gregor66724ea2009-11-14 01:20:54 +00003480 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3481 // C++ [class.copy]p3:
3482 // A member function template is never instantiated to perform the copy
3483 // of a class object to an object of its class type.
3484 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3485 if (NumArgs == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00003486 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00003487 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3488 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00003489 return;
3490 }
3491
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003492 // Add this candidate
3493 CandidateSet.push_back(OverloadCandidate());
3494 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003495 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003496 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00003497 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003498 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003499 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003500
3501 unsigned NumArgsInProto = Proto->getNumArgs();
3502
3503 // (C++ 13.3.2p2): A candidate function having fewer than m
3504 // parameters is viable only if it has an ellipsis in its parameter
3505 // list (8.3.5).
Douglas Gregor5bd1a112009-09-23 14:56:09 +00003506 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3507 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003508 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003509 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003510 return;
3511 }
3512
3513 // (C++ 13.3.2p2): A candidate function having more than m parameters
3514 // is viable only if the (m+1)st parameter has a default argument
3515 // (8.3.6). For the purposes of overload resolution, the
3516 // parameter list is truncated on the right, so that there are
3517 // exactly m parameters.
3518 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003519 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003520 // Not enough arguments.
3521 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003522 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003523 return;
3524 }
3525
3526 // Determine the implicit conversion sequences for each of the
3527 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003528 Candidate.Conversions.resize(NumArgs);
3529 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3530 if (ArgIdx < NumArgsInProto) {
3531 // (C++ 13.3.2p3): for F to be a viable function, there shall
3532 // exist for each argument an implicit conversion sequence
3533 // (13.3.3.1) that converts that argument to the corresponding
3534 // parameter of F.
3535 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003536 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003537 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003538 SuppressUserConversions,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003539 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003540 if (Candidate.Conversions[ArgIdx].isBad()) {
3541 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003542 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00003543 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00003544 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003545 } else {
3546 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3547 // argument for which there is no corresponding parameter is
3548 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003549 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003550 }
3551 }
3552}
3553
Douglas Gregor063daf62009-03-13 18:40:31 +00003554/// \brief Add all of the function declarations in the given function set to
3555/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00003556void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00003557 Expr **Args, unsigned NumArgs,
3558 OverloadCandidateSet& CandidateSet,
3559 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00003560 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00003561 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3562 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003563 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003564 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003565 cast<CXXMethodDecl>(FD)->getParent(),
3566 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003567 CandidateSet, SuppressUserConversions);
3568 else
John McCall9aa472c2010-03-19 07:35:19 +00003569 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00003570 SuppressUserConversions);
3571 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003572 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00003573 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3574 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003575 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003576 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00003577 /*FIXME: explicit args */ 0,
John McCall701c89e2009-12-03 04:06:58 +00003578 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003579 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00003580 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00003581 else
John McCall9aa472c2010-03-19 07:35:19 +00003582 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCalld5532b62009-11-23 01:53:49 +00003583 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00003584 Args, NumArgs, CandidateSet,
3585 SuppressUserConversions);
3586 }
Douglas Gregor364e0212009-06-27 21:05:07 +00003587 }
Douglas Gregor063daf62009-03-13 18:40:31 +00003588}
3589
John McCall314be4e2009-11-17 07:50:12 +00003590/// AddMethodCandidate - Adds a named decl (which is some kind of
3591/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00003592void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003593 QualType ObjectType,
John McCall314be4e2009-11-17 07:50:12 +00003594 Expr **Args, unsigned NumArgs,
3595 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003596 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00003597 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003598 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00003599
3600 if (isa<UsingShadowDecl>(Decl))
3601 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3602
3603 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3604 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3605 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00003606 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3607 /*ExplicitArgs*/ 0,
John McCall701c89e2009-12-03 04:06:58 +00003608 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00003609 CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003610 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003611 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003612 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall701c89e2009-12-03 04:06:58 +00003613 ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003614 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003615 }
3616}
3617
Douglas Gregor96176b32008-11-18 23:14:02 +00003618/// AddMethodCandidate - Adds the given C++ member function to the set
3619/// of candidate functions, using the given function call arguments
3620/// and the object argument (@c Object). For example, in a call
3621/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3622/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3623/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00003624/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00003625void
John McCall9aa472c2010-03-19 07:35:19 +00003626Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003627 CXXRecordDecl *ActingContext, QualType ObjectType,
3628 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00003629 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003630 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00003631 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003632 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00003633 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003634 assert(!isa<CXXConstructorDecl>(Method) &&
3635 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00003636
Douglas Gregor3f396022009-09-28 04:47:19 +00003637 if (!CandidateSet.isNewCandidate(Method))
3638 return;
3639
Douglas Gregor7edfb692009-11-23 12:27:39 +00003640 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003641 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003642
Douglas Gregor96176b32008-11-18 23:14:02 +00003643 // Add this candidate
3644 CandidateSet.push_back(OverloadCandidate());
3645 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003646 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00003647 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003648 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003649 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003650
3651 unsigned NumArgsInProto = Proto->getNumArgs();
3652
3653 // (C++ 13.3.2p2): A candidate function having fewer than m
3654 // parameters is viable only if it has an ellipsis in its parameter
3655 // list (8.3.5).
3656 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3657 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003658 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003659 return;
3660 }
3661
3662 // (C++ 13.3.2p2): A candidate function having more than m parameters
3663 // is viable only if the (m+1)st parameter has a default argument
3664 // (8.3.6). For the purposes of overload resolution, the
3665 // parameter list is truncated on the right, so that there are
3666 // exactly m parameters.
3667 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3668 if (NumArgs < MinRequiredArgs) {
3669 // Not enough arguments.
3670 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003671 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003672 return;
3673 }
3674
3675 Candidate.Viable = true;
3676 Candidate.Conversions.resize(NumArgs + 1);
3677
John McCall701c89e2009-12-03 04:06:58 +00003678 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00003679 // The implicit object argument is ignored.
3680 Candidate.IgnoreObjectArgument = true;
3681 else {
3682 // Determine the implicit conversion sequence for the object
3683 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00003684 Candidate.Conversions[0]
John McCall120d63c2010-08-24 20:38:10 +00003685 = TryObjectArgumentInitialization(*this, ObjectType, Method,
3686 ActingContext);
John McCall1d318332010-01-12 00:44:57 +00003687 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003688 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003689 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00003690 return;
3691 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003692 }
3693
3694 // Determine the implicit conversion sequences for each of the
3695 // arguments.
3696 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3697 if (ArgIdx < NumArgsInProto) {
3698 // (C++ 13.3.2p3): for F to be a viable function, there shall
3699 // exist for each argument an implicit conversion sequence
3700 // (13.3.3.1) that converts that argument to the corresponding
3701 // parameter of F.
3702 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003703 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003704 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003705 SuppressUserConversions,
Anders Carlsson08972922009-08-28 15:33:32 +00003706 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003707 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00003708 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003709 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00003710 break;
3711 }
3712 } else {
3713 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3714 // argument for which there is no corresponding parameter is
3715 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003716 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00003717 }
3718 }
3719}
Douglas Gregora9333192010-05-08 17:41:32 +00003720
Douglas Gregor6b906862009-08-21 00:16:32 +00003721/// \brief Add a C++ member function template as a candidate to the candidate
3722/// set, using template argument deduction to produce an appropriate member
3723/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003724void
Douglas Gregor6b906862009-08-21 00:16:32 +00003725Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00003726 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003727 CXXRecordDecl *ActingContext,
John McCalld5532b62009-11-23 01:53:49 +00003728 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00003729 QualType ObjectType,
3730 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003731 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003732 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003733 if (!CandidateSet.isNewCandidate(MethodTmpl))
3734 return;
3735
Douglas Gregor6b906862009-08-21 00:16:32 +00003736 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003737 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00003738 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003739 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00003740 // candidate functions in the usual way.113) A given name can refer to one
3741 // or more function templates and also to a set of overloaded non-template
3742 // functions. In such a case, the candidate functions generated from each
3743 // function template are combined with the set of non-template candidate
3744 // functions.
John McCall5769d612010-02-08 23:07:23 +00003745 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00003746 FunctionDecl *Specialization = 0;
3747 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003748 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003749 Args, NumArgs, Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003750 CandidateSet.push_back(OverloadCandidate());
3751 OverloadCandidate &Candidate = CandidateSet.back();
3752 Candidate.FoundDecl = FoundDecl;
3753 Candidate.Function = MethodTmpl->getTemplatedDecl();
3754 Candidate.Viable = false;
3755 Candidate.FailureKind = ovl_fail_bad_deduction;
3756 Candidate.IsSurrogate = false;
3757 Candidate.IgnoreObjectArgument = false;
3758 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3759 Info);
3760 return;
3761 }
Mike Stump1eb44332009-09-09 15:08:12 +00003762
Douglas Gregor6b906862009-08-21 00:16:32 +00003763 // Add the function template specialization produced by template argument
3764 // deduction as a candidate.
3765 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00003766 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00003767 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00003768 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003769 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003770 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00003771}
3772
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003773/// \brief Add a C++ function template specialization as a candidate
3774/// in the candidate set, using template argument deduction to produce
3775/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003776void
Douglas Gregore53060f2009-06-25 22:08:12 +00003777Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003778 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00003779 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00003780 Expr **Args, unsigned NumArgs,
3781 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003782 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003783 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3784 return;
3785
Douglas Gregore53060f2009-06-25 22:08:12 +00003786 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003787 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00003788 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003789 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00003790 // candidate functions in the usual way.113) A given name can refer to one
3791 // or more function templates and also to a set of overloaded non-template
3792 // functions. In such a case, the candidate functions generated from each
3793 // function template are combined with the set of non-template candidate
3794 // functions.
John McCall5769d612010-02-08 23:07:23 +00003795 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00003796 FunctionDecl *Specialization = 0;
3797 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003798 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003799 Args, NumArgs, Specialization, Info)) {
John McCall578b69b2009-12-16 08:11:27 +00003800 CandidateSet.push_back(OverloadCandidate());
3801 OverloadCandidate &Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003802 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00003803 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3804 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003805 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00003806 Candidate.IsSurrogate = false;
3807 Candidate.IgnoreObjectArgument = false;
Douglas Gregorff5adac2010-05-08 20:18:54 +00003808 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3809 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00003810 return;
3811 }
Mike Stump1eb44332009-09-09 15:08:12 +00003812
Douglas Gregore53060f2009-06-25 22:08:12 +00003813 // Add the function template specialization produced by template argument
3814 // deduction as a candidate.
3815 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003816 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003817 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00003818}
Mike Stump1eb44332009-09-09 15:08:12 +00003819
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003820/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00003821/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003822/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00003823/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003824/// (which may or may not be the same type as the type that the
3825/// conversion function produces).
3826void
3827Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003828 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003829 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003830 Expr *From, QualType ToType,
3831 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003832 assert(!Conversion->getDescribedFunctionTemplate() &&
3833 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003834 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00003835 if (!CandidateSet.isNewCandidate(Conversion))
3836 return;
3837
Douglas Gregor7edfb692009-11-23 12:27:39 +00003838 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00003839 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00003840
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003841 // Add this candidate
3842 CandidateSet.push_back(OverloadCandidate());
3843 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003844 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003845 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003846 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003847 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003848 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003849 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003850 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003851 Candidate.Viable = true;
3852 Candidate.Conversions.resize(1);
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003853
Douglas Gregorbca39322010-08-19 15:37:02 +00003854 // C++ [over.match.funcs]p4:
3855 // For conversion functions, the function is considered to be a member of
3856 // the class of the implicit implied object argument for the purpose of
3857 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003858 //
3859 // Determine the implicit conversion sequence for the implicit
3860 // object parameter.
3861 QualType ImplicitParamType = From->getType();
3862 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
3863 ImplicitParamType = FromPtrType->getPointeeType();
3864 CXXRecordDecl *ConversionContext
3865 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
3866
3867 Candidate.Conversions[0]
John McCall120d63c2010-08-24 20:38:10 +00003868 = TryObjectArgumentInitialization(*this, From->getType(), Conversion,
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003869 ConversionContext);
3870
John McCall1d318332010-01-12 00:44:57 +00003871 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003872 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003873 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003874 return;
3875 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003876
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003877 // We won't go through a user-define type conversion function to convert a
3878 // derived to base as such conversions are given Conversion Rank. They only
3879 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3880 QualType FromCanon
3881 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3882 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3883 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3884 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003885 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003886 return;
3887 }
3888
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003889 // To determine what the conversion from the result of calling the
3890 // conversion function to the type we're eventually trying to
3891 // convert to (ToType), we need to synthesize a call to the
3892 // conversion function and attempt copy initialization from it. This
3893 // makes sure that we get the right semantics with respect to
3894 // lvalues/rvalues and the type. Fortunately, we can allocate this
3895 // call on the stack and we don't need its arguments to be
3896 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00003897 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003898 From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00003899 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
3900 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00003901 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00003902 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00003903
Douglas Gregor7d14d382010-11-13 19:36:57 +00003904 QualType CallResultType
3905 = Conversion->getConversionType().getNonLValueExprType(Context);
3906 if (RequireCompleteType(From->getLocStart(), CallResultType, 0)) {
3907 Candidate.Viable = false;
3908 Candidate.FailureKind = ovl_fail_bad_final_conversion;
3909 return;
3910 }
3911
Mike Stump1eb44332009-09-09 15:08:12 +00003912 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00003913 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3914 // allocator).
Douglas Gregor7d14d382010-11-13 19:36:57 +00003915 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003916 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00003917 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00003918 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00003919 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003920 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00003921
John McCall1d318332010-01-12 00:44:57 +00003922 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003923 case ImplicitConversionSequence::StandardConversion:
3924 Candidate.FinalConversion = ICS.Standard;
Douglas Gregorc520c842010-04-12 23:42:09 +00003925
3926 // C++ [over.ics.user]p3:
3927 // If the user-defined conversion is specified by a specialization of a
3928 // conversion function template, the second standard conversion sequence
3929 // shall have exact match rank.
3930 if (Conversion->getPrimaryTemplate() &&
3931 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3932 Candidate.Viable = false;
3933 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3934 }
3935
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003936 break;
3937
3938 case ImplicitConversionSequence::BadConversion:
3939 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003940 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003941 break;
3942
3943 default:
Mike Stump1eb44332009-09-09 15:08:12 +00003944 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003945 "Can only end up with a standard conversion sequence or failure");
3946 }
3947}
3948
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003949/// \brief Adds a conversion function template specialization
3950/// candidate to the overload set, using template argument deduction
3951/// to deduce the template arguments of the conversion function
3952/// template from the type that we are converting to (C++
3953/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00003954void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003955Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003956 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003957 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003958 Expr *From, QualType ToType,
3959 OverloadCandidateSet &CandidateSet) {
3960 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3961 "Only conversion function templates permitted here");
3962
Douglas Gregor3f396022009-09-28 04:47:19 +00003963 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3964 return;
3965
John McCall5769d612010-02-08 23:07:23 +00003966 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003967 CXXConversionDecl *Specialization = 0;
3968 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00003969 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003970 Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003971 CandidateSet.push_back(OverloadCandidate());
3972 OverloadCandidate &Candidate = CandidateSet.back();
3973 Candidate.FoundDecl = FoundDecl;
3974 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3975 Candidate.Viable = false;
3976 Candidate.FailureKind = ovl_fail_bad_deduction;
3977 Candidate.IsSurrogate = false;
3978 Candidate.IgnoreObjectArgument = false;
3979 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3980 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003981 return;
3982 }
Mike Stump1eb44332009-09-09 15:08:12 +00003983
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003984 // Add the conversion function template specialization produced by
3985 // template argument deduction as a candidate.
3986 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003987 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00003988 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003989}
3990
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003991/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3992/// converts the given @c Object to a function pointer via the
3993/// conversion function @c Conversion, and then attempts to call it
3994/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3995/// the type of function that we'll eventually be calling.
3996void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003997 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003998 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00003999 const FunctionProtoType *Proto,
John McCall701c89e2009-12-03 04:06:58 +00004000 QualType ObjectType,
4001 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004002 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00004003 if (!CandidateSet.isNewCandidate(Conversion))
4004 return;
4005
Douglas Gregor7edfb692009-11-23 12:27:39 +00004006 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004007 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004008
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004009 CandidateSet.push_back(OverloadCandidate());
4010 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004011 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004012 Candidate.Function = 0;
4013 Candidate.Surrogate = Conversion;
4014 Candidate.Viable = true;
4015 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00004016 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004017 Candidate.Conversions.resize(NumArgs + 1);
4018
4019 // Determine the implicit conversion sequence for the implicit
4020 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00004021 ImplicitConversionSequence ObjectInit
John McCall120d63c2010-08-24 20:38:10 +00004022 = TryObjectArgumentInitialization(*this, ObjectType, Conversion,
4023 ActingContext);
John McCall1d318332010-01-12 00:44:57 +00004024 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004025 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004026 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00004027 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004028 return;
4029 }
4030
4031 // The first conversion is actually a user-defined conversion whose
4032 // first conversion is ObjectInit's standard conversion (which is
4033 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00004034 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004035 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00004036 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004037 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00004038 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004039 = Candidate.Conversions[0].UserDefined.Before;
4040 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4041
Mike Stump1eb44332009-09-09 15:08:12 +00004042 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004043 unsigned NumArgsInProto = Proto->getNumArgs();
4044
4045 // (C++ 13.3.2p2): A candidate function having fewer than m
4046 // parameters is viable only if it has an ellipsis in its parameter
4047 // list (8.3.5).
4048 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4049 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004050 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004051 return;
4052 }
4053
4054 // Function types don't have any default arguments, so just check if
4055 // we have enough arguments.
4056 if (NumArgs < NumArgsInProto) {
4057 // Not enough arguments.
4058 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004059 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004060 return;
4061 }
4062
4063 // Determine the implicit conversion sequences for each of the
4064 // arguments.
4065 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4066 if (ArgIdx < NumArgsInProto) {
4067 // (C++ 13.3.2p3): for F to be a viable function, there shall
4068 // exist for each argument an implicit conversion sequence
4069 // (13.3.3.1) that converts that argument to the corresponding
4070 // parameter of F.
4071 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00004072 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004073 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00004074 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00004075 /*InOverloadResolution=*/false);
John McCall1d318332010-01-12 00:44:57 +00004076 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004077 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004078 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004079 break;
4080 }
4081 } else {
4082 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4083 // argument for which there is no corresponding parameter is
4084 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00004085 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004086 }
4087 }
4088}
4089
Douglas Gregor063daf62009-03-13 18:40:31 +00004090/// \brief Add overload candidates for overloaded operators that are
4091/// member functions.
4092///
4093/// Add the overloaded operator candidates that are member functions
4094/// for the operator Op that was used in an operator expression such
4095/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4096/// CandidateSet will store the added overload candidates. (C++
4097/// [over.match.oper]).
4098void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4099 SourceLocation OpLoc,
4100 Expr **Args, unsigned NumArgs,
4101 OverloadCandidateSet& CandidateSet,
4102 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00004103 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4104
4105 // C++ [over.match.oper]p3:
4106 // For a unary operator @ with an operand of a type whose
4107 // cv-unqualified version is T1, and for a binary operator @ with
4108 // a left operand of a type whose cv-unqualified version is T1 and
4109 // a right operand of a type whose cv-unqualified version is T2,
4110 // three sets of candidate functions, designated member
4111 // candidates, non-member candidates and built-in candidates, are
4112 // constructed as follows:
4113 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00004114
4115 // -- If T1 is a class type, the set of member candidates is the
4116 // result of the qualified lookup of T1::operator@
4117 // (13.3.1.1.1); otherwise, the set of member candidates is
4118 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00004119 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004120 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004121 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004122 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004123
John McCalla24dc2e2009-11-17 02:14:36 +00004124 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4125 LookupQualifiedName(Operators, T1Rec->getDecl());
4126 Operators.suppressDiagnostics();
4127
Mike Stump1eb44332009-09-09 15:08:12 +00004128 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004129 OperEnd = Operators.end();
4130 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00004131 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00004132 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall701c89e2009-12-03 04:06:58 +00004133 Args + 1, NumArgs - 1, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00004134 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00004135 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004136}
4137
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004138/// AddBuiltinCandidate - Add a candidate for a built-in
4139/// operator. ResultTy and ParamTys are the result and parameter types
4140/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004141/// arguments being passed to the candidate. IsAssignmentOperator
4142/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004143/// operator. NumContextualBoolArguments is the number of arguments
4144/// (at the beginning of the argument list) that will be contextually
4145/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00004146void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004147 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004148 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004149 bool IsAssignmentOperator,
4150 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00004151 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004152 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004153
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004154 // Add this candidate
4155 CandidateSet.push_back(OverloadCandidate());
4156 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004157 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004158 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00004159 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004160 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004161 Candidate.BuiltinTypes.ResultTy = ResultTy;
4162 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4163 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4164
4165 // Determine the implicit conversion sequences for each of the
4166 // arguments.
4167 Candidate.Viable = true;
4168 Candidate.Conversions.resize(NumArgs);
4169 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004170 // C++ [over.match.oper]p4:
4171 // For the built-in assignment operators, conversions of the
4172 // left operand are restricted as follows:
4173 // -- no temporaries are introduced to hold the left operand, and
4174 // -- no user-defined conversions are applied to the left
4175 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00004176 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004177 //
4178 // We block these conversions by turning off user-defined
4179 // conversions, since that is the only way that initialization of
4180 // a reference to a non-class type can occur from something that
4181 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004182 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00004183 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004184 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00004185 Candidate.Conversions[ArgIdx]
4186 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004187 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00004188 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004189 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00004190 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00004191 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004192 }
John McCall1d318332010-01-12 00:44:57 +00004193 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004194 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004195 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00004196 break;
4197 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004198 }
4199}
4200
4201/// BuiltinCandidateTypeSet - A set of types that will be used for the
4202/// candidate operator functions for built-in operators (C++
4203/// [over.built]). The types are separated into pointer types and
4204/// enumeration types.
4205class BuiltinCandidateTypeSet {
4206 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004207 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004208
4209 /// PointerTypes - The set of pointer types that will be used in the
4210 /// built-in candidates.
4211 TypeSet PointerTypes;
4212
Sebastian Redl78eb8742009-04-19 21:53:20 +00004213 /// MemberPointerTypes - The set of member pointer types that will be
4214 /// used in the built-in candidates.
4215 TypeSet MemberPointerTypes;
4216
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004217 /// EnumerationTypes - The set of enumeration types that will be
4218 /// used in the built-in candidates.
4219 TypeSet EnumerationTypes;
4220
Douglas Gregor26bcf672010-05-19 03:21:00 +00004221 /// \brief The set of vector types that will be used in the built-in
4222 /// candidates.
4223 TypeSet VectorTypes;
4224
Douglas Gregor5842ba92009-08-24 15:23:48 +00004225 /// Sema - The semantic analysis instance where we are building the
4226 /// candidate type set.
4227 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00004228
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004229 /// Context - The AST context in which we will build the type sets.
4230 ASTContext &Context;
4231
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004232 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4233 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00004234 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004235
4236public:
4237 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004238 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004239
Mike Stump1eb44332009-09-09 15:08:12 +00004240 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor5842ba92009-08-24 15:23:48 +00004241 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004242
Douglas Gregor573d9c32009-10-21 23:19:44 +00004243 void AddTypesConvertedFrom(QualType Ty,
4244 SourceLocation Loc,
4245 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004246 bool AllowExplicitConversions,
4247 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004248
4249 /// pointer_begin - First pointer type found;
4250 iterator pointer_begin() { return PointerTypes.begin(); }
4251
Sebastian Redl78eb8742009-04-19 21:53:20 +00004252 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004253 iterator pointer_end() { return PointerTypes.end(); }
4254
Sebastian Redl78eb8742009-04-19 21:53:20 +00004255 /// member_pointer_begin - First member pointer type found;
4256 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4257
4258 /// member_pointer_end - Past the last member pointer type found;
4259 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4260
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004261 /// enumeration_begin - First enumeration type found;
4262 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4263
Sebastian Redl78eb8742009-04-19 21:53:20 +00004264 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004265 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004266
4267 iterator vector_begin() { return VectorTypes.begin(); }
4268 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004269};
4270
Sebastian Redl78eb8742009-04-19 21:53:20 +00004271/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004272/// the set of pointer types along with any more-qualified variants of
4273/// that type. For example, if @p Ty is "int const *", this routine
4274/// will add "int const *", "int const volatile *", "int const
4275/// restrict *", and "int const volatile restrict *" to the set of
4276/// pointer types. Returns true if the add of @p Ty itself succeeded,
4277/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00004278///
4279/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004280bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00004281BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4282 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00004283
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004284 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004285 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004286 return false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004287
4288 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00004289 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004290 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004291 if (!PointerTy) {
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004292 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004293 PointeeTy = PTy->getPointeeType();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004294 buildObjCPtr = true;
4295 }
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004296 else
4297 assert(false && "type was not a pointer type!");
4298 }
4299 else
4300 PointeeTy = PointerTy->getPointeeType();
4301
Sebastian Redla9efada2009-11-18 20:39:26 +00004302 // Don't add qualified variants of arrays. For one, they're not allowed
4303 // (the qualifier would sink to the element type), and for another, the
4304 // only overload situation where it matters is subscript or pointer +- int,
4305 // and those shouldn't have qualifier variants anyway.
4306 if (PointeeTy->isArrayType())
4307 return true;
John McCall0953e762009-09-24 19:53:00 +00004308 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00004309 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00004310 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004311 bool hasVolatile = VisibleQuals.hasVolatile();
4312 bool hasRestrict = VisibleQuals.hasRestrict();
4313
John McCall0953e762009-09-24 19:53:00 +00004314 // Iterate through all strict supersets of BaseCVR.
4315 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4316 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004317 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4318 // in the types.
4319 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4320 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00004321 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004322 if (!buildObjCPtr)
4323 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4324 else
4325 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004326 }
4327
4328 return true;
4329}
4330
Sebastian Redl78eb8742009-04-19 21:53:20 +00004331/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4332/// to the set of pointer types along with any more-qualified variants of
4333/// that type. For example, if @p Ty is "int const *", this routine
4334/// will add "int const *", "int const volatile *", "int const
4335/// restrict *", and "int const volatile restrict *" to the set of
4336/// pointer types. Returns true if the add of @p Ty itself succeeded,
4337/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00004338///
4339/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004340bool
4341BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4342 QualType Ty) {
4343 // Insert this type.
4344 if (!MemberPointerTypes.insert(Ty))
4345 return false;
4346
John McCall0953e762009-09-24 19:53:00 +00004347 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4348 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00004349
John McCall0953e762009-09-24 19:53:00 +00004350 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00004351 // Don't add qualified variants of arrays. For one, they're not allowed
4352 // (the qualifier would sink to the element type), and for another, the
4353 // only overload situation where it matters is subscript or pointer +- int,
4354 // and those shouldn't have qualifier variants anyway.
4355 if (PointeeTy->isArrayType())
4356 return true;
John McCall0953e762009-09-24 19:53:00 +00004357 const Type *ClassTy = PointerTy->getClass();
4358
4359 // Iterate through all strict supersets of the pointee type's CVR
4360 // qualifiers.
4361 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4362 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4363 if ((CVR | BaseCVR) != CVR) continue;
4364
4365 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4366 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00004367 }
4368
4369 return true;
4370}
4371
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004372/// AddTypesConvertedFrom - Add each of the types to which the type @p
4373/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00004374/// primarily interested in pointer types and enumeration types. We also
4375/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004376/// AllowUserConversions is true if we should look at the conversion
4377/// functions of a class type, and AllowExplicitConversions if we
4378/// should also include the explicit conversion functions of a class
4379/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00004380void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004381BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004382 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004383 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004384 bool AllowExplicitConversions,
4385 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004386 // Only deal with canonical types.
4387 Ty = Context.getCanonicalType(Ty);
4388
4389 // Look through reference types; they aren't part of the type of an
4390 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00004391 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004392 Ty = RefTy->getPointeeType();
4393
4394 // We don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004395 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004396
Sebastian Redla65b5512009-11-05 16:36:20 +00004397 // If we're dealing with an array type, decay to the pointer.
4398 if (Ty->isArrayType())
4399 Ty = SemaRef.Context.getArrayDecayedType(Ty);
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004400 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4401 PointerTypes.insert(Ty);
4402 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004403 // Insert our type, and its more-qualified variants, into the set
4404 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004405 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004406 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00004407 } else if (Ty->isMemberPointerType()) {
4408 // Member pointers are far easier, since the pointee can't be converted.
4409 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4410 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004411 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00004412 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004413 } else if (Ty->isVectorType()) {
4414 VectorTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004415 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004416 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00004417 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00004418 // No conversion functions in incomplete types.
4419 return;
4420 }
Mike Stump1eb44332009-09-09 15:08:12 +00004421
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004422 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00004423 const UnresolvedSetImpl *Conversions
Fariborz Jahanianca4fb042009-10-07 17:26:09 +00004424 = ClassDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00004425 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004426 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00004427 NamedDecl *D = I.getDecl();
4428 if (isa<UsingShadowDecl>(D))
4429 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004430
Mike Stump1eb44332009-09-09 15:08:12 +00004431 // Skip conversion function templates; they don't tell us anything
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004432 // about which builtin types we can convert to.
John McCall32daa422010-03-31 01:36:47 +00004433 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004434 continue;
4435
John McCall32daa422010-03-31 01:36:47 +00004436 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004437 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00004438 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004439 VisibleQuals);
4440 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004441 }
4442 }
4443 }
4444}
4445
Douglas Gregor19b7b152009-08-24 13:43:27 +00004446/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4447/// the volatile- and non-volatile-qualified assignment operators for the
4448/// given type to the candidate set.
4449static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4450 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00004451 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004452 unsigned NumArgs,
4453 OverloadCandidateSet &CandidateSet) {
4454 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00004455
Douglas Gregor19b7b152009-08-24 13:43:27 +00004456 // T& operator=(T&, T)
4457 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4458 ParamTypes[1] = T;
4459 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4460 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004461
Douglas Gregor19b7b152009-08-24 13:43:27 +00004462 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4463 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00004464 ParamTypes[0]
4465 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00004466 ParamTypes[1] = T;
4467 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00004468 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00004469 }
4470}
Mike Stump1eb44332009-09-09 15:08:12 +00004471
Sebastian Redl9994a342009-10-25 17:03:50 +00004472/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4473/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004474static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4475 Qualifiers VRQuals;
4476 const RecordType *TyRec;
4477 if (const MemberPointerType *RHSMPType =
4478 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004479 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004480 else
4481 TyRec = ArgExpr->getType()->getAs<RecordType>();
4482 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004483 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004484 VRQuals.addVolatile();
4485 VRQuals.addRestrict();
4486 return VRQuals;
4487 }
4488
4489 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00004490 if (!ClassDecl->hasDefinition())
4491 return VRQuals;
4492
John McCalleec51cf2010-01-20 00:46:10 +00004493 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00004494 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004495
John McCalleec51cf2010-01-20 00:46:10 +00004496 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004497 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00004498 NamedDecl *D = I.getDecl();
4499 if (isa<UsingShadowDecl>(D))
4500 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4501 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004502 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4503 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4504 CanTy = ResTypeRef->getPointeeType();
4505 // Need to go down the pointer/mempointer chain and add qualifiers
4506 // as see them.
4507 bool done = false;
4508 while (!done) {
4509 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4510 CanTy = ResTypePtr->getPointeeType();
4511 else if (const MemberPointerType *ResTypeMPtr =
4512 CanTy->getAs<MemberPointerType>())
4513 CanTy = ResTypeMPtr->getPointeeType();
4514 else
4515 done = true;
4516 if (CanTy.isVolatileQualified())
4517 VRQuals.addVolatile();
4518 if (CanTy.isRestrictQualified())
4519 VRQuals.addRestrict();
4520 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4521 return VRQuals;
4522 }
4523 }
4524 }
4525 return VRQuals;
4526}
John McCall00071ec2010-11-13 05:51:15 +00004527
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004528
Douglas Gregor74253732008-11-19 15:42:04 +00004529/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4530/// operator overloads to the candidate set (C++ [over.built]), based
4531/// on the operator @p Op and the arguments given. For example, if the
4532/// operator is a binary '+', this routine might add "int
4533/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004534void
Mike Stump1eb44332009-09-09 15:08:12 +00004535Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004536 SourceLocation OpLoc,
Douglas Gregor74253732008-11-19 15:42:04 +00004537 Expr **Args, unsigned NumArgs,
4538 OverloadCandidateSet& CandidateSet) {
John McCall00071ec2010-11-13 05:51:15 +00004539 // Information about arithmetic types useful to builtin-type
4540 // calculations.
4541
4542 // The "promoted arithmetic types" are the arithmetic
4543 // types are that preserved by promotion (C++ [over.built]p2).
4544
4545 static const unsigned FirstIntegralType = 3;
4546 static const unsigned LastIntegralType = 18;
4547 static const unsigned FirstPromotedIntegralType = 3,
4548 LastPromotedIntegralType = 9;
4549 static const unsigned FirstPromotedArithmeticType = 0,
4550 LastPromotedArithmeticType = 9;
4551 static const unsigned NumArithmeticTypes = 18;
4552
John McCall72a01412010-11-13 02:01:09 +00004553 static CanQualType ASTContext::* const ArithmeticTypes[NumArithmeticTypes] = {
John McCall00071ec2010-11-13 05:51:15 +00004554 // Start of promoted types.
4555 &ASTContext::FloatTy,
4556 &ASTContext::DoubleTy,
4557 &ASTContext::LongDoubleTy,
4558
4559 // Start of integral types.
4560 &ASTContext::IntTy,
4561 &ASTContext::LongTy,
4562 &ASTContext::LongLongTy,
4563 &ASTContext::UnsignedIntTy,
4564 &ASTContext::UnsignedLongTy,
4565 &ASTContext::UnsignedLongLongTy,
4566 // End of promoted types.
4567
John McCall72a01412010-11-13 02:01:09 +00004568 &ASTContext::BoolTy,
4569 &ASTContext::CharTy,
4570 &ASTContext::WCharTy,
4571 &ASTContext::Char16Ty,
4572 &ASTContext::Char32Ty,
4573 &ASTContext::SignedCharTy,
4574 &ASTContext::ShortTy,
4575 &ASTContext::UnsignedCharTy,
John McCall00071ec2010-11-13 05:51:15 +00004576 &ASTContext::UnsignedShortTy
4577 // End of integral types.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004578 };
John McCall00071ec2010-11-13 05:51:15 +00004579 // FIXME: What about complex?
John McCall72a01412010-11-13 02:01:09 +00004580 assert(ArithmeticTypes[FirstPromotedIntegralType] == &ASTContext::IntTy &&
Douglas Gregor652371a2009-10-21 22:01:30 +00004581 "Invalid first promoted integral type");
4582 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
John McCall72a01412010-11-13 02:01:09 +00004583 == &ASTContext::UnsignedLongLongTy &&
Douglas Gregor652371a2009-10-21 22:01:30 +00004584 "Invalid last promoted integral type");
John McCall00071ec2010-11-13 05:51:15 +00004585 assert(ArithmeticTypes[FirstPromotedArithmeticType] == &ASTContext::FloatTy &&
Douglas Gregor652371a2009-10-21 22:01:30 +00004586 "Invalid first promoted arithmetic type");
4587 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
John McCall00071ec2010-11-13 05:51:15 +00004588 == &ASTContext::UnsignedLongLongTy &&
Douglas Gregor652371a2009-10-21 22:01:30 +00004589 "Invalid last promoted arithmetic type");
John McCall00071ec2010-11-13 05:51:15 +00004590
4591 // Accelerator table for performing the usual arithmetic conversions.
4592 // The rules are basically:
4593 // - if either is floating-point, use the wider floating-point
4594 // - if same signedness, use the higher rank
4595 // - if same size, use unsigned of the higher rank
4596 // - use the larger type
4597 // These rules, together with the axiom that higher ranks are
4598 // never smaller, are sufficient to precompute all of these results
4599 // *except* when dealing with signed types of higher rank.
4600 // (we could precompute SLL x UI for all known platforms, but it's
4601 // better not to make any assumptions).
4602 enum PromT { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1 };
4603 static PromT UsualArithmeticConversionsTypes
4604 [LastPromotedArithmeticType][LastPromotedArithmeticType] = {
4605 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
4606 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
4607 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
4608 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
4609 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
4610 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
4611 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
4612 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
4613 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL }
4614 };
4615 struct UsualArithmeticConversionsType {
4616 static CanQualType find(ASTContext &C, unsigned L, unsigned R) {
4617 assert(L < LastPromotedArithmeticType);
4618 assert(R < LastPromotedArithmeticType);
4619 signed char Idx = UsualArithmeticConversionsTypes[L][R];
4620
4621 // Fast path: the table gives us a concrete answer.
4622 if (Idx != Dep) return C.*ArithmeticTypes[Idx];
4623
4624 // Slow path: we need to compare widths.
4625 // An invariant is that the signed type has higher rank.
4626 CanQualType LT = C.*ArithmeticTypes[L], RT = C.*ArithmeticTypes[R];
4627 unsigned LW = C.getIntWidth(LT), RW = C.getIntWidth(RT);
4628
4629 // If they're different widths, use the signed type.
4630 if (LW > RW) return LT;
4631 else if (LW > RW) return RT;
4632
4633 // Otherwise, use the unsigned type of the signed type's rank.
4634 if (L == SL || R == SL) return C.UnsignedLongTy;
4635 assert(L == SLL || R == SLL);
4636 return C.UnsignedLongLongTy;
4637 }
4638 };
Douglas Gregor652371a2009-10-21 22:01:30 +00004639
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004640 // Find all of the types that the arguments can convert to, but only
4641 // if the operator we're looking at has built-in operator candidates
4642 // that make use of these types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004643 Qualifiers VisibleTypeConversionsQuals;
4644 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004645 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4646 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4647
Douglas Gregorfec56e72010-11-03 17:00:07 +00004648 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
4649 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4650 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
4651 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4652 OpLoc,
4653 true,
4654 (Op == OO_Exclaim ||
4655 Op == OO_AmpAmp ||
4656 Op == OO_PipePipe),
4657 VisibleTypeConversionsQuals);
4658 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004659
Douglas Gregor661b4932010-09-12 04:28:07 +00004660 // C++ [over.built]p1:
4661 // If there is a user-written candidate with the same name and parameter
4662 // types as a built-in candidate operator function, the built-in operator
4663 // function is hidden and is not included in the set of candidate functions.
4664 //
4665 // The text is actually in a note, but if we don't implement it then we end
4666 // up with ambiguities when the user provides an overloaded operator for
4667 // an enumeration type. Note that only enumeration types have this problem,
4668 // so we track which enumeration types we've seen operators for.
4669 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
4670 UserDefinedBinaryOperators;
4671
Douglas Gregorfec56e72010-11-03 17:00:07 +00004672 /// Set of (canonical) types that we've already handled.
4673 llvm::SmallPtrSet<QualType, 8> AddedTypes;
4674
4675 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4676 if (CandidateTypes[ArgIdx].enumeration_begin()
4677 != CandidateTypes[ArgIdx].enumeration_end()) {
4678 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
4679 CEnd = CandidateSet.end();
4680 C != CEnd; ++C) {
4681 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
4682 continue;
4683
4684 // Check if the first parameter is of enumeration type.
4685 QualType FirstParamType
4686 = C->Function->getParamDecl(0)->getType().getUnqualifiedType();
4687 if (!FirstParamType->isEnumeralType())
4688 continue;
4689
4690 // Check if the second parameter is of enumeration type.
4691 QualType SecondParamType
4692 = C->Function->getParamDecl(1)->getType().getUnqualifiedType();
4693 if (!SecondParamType->isEnumeralType())
4694 continue;
Douglas Gregor661b4932010-09-12 04:28:07 +00004695
Douglas Gregorfec56e72010-11-03 17:00:07 +00004696 // Add this operator to the set of known user-defined operators.
4697 UserDefinedBinaryOperators.insert(
4698 std::make_pair(Context.getCanonicalType(FirstParamType),
4699 Context.getCanonicalType(SecondParamType)));
4700 }
Douglas Gregor661b4932010-09-12 04:28:07 +00004701 }
4702 }
4703
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004704 bool isComparison = false;
4705 switch (Op) {
4706 case OO_None:
4707 case NUM_OVERLOADED_OPERATORS:
4708 assert(false && "Expected an overloaded operator");
4709 break;
4710
Douglas Gregor74253732008-11-19 15:42:04 +00004711 case OO_Star: // '*' is either unary or binary
Mike Stump1eb44332009-09-09 15:08:12 +00004712 if (NumArgs == 1)
Douglas Gregor74253732008-11-19 15:42:04 +00004713 goto UnaryStar;
4714 else
4715 goto BinaryStar;
4716 break;
4717
4718 case OO_Plus: // '+' is either unary or binary
4719 if (NumArgs == 1)
4720 goto UnaryPlus;
4721 else
4722 goto BinaryPlus;
4723 break;
4724
4725 case OO_Minus: // '-' is either unary or binary
4726 if (NumArgs == 1)
4727 goto UnaryMinus;
4728 else
4729 goto BinaryMinus;
4730 break;
4731
4732 case OO_Amp: // '&' is either unary or binary
4733 if (NumArgs == 1)
4734 goto UnaryAmp;
4735 else
4736 goto BinaryAmp;
4737
4738 case OO_PlusPlus:
4739 case OO_MinusMinus:
4740 // C++ [over.built]p3:
4741 //
4742 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4743 // is either volatile or empty, there exist candidate operator
4744 // functions of the form
4745 //
4746 // VQ T& operator++(VQ T&);
4747 // T operator++(VQ T&, int);
4748 //
4749 // C++ [over.built]p4:
4750 //
4751 // For every pair (T, VQ), where T is an arithmetic type other
4752 // than bool, and VQ is either volatile or empty, there exist
4753 // candidate operator functions of the form
4754 //
4755 // VQ T& operator--(VQ T&);
4756 // T operator--(VQ T&, int);
Mike Stump1eb44332009-09-09 15:08:12 +00004757 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor74253732008-11-19 15:42:04 +00004758 Arith < NumArithmeticTypes; ++Arith) {
John McCall72a01412010-11-13 02:01:09 +00004759 QualType ArithTy = Context.*ArithmeticTypes[Arith];
Mike Stump1eb44332009-09-09 15:08:12 +00004760 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004761 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00004762
4763 // Non-volatile version.
4764 if (NumArgs == 1)
4765 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4766 else
4767 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004768 // heuristic to reduce number of builtin candidates in the set.
4769 // Add volatile version only if there are conversions to a volatile type.
4770 if (VisibleTypeConversionsQuals.hasVolatile()) {
4771 // Volatile version
4772 ParamTypes[0]
4773 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4774 if (NumArgs == 1)
4775 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4776 else
4777 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4778 }
Douglas Gregor74253732008-11-19 15:42:04 +00004779 }
4780
4781 // C++ [over.built]p5:
4782 //
4783 // For every pair (T, VQ), where T is a cv-qualified or
4784 // cv-unqualified object type, and VQ is either volatile or
4785 // empty, there exist candidate operator functions of the form
4786 //
4787 // T*VQ& operator++(T*VQ&);
4788 // T*VQ& operator--(T*VQ&);
4789 // T* operator++(T*VQ&, int);
4790 // T* operator--(T*VQ&, int);
Douglas Gregorfec56e72010-11-03 17:00:07 +00004791 for (BuiltinCandidateTypeSet::iterator
4792 Ptr = CandidateTypes[0].pointer_begin(),
4793 PtrEnd = CandidateTypes[0].pointer_end();
4794 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor74253732008-11-19 15:42:04 +00004795 // Skip pointer types that aren't pointers to object types.
Eli Friedman13578692010-08-05 02:49:48 +00004796 if (!(*Ptr)->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00004797 continue;
4798
Mike Stump1eb44332009-09-09 15:08:12 +00004799 QualType ParamTypes[2] = {
4800 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00004801 };
Mike Stump1eb44332009-09-09 15:08:12 +00004802
Douglas Gregor74253732008-11-19 15:42:04 +00004803 // Without volatile
4804 if (NumArgs == 1)
4805 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4806 else
4807 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4808
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004809 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4810 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00004811 // With volatile
John McCall0953e762009-09-24 19:53:00 +00004812 ParamTypes[0]
4813 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor74253732008-11-19 15:42:04 +00004814 if (NumArgs == 1)
4815 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4816 else
4817 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4818 }
4819 }
4820 break;
4821
4822 UnaryStar:
4823 // C++ [over.built]p6:
4824 // For every cv-qualified or cv-unqualified object type T, there
4825 // exist candidate operator functions of the form
4826 //
4827 // T& operator*(T*);
4828 //
4829 // C++ [over.built]p7:
4830 // For every function type T, there exist candidate operator
4831 // functions of the form
4832 // T& operator*(T*);
Douglas Gregorfec56e72010-11-03 17:00:07 +00004833 for (BuiltinCandidateTypeSet::iterator
4834 Ptr = CandidateTypes[0].pointer_begin(),
4835 PtrEnd = CandidateTypes[0].pointer_end();
4836 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor74253732008-11-19 15:42:04 +00004837 QualType ParamTy = *Ptr;
Argyrios Kyrtzidis42d0f2a2010-08-23 07:12:16 +00004838 QualType PointeeTy = ParamTy->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004839 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00004840 &ParamTy, Args, 1, CandidateSet);
4841 }
4842 break;
4843
4844 UnaryPlus:
4845 // C++ [over.built]p8:
4846 // For every type T, there exist candidate operator functions of
4847 // the form
4848 //
4849 // T* operator+(T*);
Douglas Gregorfec56e72010-11-03 17:00:07 +00004850 for (BuiltinCandidateTypeSet::iterator
4851 Ptr = CandidateTypes[0].pointer_begin(),
4852 PtrEnd = CandidateTypes[0].pointer_end();
4853 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor74253732008-11-19 15:42:04 +00004854 QualType ParamTy = *Ptr;
4855 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4856 }
Mike Stump1eb44332009-09-09 15:08:12 +00004857
Douglas Gregor74253732008-11-19 15:42:04 +00004858 // Fall through
4859
4860 UnaryMinus:
4861 // C++ [over.built]p9:
4862 // For every promoted arithmetic type T, there exist candidate
4863 // operator functions of the form
4864 //
4865 // T operator+(T);
4866 // T operator-(T);
Mike Stump1eb44332009-09-09 15:08:12 +00004867 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor74253732008-11-19 15:42:04 +00004868 Arith < LastPromotedArithmeticType; ++Arith) {
John McCall72a01412010-11-13 02:01:09 +00004869 QualType ArithTy = Context.*ArithmeticTypes[Arith];
Douglas Gregor74253732008-11-19 15:42:04 +00004870 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4871 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004872
4873 // Extension: We also add these operators for vector types.
Douglas Gregorfec56e72010-11-03 17:00:07 +00004874 for (BuiltinCandidateTypeSet::iterator
4875 Vec = CandidateTypes[0].vector_begin(),
4876 VecEnd = CandidateTypes[0].vector_end();
Douglas Gregor26bcf672010-05-19 03:21:00 +00004877 Vec != VecEnd; ++Vec) {
4878 QualType VecTy = *Vec;
4879 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4880 }
Douglas Gregor74253732008-11-19 15:42:04 +00004881 break;
4882
4883 case OO_Tilde:
4884 // C++ [over.built]p10:
4885 // For every promoted integral type T, there exist candidate
4886 // operator functions of the form
4887 //
4888 // T operator~(T);
Mike Stump1eb44332009-09-09 15:08:12 +00004889 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor74253732008-11-19 15:42:04 +00004890 Int < LastPromotedIntegralType; ++Int) {
John McCall72a01412010-11-13 02:01:09 +00004891 QualType IntTy = Context.*ArithmeticTypes[Int];
Douglas Gregor74253732008-11-19 15:42:04 +00004892 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4893 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004894
4895 // Extension: We also add this operator for vector types.
Douglas Gregorfec56e72010-11-03 17:00:07 +00004896 for (BuiltinCandidateTypeSet::iterator
4897 Vec = CandidateTypes[0].vector_begin(),
4898 VecEnd = CandidateTypes[0].vector_end();
Douglas Gregor26bcf672010-05-19 03:21:00 +00004899 Vec != VecEnd; ++Vec) {
4900 QualType VecTy = *Vec;
4901 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4902 }
Douglas Gregor74253732008-11-19 15:42:04 +00004903 break;
4904
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004905 case OO_New:
4906 case OO_Delete:
4907 case OO_Array_New:
4908 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004909 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00004910 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004911 break;
4912
4913 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00004914 UnaryAmp:
4915 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004916 // C++ [over.match.oper]p3:
4917 // -- For the operator ',', the unary operator '&', or the
4918 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004919 break;
4920
Douglas Gregor19b7b152009-08-24 13:43:27 +00004921 case OO_EqualEqual:
4922 case OO_ExclaimEqual:
4923 // C++ [over.match.oper]p16:
Mike Stump1eb44332009-09-09 15:08:12 +00004924 // For every pointer to member type T, there exist candidate operator
4925 // functions of the form
Douglas Gregor19b7b152009-08-24 13:43:27 +00004926 //
4927 // bool operator==(T,T);
4928 // bool operator!=(T,T);
Douglas Gregorfec56e72010-11-03 17:00:07 +00004929 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4930 for (BuiltinCandidateTypeSet::iterator
4931 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
4932 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
4933 MemPtr != MemPtrEnd;
4934 ++MemPtr) {
4935 // Don't add the same builtin candidate twice.
4936 if (!AddedTypes.insert(Context.getCanonicalType(*MemPtr)))
4937 continue;
4938
4939 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4940 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4941 }
Douglas Gregor19b7b152009-08-24 13:43:27 +00004942 }
Douglas Gregorfec56e72010-11-03 17:00:07 +00004943 AddedTypes.clear();
4944
Douglas Gregor19b7b152009-08-24 13:43:27 +00004945 // Fall through
Mike Stump1eb44332009-09-09 15:08:12 +00004946
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004947 case OO_Less:
4948 case OO_Greater:
4949 case OO_LessEqual:
4950 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004951 // C++ [over.built]p15:
4952 //
4953 // For every pointer or enumeration type T, there exist
4954 // candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004955 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004956 // bool operator<(T, T);
4957 // bool operator>(T, T);
4958 // bool operator<=(T, T);
4959 // bool operator>=(T, T);
4960 // bool operator==(T, T);
4961 // bool operator!=(T, T);
Douglas Gregorfec56e72010-11-03 17:00:07 +00004962 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4963 for (BuiltinCandidateTypeSet::iterator
4964 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
4965 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
4966 Ptr != PtrEnd; ++Ptr) {
4967 // Don't add the same builtin candidate twice.
4968 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
4969 continue;
4970
4971 QualType ParamTypes[2] = { *Ptr, *Ptr };
Douglas Gregor661b4932010-09-12 04:28:07 +00004972 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorfec56e72010-11-03 17:00:07 +00004973 }
4974 for (BuiltinCandidateTypeSet::iterator
4975 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
4976 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
4977 Enum != EnumEnd; ++Enum) {
4978 // Don't add the same builtin candidate twice.
4979 if (!AddedTypes.insert(Context.getCanonicalType(*Enum)))
4980 continue;
4981
4982 QualType ParamTypes[2] = { *Enum, *Enum };
4983 CanQualType CanonType = Context.getCanonicalType(*Enum);
4984 if (!UserDefinedBinaryOperators.count(
4985 std::make_pair(CanonType, CanonType)))
4986 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4987 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004988 }
Douglas Gregorfec56e72010-11-03 17:00:07 +00004989 AddedTypes.clear();
4990
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004991 // Fall through.
4992 isComparison = true;
4993
Douglas Gregor74253732008-11-19 15:42:04 +00004994 BinaryPlus:
4995 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004996 if (!isComparison) {
4997 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4998
4999 // C++ [over.built]p13:
5000 //
5001 // For every cv-qualified or cv-unqualified object type T
5002 // there exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00005003 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005004 // T* operator+(T*, ptrdiff_t);
5005 // T& operator[](T*, ptrdiff_t); [BELOW]
5006 // T* operator-(T*, ptrdiff_t);
5007 // T* operator+(ptrdiff_t, T*);
5008 // T& operator[](ptrdiff_t, T*); [BELOW]
5009 //
5010 // C++ [over.built]p14:
5011 //
5012 // For every T, where T is a pointer to object type, there
5013 // exist candidate operator functions of the form
5014 //
5015 // ptrdiff_t operator-(T, T);
Douglas Gregorfec56e72010-11-03 17:00:07 +00005016 for (BuiltinCandidateTypeSet::iterator
5017 Ptr = CandidateTypes[0].pointer_begin(),
5018 PtrEnd = CandidateTypes[0].pointer_end();
5019 Ptr != PtrEnd; ++Ptr) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005020 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
5021
5022 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5023 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5024
Douglas Gregorfec56e72010-11-03 17:00:07 +00005025 if (Op == OO_Minus) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005026 // ptrdiff_t operator-(T, T);
Douglas Gregorfec56e72010-11-03 17:00:07 +00005027 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5028 continue;
5029
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005030 ParamTypes[1] = *Ptr;
5031 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
5032 Args, 2, CandidateSet);
5033 }
5034 }
Douglas Gregorfec56e72010-11-03 17:00:07 +00005035
5036 for (BuiltinCandidateTypeSet::iterator
5037 Ptr = CandidateTypes[1].pointer_begin(),
5038 PtrEnd = CandidateTypes[1].pointer_end();
5039 Ptr != PtrEnd; ++Ptr) {
5040 if (Op == OO_Plus) {
5041 // T* operator+(ptrdiff_t, T*);
5042 QualType ParamTypes[2] = { Context.getPointerDiffType(), *Ptr };
5043 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5044 } else {
5045 // ptrdiff_t operator-(T, T);
5046 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5047 continue;
5048
5049 QualType ParamTypes[2] = { *Ptr, *Ptr };
5050 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
5051 Args, 2, CandidateSet);
5052 }
5053 }
5054
5055 AddedTypes.clear();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005056 }
5057 // Fall through
5058
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005059 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00005060 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005061 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005062 // C++ [over.built]p12:
5063 //
5064 // For every pair of promoted arithmetic types L and R, there
5065 // exist candidate operator functions of the form
5066 //
5067 // LR operator*(L, R);
5068 // LR operator/(L, R);
5069 // LR operator+(L, R);
5070 // LR operator-(L, R);
5071 // bool operator<(L, R);
5072 // bool operator>(L, R);
5073 // bool operator<=(L, R);
5074 // bool operator>=(L, R);
5075 // bool operator==(L, R);
5076 // bool operator!=(L, R);
5077 //
5078 // where LR is the result of the usual arithmetic conversions
5079 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005080 //
5081 // C++ [over.built]p24:
5082 //
5083 // For every pair of promoted arithmetic types L and R, there exist
5084 // candidate operator functions of the form
5085 //
5086 // LR operator?(bool, L, R);
5087 //
5088 // where LR is the result of the usual arithmetic conversions
5089 // between types L and R.
5090 // Our candidates ignore the first parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00005091 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005092 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00005093 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005094 Right < LastPromotedArithmeticType; ++Right) {
John McCall72a01412010-11-13 02:01:09 +00005095 QualType LandR[2] = { Context.*ArithmeticTypes[Left],
5096 Context.*ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00005097 QualType Result
5098 = isComparison
5099 ? Context.BoolTy
John McCall00071ec2010-11-13 05:51:15 +00005100 : UsualArithmeticConversionsType::find(Context, Left, Right);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005101 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5102 }
5103 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00005104
5105 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5106 // conditional operator for vector types.
Douglas Gregorfec56e72010-11-03 17:00:07 +00005107 for (BuiltinCandidateTypeSet::iterator
5108 Vec1 = CandidateTypes[0].vector_begin(),
5109 Vec1End = CandidateTypes[0].vector_end();
Douglas Gregor26bcf672010-05-19 03:21:00 +00005110 Vec1 != Vec1End; ++Vec1)
5111 for (BuiltinCandidateTypeSet::iterator
Douglas Gregorfec56e72010-11-03 17:00:07 +00005112 Vec2 = CandidateTypes[1].vector_begin(),
5113 Vec2End = CandidateTypes[1].vector_end();
Douglas Gregor26bcf672010-05-19 03:21:00 +00005114 Vec2 != Vec2End; ++Vec2) {
5115 QualType LandR[2] = { *Vec1, *Vec2 };
5116 QualType Result;
5117 if (isComparison)
5118 Result = Context.BoolTy;
5119 else {
5120 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5121 Result = *Vec1;
5122 else
5123 Result = *Vec2;
5124 }
5125
5126 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5127 }
5128
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005129 break;
5130
5131 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00005132 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005133 case OO_Caret:
5134 case OO_Pipe:
5135 case OO_LessLess:
5136 case OO_GreaterGreater:
5137 // C++ [over.built]p17:
5138 //
5139 // For every pair of promoted integral types L and R, there
5140 // exist candidate operator functions of the form
5141 //
5142 // LR operator%(L, R);
5143 // LR operator&(L, R);
5144 // LR operator^(L, R);
5145 // LR operator|(L, R);
5146 // L operator<<(L, R);
5147 // L operator>>(L, R);
5148 //
5149 // where LR is the result of the usual arithmetic conversions
5150 // between types L and R.
Mike Stump1eb44332009-09-09 15:08:12 +00005151 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005152 Left < LastPromotedIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00005153 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005154 Right < LastPromotedIntegralType; ++Right) {
John McCall72a01412010-11-13 02:01:09 +00005155 QualType LandR[2] = { Context.*ArithmeticTypes[Left],
5156 Context.*ArithmeticTypes[Right] };
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005157 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5158 ? LandR[0]
John McCall00071ec2010-11-13 05:51:15 +00005159 : UsualArithmeticConversionsType::find(Context, Left, Right);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005160 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5161 }
5162 }
5163 break;
5164
5165 case OO_Equal:
5166 // C++ [over.built]p20:
5167 //
5168 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00005169 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005170 // empty, there exist candidate operator functions of the form
5171 //
5172 // VQ T& operator=(VQ T&, T);
Douglas Gregorfec56e72010-11-03 17:00:07 +00005173 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5174 for (BuiltinCandidateTypeSet::iterator
5175 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5176 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5177 Enum != EnumEnd; ++Enum) {
5178 if (!AddedTypes.insert(Context.getCanonicalType(*Enum)))
5179 continue;
5180
5181 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
5182 CandidateSet);
5183 }
5184
5185 for (BuiltinCandidateTypeSet::iterator
5186 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5187 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5188 MemPtr != MemPtrEnd; ++MemPtr) {
5189 if (!AddedTypes.insert(Context.getCanonicalType(*MemPtr)))
5190 continue;
5191
5192 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
5193 CandidateSet);
5194 }
5195 }
5196 AddedTypes.clear();
Douglas Gregor26bcf672010-05-19 03:21:00 +00005197
5198 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005199
5200 case OO_PlusEqual:
5201 case OO_MinusEqual:
5202 // C++ [over.built]p19:
5203 //
5204 // For every pair (T, VQ), where T is any type and VQ is either
5205 // volatile or empty, there exist candidate operator functions
5206 // of the form
5207 //
5208 // T*VQ& operator=(T*VQ&, T*);
5209 //
5210 // C++ [over.built]p21:
5211 //
5212 // For every pair (T, VQ), where T is a cv-qualified or
5213 // cv-unqualified object type and VQ is either volatile or
5214 // empty, there exist candidate operator functions of the form
5215 //
5216 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5217 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
Douglas Gregorfec56e72010-11-03 17:00:07 +00005218 for (BuiltinCandidateTypeSet::iterator
5219 Ptr = CandidateTypes[0].pointer_begin(),
5220 PtrEnd = CandidateTypes[0].pointer_end();
5221 Ptr != PtrEnd; ++Ptr) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005222 QualType ParamTypes[2];
5223 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
5224
Douglas Gregorfec56e72010-11-03 17:00:07 +00005225 // If this is operator=, keep track of the builtin candidates we added.
5226 if (Op == OO_Equal)
5227 AddedTypes.insert(Context.getCanonicalType(*Ptr));
5228
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005229 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005230 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005231 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5232 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005233
Fariborz Jahanian8621d012009-10-19 21:30:45 +00005234 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5235 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00005236 // volatile version
John McCall0953e762009-09-24 19:53:00 +00005237 ParamTypes[0]
5238 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005239 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5240 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00005241 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005242 }
Douglas Gregorfec56e72010-11-03 17:00:07 +00005243
5244 if (Op == OO_Equal) {
5245 for (BuiltinCandidateTypeSet::iterator
5246 Ptr = CandidateTypes[1].pointer_begin(),
5247 PtrEnd = CandidateTypes[1].pointer_end();
5248 Ptr != PtrEnd; ++Ptr) {
5249 // Make sure we don't add the same candidate twice.
5250 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5251 continue;
5252
5253 QualType ParamTypes[2] = { Context.getLValueReferenceType(*Ptr), *Ptr };
5254
5255 // non-volatile version
5256 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5257 /*IsAssigmentOperator=*/true);
5258
5259 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5260 VisibleTypeConversionsQuals.hasVolatile()) {
5261 // volatile version
5262 ParamTypes[0]
5263 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
5264 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5265 /*IsAssigmentOperator=*/true);
5266 }
5267 }
5268 AddedTypes.clear();
5269 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005270 // Fall through.
5271
5272 case OO_StarEqual:
5273 case OO_SlashEqual:
5274 // C++ [over.built]p18:
5275 //
5276 // For every triple (L, VQ, R), where L is an arithmetic type,
5277 // VQ is either volatile or empty, and R is a promoted
5278 // arithmetic type, there exist candidate operator functions of
5279 // the form
5280 //
5281 // VQ L& operator=(VQ L&, R);
5282 // VQ L& operator*=(VQ L&, R);
5283 // VQ L& operator/=(VQ L&, R);
5284 // VQ L& operator+=(VQ L&, R);
5285 // VQ L& operator-=(VQ L&, R);
5286 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00005287 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005288 Right < LastPromotedArithmeticType; ++Right) {
5289 QualType ParamTypes[2];
John McCall72a01412010-11-13 02:01:09 +00005290 ParamTypes[1] = Context.*ArithmeticTypes[Right];
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005291
5292 // Add this built-in operator as a candidate (VQ is empty).
John McCall72a01412010-11-13 02:01:09 +00005293 ParamTypes[0] =
5294 Context.getLValueReferenceType(Context.*ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005295 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5296 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005297
5298 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanian8621d012009-10-19 21:30:45 +00005299 if (VisibleTypeConversionsQuals.hasVolatile()) {
John McCall72a01412010-11-13 02:01:09 +00005300 ParamTypes[0] =
5301 Context.getVolatileType(Context.*ArithmeticTypes[Left]);
Fariborz Jahanian8621d012009-10-19 21:30:45 +00005302 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5303 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5304 /*IsAssigmentOperator=*/Op == OO_Equal);
5305 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005306 }
5307 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00005308
5309 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
Douglas Gregorfec56e72010-11-03 17:00:07 +00005310 for (BuiltinCandidateTypeSet::iterator
5311 Vec1 = CandidateTypes[0].vector_begin(),
5312 Vec1End = CandidateTypes[0].vector_end();
Douglas Gregor26bcf672010-05-19 03:21:00 +00005313 Vec1 != Vec1End; ++Vec1)
5314 for (BuiltinCandidateTypeSet::iterator
Douglas Gregorfec56e72010-11-03 17:00:07 +00005315 Vec2 = CandidateTypes[1].vector_begin(),
5316 Vec2End = CandidateTypes[1].vector_end();
Douglas Gregor26bcf672010-05-19 03:21:00 +00005317 Vec2 != Vec2End; ++Vec2) {
5318 QualType ParamTypes[2];
5319 ParamTypes[1] = *Vec2;
5320 // Add this built-in operator as a candidate (VQ is empty).
5321 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
5322 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5323 /*IsAssigmentOperator=*/Op == OO_Equal);
5324
5325 // Add this built-in operator as a candidate (VQ is 'volatile').
5326 if (VisibleTypeConversionsQuals.hasVolatile()) {
5327 ParamTypes[0] = Context.getVolatileType(*Vec1);
5328 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5329 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5330 /*IsAssigmentOperator=*/Op == OO_Equal);
5331 }
5332 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005333 break;
5334
5335 case OO_PercentEqual:
5336 case OO_LessLessEqual:
5337 case OO_GreaterGreaterEqual:
5338 case OO_AmpEqual:
5339 case OO_CaretEqual:
5340 case OO_PipeEqual:
5341 // C++ [over.built]p22:
5342 //
5343 // For every triple (L, VQ, R), where L is an integral type, VQ
5344 // is either volatile or empty, and R is a promoted integral
5345 // type, there exist candidate operator functions of the form
5346 //
5347 // VQ L& operator%=(VQ L&, R);
5348 // VQ L& operator<<=(VQ L&, R);
5349 // VQ L& operator>>=(VQ L&, R);
5350 // VQ L& operator&=(VQ L&, R);
5351 // VQ L& operator^=(VQ L&, R);
5352 // VQ L& operator|=(VQ L&, R);
5353 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00005354 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005355 Right < LastPromotedIntegralType; ++Right) {
5356 QualType ParamTypes[2];
John McCall72a01412010-11-13 02:01:09 +00005357 ParamTypes[1] = Context.*ArithmeticTypes[Right];
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005358
5359 // Add this built-in operator as a candidate (VQ is empty).
John McCall72a01412010-11-13 02:01:09 +00005360 ParamTypes[0] =
5361 Context.getLValueReferenceType(Context.*ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005362 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian035c46f2009-10-20 00:04:40 +00005363 if (VisibleTypeConversionsQuals.hasVolatile()) {
5364 // Add this built-in operator as a candidate (VQ is 'volatile').
John McCall72a01412010-11-13 02:01:09 +00005365 ParamTypes[0] = Context.*ArithmeticTypes[Left];
Fariborz Jahanian035c46f2009-10-20 00:04:40 +00005366 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
5367 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5368 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5369 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005370 }
5371 }
5372 break;
5373
Douglas Gregor74253732008-11-19 15:42:04 +00005374 case OO_Exclaim: {
5375 // C++ [over.operator]p23:
5376 //
5377 // There also exist candidate operator functions of the form
5378 //
Mike Stump1eb44332009-09-09 15:08:12 +00005379 // bool operator!(bool);
Douglas Gregor74253732008-11-19 15:42:04 +00005380 // bool operator&&(bool, bool); [BELOW]
5381 // bool operator||(bool, bool); [BELOW]
5382 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005383 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5384 /*IsAssignmentOperator=*/false,
5385 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00005386 break;
5387 }
5388
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005389 case OO_AmpAmp:
5390 case OO_PipePipe: {
5391 // C++ [over.operator]p23:
5392 //
5393 // There also exist candidate operator functions of the form
5394 //
Douglas Gregor74253732008-11-19 15:42:04 +00005395 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005396 // bool operator&&(bool, bool);
5397 // bool operator||(bool, bool);
5398 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005399 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5400 /*IsAssignmentOperator=*/false,
5401 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005402 break;
5403 }
5404
5405 case OO_Subscript:
5406 // C++ [over.built]p13:
5407 //
5408 // For every cv-qualified or cv-unqualified object type T there
5409 // exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00005410 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005411 // T* operator+(T*, ptrdiff_t); [ABOVE]
5412 // T& operator[](T*, ptrdiff_t);
5413 // T* operator-(T*, ptrdiff_t); [ABOVE]
5414 // T* operator+(ptrdiff_t, T*); [ABOVE]
5415 // T& operator[](ptrdiff_t, T*);
Douglas Gregorfec56e72010-11-03 17:00:07 +00005416 for (BuiltinCandidateTypeSet::iterator
5417 Ptr = CandidateTypes[0].pointer_begin(),
5418 PtrEnd = CandidateTypes[0].pointer_end();
5419 Ptr != PtrEnd; ++Ptr) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005420 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Argyrios Kyrtzidis42d0f2a2010-08-23 07:12:16 +00005421 QualType PointeeType = (*Ptr)->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005422 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005423
5424 // T& operator[](T*, ptrdiff_t)
5425 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorfec56e72010-11-03 17:00:07 +00005426 }
5427
5428 for (BuiltinCandidateTypeSet::iterator
5429 Ptr = CandidateTypes[1].pointer_begin(),
5430 PtrEnd = CandidateTypes[1].pointer_end();
5431 Ptr != PtrEnd; ++Ptr) {
5432 QualType ParamTypes[2] = { Context.getPointerDiffType(), *Ptr };
5433 QualType PointeeType = (*Ptr)->getPointeeType();
5434 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
5435
5436 // T& operator[](ptrdiff_t, T*)
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005437 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorfec56e72010-11-03 17:00:07 +00005438 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005439 break;
5440
5441 case OO_ArrowStar:
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005442 // C++ [over.built]p11:
5443 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5444 // C1 is the same type as C2 or is a derived class of C2, T is an object
5445 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5446 // there exist candidate operator functions of the form
Douglas Gregorfec56e72010-11-03 17:00:07 +00005447 //
5448 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5449 //
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005450 // where CV12 is the union of CV1 and CV2.
5451 {
Douglas Gregorfec56e72010-11-03 17:00:07 +00005452 for (BuiltinCandidateTypeSet::iterator
5453 Ptr = CandidateTypes[0].pointer_begin(),
5454 PtrEnd = CandidateTypes[0].pointer_end();
5455 Ptr != PtrEnd; ++Ptr) {
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005456 QualType C1Ty = (*Ptr);
5457 QualType C1;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00005458 QualifierCollector Q1;
Argyrios Kyrtzidis42d0f2a2010-08-23 07:12:16 +00005459 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5460 if (!isa<RecordType>(C1))
5461 continue;
5462 // heuristic to reduce number of builtin candidates in the set.
5463 // Add volatile/restrict version only if there are conversions to a
5464 // volatile/restrict type.
5465 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5466 continue;
5467 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5468 continue;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005469 for (BuiltinCandidateTypeSet::iterator
Douglas Gregorfec56e72010-11-03 17:00:07 +00005470 MemPtr = CandidateTypes[1].member_pointer_begin(),
5471 MemPtrEnd = CandidateTypes[1].member_pointer_end();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005472 MemPtr != MemPtrEnd; ++MemPtr) {
5473 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5474 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian43036972009-10-07 16:56:50 +00005475 C2 = C2.getUnqualifiedType();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005476 if (C1 != C2 && !IsDerivedFrom(C1, C2))
5477 break;
5478 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5479 // build CV12 T&
5480 QualType T = mptr->getPointeeType();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005481 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5482 T.isVolatileQualified())
5483 continue;
5484 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5485 T.isRestrictQualified())
5486 continue;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00005487 T = Q1.apply(T);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005488 QualType ResultTy = Context.getLValueReferenceType(T);
5489 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5490 }
5491 }
5492 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005493 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005494
5495 case OO_Conditional:
5496 // Note that we don't consider the first argument, since it has been
5497 // contextually converted to bool long ago. The candidates below are
5498 // therefore added as binary.
5499 //
Douglas Gregor5a1f97e2010-10-15 00:50:56 +00005500 // C++ [over.built]p25:
5501 // For every type T, where T is a pointer, pointer-to-member, or scoped
5502 // enumeration type, there exist candidate operator functions of the form
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005503 //
5504 // T operator?(bool, T, T);
5505 //
Douglas Gregorfec56e72010-11-03 17:00:07 +00005506 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5507 for (BuiltinCandidateTypeSet::iterator
5508 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5509 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5510 Ptr != PtrEnd; ++Ptr) {
5511 if (!AddedTypes.insert(Context.getCanonicalType(*Ptr)))
5512 continue;
5513
5514 QualType ParamTypes[2] = { *Ptr, *Ptr };
5515 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5516 }
5517
5518 for (BuiltinCandidateTypeSet::iterator
5519 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5520 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5521 MemPtr != MemPtrEnd; ++MemPtr) {
5522 if (!AddedTypes.insert(Context.getCanonicalType(*MemPtr)))
5523 continue;
5524
5525 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5526 AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
5527 }
5528
5529 if (getLangOptions().CPlusPlus0x) {
5530 for (BuiltinCandidateTypeSet::iterator
5531 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5532 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5533 Enum != EnumEnd; ++Enum) {
5534 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
5535 continue;
5536
5537 if (!AddedTypes.insert(Context.getCanonicalType(*Enum)))
5538 continue;
5539
5540 QualType ParamTypes[2] = { *Enum, *Enum };
5541 AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
5542 }
5543 }
Douglas Gregor5a1f97e2010-10-15 00:50:56 +00005544 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005545 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005546 }
5547}
5548
Douglas Gregorfa047642009-02-04 00:32:51 +00005549/// \brief Add function candidates found via argument-dependent lookup
5550/// to the set of overloading candidates.
5551///
5552/// This routine performs argument-dependent name lookup based on the
5553/// given function name (which may also be an operator name) and adds
5554/// all of the overload candidates found by ADL to the overload
5555/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00005556void
Douglas Gregorfa047642009-02-04 00:32:51 +00005557Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00005558 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00005559 Expr **Args, unsigned NumArgs,
John McCalld5532b62009-11-23 01:53:49 +00005560 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005561 OverloadCandidateSet& CandidateSet,
5562 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00005563 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00005564
John McCalla113e722010-01-26 06:04:06 +00005565 // FIXME: This approach for uniquing ADL results (and removing
5566 // redundant candidates from the set) relies on pointer-equality,
5567 // which means we need to key off the canonical decl. However,
5568 // always going back to the canonical decl might not get us the
5569 // right set of default arguments. What default arguments are
5570 // we supposed to consider on ADL candidates, anyway?
5571
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005572 // FIXME: Pass in the explicit template arguments?
John McCall7edb5fd2010-01-26 07:16:45 +00005573 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00005574
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005575 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005576 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5577 CandEnd = CandidateSet.end();
5578 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00005579 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00005580 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00005581 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00005582 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00005583 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005584
5585 // For each of the ADL candidates we found, add it to the overload
5586 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00005587 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00005588 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00005589 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00005590 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005591 continue;
5592
John McCall9aa472c2010-03-19 07:35:19 +00005593 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00005594 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005595 } else
John McCall6e266892010-01-26 03:27:55 +00005596 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00005597 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00005598 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00005599 }
Douglas Gregorfa047642009-02-04 00:32:51 +00005600}
5601
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005602/// isBetterOverloadCandidate - Determines whether the first overload
5603/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00005604bool
John McCall120d63c2010-08-24 20:38:10 +00005605isBetterOverloadCandidate(Sema &S,
5606 const OverloadCandidate& Cand1,
5607 const OverloadCandidate& Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005608 SourceLocation Loc,
5609 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005610 // Define viable functions to be better candidates than non-viable
5611 // functions.
5612 if (!Cand2.Viable)
5613 return Cand1.Viable;
5614 else if (!Cand1.Viable)
5615 return false;
5616
Douglas Gregor88a35142008-12-22 05:46:06 +00005617 // C++ [over.match.best]p1:
5618 //
5619 // -- if F is a static member function, ICS1(F) is defined such
5620 // that ICS1(F) is neither better nor worse than ICS1(G) for
5621 // any function G, and, symmetrically, ICS1(G) is neither
5622 // better nor worse than ICS1(F).
5623 unsigned StartArg = 0;
5624 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5625 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005626
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005627 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00005628 // A viable function F1 is defined to be a better function than another
5629 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005630 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005631 unsigned NumArgs = Cand1.Conversions.size();
5632 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5633 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005634 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00005635 switch (CompareImplicitConversionSequences(S,
5636 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005637 Cand2.Conversions[ArgIdx])) {
5638 case ImplicitConversionSequence::Better:
5639 // Cand1 has a better conversion sequence.
5640 HasBetterConversion = true;
5641 break;
5642
5643 case ImplicitConversionSequence::Worse:
5644 // Cand1 can't be better than Cand2.
5645 return false;
5646
5647 case ImplicitConversionSequence::Indistinguishable:
5648 // Do nothing.
5649 break;
5650 }
5651 }
5652
Mike Stump1eb44332009-09-09 15:08:12 +00005653 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005654 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005655 if (HasBetterConversion)
5656 return true;
5657
Mike Stump1eb44332009-09-09 15:08:12 +00005658 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005659 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00005660 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005661 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5662 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005663
5664 // -- F1 and F2 are function template specializations, and the function
5665 // template for F1 is more specialized than the template for F2
5666 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005667 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00005668 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5669 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005670 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00005671 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5672 Cand2.Function->getPrimaryTemplate(),
5673 Loc,
Douglas Gregor5d7d3752009-09-14 23:02:14 +00005674 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5675 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005676 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005677
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005678 // -- the context is an initialization by user-defined conversion
5679 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5680 // from the return type of F1 to the destination type (i.e.,
5681 // the type of the entity being initialized) is a better
5682 // conversion sequence than the standard conversion sequence
5683 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005684 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00005685 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005686 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall120d63c2010-08-24 20:38:10 +00005687 switch (CompareStandardConversionSequences(S,
5688 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005689 Cand2.FinalConversion)) {
5690 case ImplicitConversionSequence::Better:
5691 // Cand1 has a better conversion sequence.
5692 return true;
5693
5694 case ImplicitConversionSequence::Worse:
5695 // Cand1 can't be better than Cand2.
5696 return false;
5697
5698 case ImplicitConversionSequence::Indistinguishable:
5699 // Do nothing
5700 break;
5701 }
5702 }
5703
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005704 return false;
5705}
5706
Mike Stump1eb44332009-09-09 15:08:12 +00005707/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00005708/// within an overload candidate set.
5709///
5710/// \param CandidateSet the set of candidate functions.
5711///
5712/// \param Loc the location of the function name (or operator symbol) for
5713/// which overload resolution occurs.
5714///
Mike Stump1eb44332009-09-09 15:08:12 +00005715/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00005716/// function, Best points to the candidate function found.
5717///
5718/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00005719OverloadingResult
5720OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005721 iterator& Best,
5722 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005723 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00005724 Best = end();
5725 for (iterator Cand = begin(); Cand != end(); ++Cand) {
5726 if (Cand->Viable)
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005727 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
5728 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005729 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005730 }
5731
5732 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00005733 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005734 return OR_No_Viable_Function;
5735
5736 // Make sure that this function is better than every other viable
5737 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00005738 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00005739 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005740 Cand != Best &&
Douglas Gregor8fcc5162010-09-12 08:07:23 +00005741 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
5742 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00005743 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005744 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005745 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005746 }
Mike Stump1eb44332009-09-09 15:08:12 +00005747
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005748 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005749 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00005750 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005751 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005752 return OR_Deleted;
5753
Douglas Gregore0762c92009-06-19 23:52:42 +00005754 // C++ [basic.def.odr]p2:
5755 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00005756 // when referred to from a potentially-evaluated expression. [Note: this
5757 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00005758 // (clause 13), user-defined conversions (12.3.2), allocation function for
5759 // placement new (5.3.4), as well as non-default initialization (8.5).
5760 if (Best->Function)
John McCall120d63c2010-08-24 20:38:10 +00005761 S.MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor9b623632010-10-12 23:32:35 +00005762
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005763 return OR_Success;
5764}
5765
John McCall3c80f572010-01-12 02:15:36 +00005766namespace {
5767
5768enum OverloadCandidateKind {
5769 oc_function,
5770 oc_method,
5771 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00005772 oc_function_template,
5773 oc_method_template,
5774 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00005775 oc_implicit_default_constructor,
5776 oc_implicit_copy_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00005777 oc_implicit_copy_assignment
John McCall3c80f572010-01-12 02:15:36 +00005778};
5779
John McCall220ccbf2010-01-13 00:25:19 +00005780OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5781 FunctionDecl *Fn,
5782 std::string &Description) {
5783 bool isTemplate = false;
5784
5785 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5786 isTemplate = true;
5787 Description = S.getTemplateArgumentBindingsText(
5788 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5789 }
John McCallb1622a12010-01-06 09:43:14 +00005790
5791 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00005792 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00005793 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00005794
John McCall3c80f572010-01-12 02:15:36 +00005795 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5796 : oc_implicit_default_constructor;
John McCallb1622a12010-01-06 09:43:14 +00005797 }
5798
5799 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5800 // This actually gets spelled 'candidate function' for now, but
5801 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00005802 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00005803 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00005804
Douglas Gregor3e9438b2010-09-27 22:37:28 +00005805 assert(Meth->isCopyAssignmentOperator()
John McCallb1622a12010-01-06 09:43:14 +00005806 && "implicit method is not copy assignment operator?");
John McCall3c80f572010-01-12 02:15:36 +00005807 return oc_implicit_copy_assignment;
5808 }
5809
John McCall220ccbf2010-01-13 00:25:19 +00005810 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00005811}
5812
5813} // end anonymous namespace
5814
5815// Notes the location of an overload candidate.
5816void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCall220ccbf2010-01-13 00:25:19 +00005817 std::string FnDesc;
5818 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5819 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5820 << (unsigned) K << FnDesc;
John McCallb1622a12010-01-06 09:43:14 +00005821}
5822
John McCall1d318332010-01-12 00:44:57 +00005823/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5824/// "lead" diagnostic; it will be given two arguments, the source and
5825/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00005826void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
5827 Sema &S,
5828 SourceLocation CaretLoc,
5829 const PartialDiagnostic &PDiag) const {
5830 S.Diag(CaretLoc, PDiag)
5831 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall1d318332010-01-12 00:44:57 +00005832 for (AmbiguousConversionSequence::const_iterator
John McCall120d63c2010-08-24 20:38:10 +00005833 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
5834 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00005835 }
John McCall81201622010-01-08 04:41:39 +00005836}
5837
John McCall1d318332010-01-12 00:44:57 +00005838namespace {
5839
John McCalladbb8f82010-01-13 09:16:55 +00005840void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5841 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5842 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00005843 assert(Cand->Function && "for now, candidate must be a function");
5844 FunctionDecl *Fn = Cand->Function;
5845
5846 // There's a conversion slot for the object argument if this is a
5847 // non-constructor method. Note that 'I' corresponds the
5848 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00005849 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00005850 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00005851 if (I == 0)
5852 isObjectArgument = true;
5853 else
5854 I--;
John McCall220ccbf2010-01-13 00:25:19 +00005855 }
5856
John McCall220ccbf2010-01-13 00:25:19 +00005857 std::string FnDesc;
5858 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5859
John McCalladbb8f82010-01-13 09:16:55 +00005860 Expr *FromExpr = Conv.Bad.FromExpr;
5861 QualType FromTy = Conv.Bad.getFromType();
5862 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00005863
John McCall5920dbb2010-02-02 02:42:52 +00005864 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00005865 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00005866 Expr *E = FromExpr->IgnoreParens();
5867 if (isa<UnaryOperator>(E))
5868 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00005869 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00005870
5871 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5872 << (unsigned) FnKind << FnDesc
5873 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5874 << ToTy << Name << I+1;
5875 return;
5876 }
5877
John McCall258b2032010-01-23 08:10:49 +00005878 // Do some hand-waving analysis to see if the non-viability is due
5879 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00005880 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5881 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5882 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5883 CToTy = RT->getPointeeType();
5884 else {
5885 // TODO: detect and diagnose the full richness of const mismatches.
5886 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5887 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5888 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5889 }
5890
5891 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5892 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5893 // It is dumb that we have to do this here.
5894 while (isa<ArrayType>(CFromTy))
5895 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5896 while (isa<ArrayType>(CToTy))
5897 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5898
5899 Qualifiers FromQs = CFromTy.getQualifiers();
5900 Qualifiers ToQs = CToTy.getQualifiers();
5901
5902 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5903 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5904 << (unsigned) FnKind << FnDesc
5905 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5906 << FromTy
5907 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5908 << (unsigned) isObjectArgument << I+1;
5909 return;
5910 }
5911
5912 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5913 assert(CVR && "unexpected qualifiers mismatch");
5914
5915 if (isObjectArgument) {
5916 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5917 << (unsigned) FnKind << FnDesc
5918 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5919 << FromTy << (CVR - 1);
5920 } else {
5921 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5922 << (unsigned) FnKind << FnDesc
5923 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5924 << FromTy << (CVR - 1) << I+1;
5925 }
5926 return;
5927 }
5928
John McCall258b2032010-01-23 08:10:49 +00005929 // Diagnose references or pointers to incomplete types differently,
5930 // since it's far from impossible that the incompleteness triggered
5931 // the failure.
5932 QualType TempFromTy = FromTy.getNonReferenceType();
5933 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5934 TempFromTy = PTy->getPointeeType();
5935 if (TempFromTy->isIncompleteType()) {
5936 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5937 << (unsigned) FnKind << FnDesc
5938 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5939 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5940 return;
5941 }
5942
Douglas Gregor85789812010-06-30 23:01:39 +00005943 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005944 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00005945 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
5946 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
5947 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5948 FromPtrTy->getPointeeType()) &&
5949 !FromPtrTy->getPointeeType()->isIncompleteType() &&
5950 !ToPtrTy->getPointeeType()->isIncompleteType() &&
5951 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
5952 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005953 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00005954 }
5955 } else if (const ObjCObjectPointerType *FromPtrTy
5956 = FromTy->getAs<ObjCObjectPointerType>()) {
5957 if (const ObjCObjectPointerType *ToPtrTy
5958 = ToTy->getAs<ObjCObjectPointerType>())
5959 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
5960 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
5961 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5962 FromPtrTy->getPointeeType()) &&
5963 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005964 BaseToDerivedConversion = 2;
5965 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
5966 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
5967 !FromTy->isIncompleteType() &&
5968 !ToRefTy->getPointeeType()->isIncompleteType() &&
5969 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
5970 BaseToDerivedConversion = 3;
5971 }
5972
5973 if (BaseToDerivedConversion) {
Douglas Gregor85789812010-06-30 23:01:39 +00005974 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005975 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00005976 << (unsigned) FnKind << FnDesc
5977 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005978 << (BaseToDerivedConversion - 1)
Douglas Gregor85789812010-06-30 23:01:39 +00005979 << FromTy << ToTy << I+1;
5980 return;
5981 }
5982
John McCall651f3ee2010-01-14 03:28:57 +00005983 // TODO: specialize more based on the kind of mismatch
John McCall220ccbf2010-01-13 00:25:19 +00005984 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5985 << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00005986 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalle81e15e2010-01-14 00:56:20 +00005987 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCalladbb8f82010-01-13 09:16:55 +00005988}
5989
5990void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5991 unsigned NumFormalArgs) {
5992 // TODO: treat calls to a missing default constructor as a special case
5993
5994 FunctionDecl *Fn = Cand->Function;
5995 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5996
5997 unsigned MinParams = Fn->getMinRequiredArguments();
5998
5999 // at least / at most / exactly
Douglas Gregora18592e2010-05-08 18:13:28 +00006000 // FIXME: variadic templates "at most" should account for parameter packs
John McCalladbb8f82010-01-13 09:16:55 +00006001 unsigned mode, modeCount;
6002 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00006003 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
6004 (Cand->FailureKind == ovl_fail_bad_deduction &&
6005 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCalladbb8f82010-01-13 09:16:55 +00006006 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
6007 mode = 0; // "at least"
6008 else
6009 mode = 2; // "exactly"
6010 modeCount = MinParams;
6011 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00006012 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
6013 (Cand->FailureKind == ovl_fail_bad_deduction &&
6014 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00006015 if (MinParams != FnTy->getNumArgs())
6016 mode = 1; // "at most"
6017 else
6018 mode = 2; // "exactly"
6019 modeCount = FnTy->getNumArgs();
6020 }
6021
6022 std::string Description;
6023 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6024
6025 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregora18592e2010-05-08 18:13:28 +00006026 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
6027 << modeCount << NumFormalArgs;
John McCall220ccbf2010-01-13 00:25:19 +00006028}
6029
John McCall342fec42010-02-01 18:53:26 +00006030/// Diagnose a failed template-argument deduction.
6031void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6032 Expr **Args, unsigned NumArgs) {
6033 FunctionDecl *Fn = Cand->Function; // pattern
6034
Douglas Gregora9333192010-05-08 17:41:32 +00006035 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00006036 NamedDecl *ParamD;
6037 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
6038 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
6039 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00006040 switch (Cand->DeductionFailure.Result) {
6041 case Sema::TDK_Success:
6042 llvm_unreachable("TDK_success while diagnosing bad deduction");
6043
6044 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00006045 assert(ParamD && "no parameter found for incomplete deduction result");
6046 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
6047 << ParamD->getDeclName();
6048 return;
6049 }
6050
John McCall57e97782010-08-05 09:05:08 +00006051 case Sema::TDK_Underqualified: {
6052 assert(ParamD && "no parameter found for bad qualifiers deduction result");
6053 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
6054
6055 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
6056
6057 // Param will have been canonicalized, but it should just be a
6058 // qualified version of ParamD, so move the qualifiers to that.
6059 QualifierCollector Qs(S.Context);
6060 Qs.strip(Param);
6061 QualType NonCanonParam = Qs.apply(TParam->getTypeForDecl());
6062 assert(S.Context.hasSameType(Param, NonCanonParam));
6063
6064 // Arg has also been canonicalized, but there's nothing we can do
6065 // about that. It also doesn't matter as much, because it won't
6066 // have any template parameters in it (because deduction isn't
6067 // done on dependent types).
6068 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
6069
6070 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
6071 << ParamD->getDeclName() << Arg << NonCanonParam;
6072 return;
6073 }
6074
6075 case Sema::TDK_Inconsistent: {
Douglas Gregorf1a84452010-05-08 19:15:54 +00006076 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00006077 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00006078 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00006079 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00006080 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00006081 which = 1;
6082 else {
Douglas Gregora9333192010-05-08 17:41:32 +00006083 which = 2;
6084 }
6085
6086 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
6087 << which << ParamD->getDeclName()
6088 << *Cand->DeductionFailure.getFirstArg()
6089 << *Cand->DeductionFailure.getSecondArg();
6090 return;
6091 }
Douglas Gregora18592e2010-05-08 18:13:28 +00006092
Douglas Gregorf1a84452010-05-08 19:15:54 +00006093 case Sema::TDK_InvalidExplicitArguments:
6094 assert(ParamD && "no parameter found for invalid explicit arguments");
6095 if (ParamD->getDeclName())
6096 S.Diag(Fn->getLocation(),
6097 diag::note_ovl_candidate_explicit_arg_mismatch_named)
6098 << ParamD->getDeclName();
6099 else {
6100 int index = 0;
6101 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
6102 index = TTP->getIndex();
6103 else if (NonTypeTemplateParmDecl *NTTP
6104 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
6105 index = NTTP->getIndex();
6106 else
6107 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
6108 S.Diag(Fn->getLocation(),
6109 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
6110 << (index + 1);
6111 }
6112 return;
6113
Douglas Gregora18592e2010-05-08 18:13:28 +00006114 case Sema::TDK_TooManyArguments:
6115 case Sema::TDK_TooFewArguments:
6116 DiagnoseArityMismatch(S, Cand, NumArgs);
6117 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00006118
6119 case Sema::TDK_InstantiationDepth:
6120 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
6121 return;
6122
6123 case Sema::TDK_SubstitutionFailure: {
6124 std::string ArgString;
6125 if (TemplateArgumentList *Args
6126 = Cand->DeductionFailure.getTemplateArgumentList())
6127 ArgString = S.getTemplateArgumentBindingsText(
6128 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
6129 *Args);
6130 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
6131 << ArgString;
6132 return;
6133 }
Douglas Gregora9333192010-05-08 17:41:32 +00006134
John McCall342fec42010-02-01 18:53:26 +00006135 // TODO: diagnose these individually, then kill off
6136 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00006137 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00006138 case Sema::TDK_FailedOverloadResolution:
6139 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
6140 return;
6141 }
6142}
6143
6144/// Generates a 'note' diagnostic for an overload candidate. We've
6145/// already generated a primary error at the call site.
6146///
6147/// It really does need to be a single diagnostic with its caret
6148/// pointed at the candidate declaration. Yes, this creates some
6149/// major challenges of technical writing. Yes, this makes pointing
6150/// out problems with specific arguments quite awkward. It's still
6151/// better than generating twenty screens of text for every failed
6152/// overload.
6153///
6154/// It would be great to be able to express per-candidate problems
6155/// more richly for those diagnostic clients that cared, but we'd
6156/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00006157void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
6158 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00006159 FunctionDecl *Fn = Cand->Function;
6160
John McCall81201622010-01-08 04:41:39 +00006161 // Note deleted candidates, but only if they're viable.
John McCall3c80f572010-01-12 02:15:36 +00006162 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCall220ccbf2010-01-13 00:25:19 +00006163 std::string FnDesc;
6164 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00006165
6166 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00006167 << FnKind << FnDesc << Fn->isDeleted();
John McCalla1d7d622010-01-08 00:58:21 +00006168 return;
John McCall81201622010-01-08 04:41:39 +00006169 }
6170
John McCall220ccbf2010-01-13 00:25:19 +00006171 // We don't really have anything else to say about viable candidates.
6172 if (Cand->Viable) {
6173 S.NoteOverloadCandidate(Fn);
6174 return;
6175 }
John McCall1d318332010-01-12 00:44:57 +00006176
John McCalladbb8f82010-01-13 09:16:55 +00006177 switch (Cand->FailureKind) {
6178 case ovl_fail_too_many_arguments:
6179 case ovl_fail_too_few_arguments:
6180 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00006181
John McCalladbb8f82010-01-13 09:16:55 +00006182 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00006183 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
6184
John McCall717e8912010-01-23 05:17:32 +00006185 case ovl_fail_trivial_conversion:
6186 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00006187 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00006188 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00006189
John McCallb1bdc622010-02-25 01:37:24 +00006190 case ovl_fail_bad_conversion: {
6191 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
6192 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00006193 if (Cand->Conversions[I].isBad())
6194 return DiagnoseBadConversion(S, Cand, I);
6195
6196 // FIXME: this currently happens when we're called from SemaInit
6197 // when user-conversion overload fails. Figure out how to handle
6198 // those conditions and diagnose them well.
6199 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00006200 }
John McCallb1bdc622010-02-25 01:37:24 +00006201 }
John McCalla1d7d622010-01-08 00:58:21 +00006202}
6203
6204void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
6205 // Desugar the type of the surrogate down to a function type,
6206 // retaining as many typedefs as possible while still showing
6207 // the function type (and, therefore, its parameter types).
6208 QualType FnType = Cand->Surrogate->getConversionType();
6209 bool isLValueReference = false;
6210 bool isRValueReference = false;
6211 bool isPointer = false;
6212 if (const LValueReferenceType *FnTypeRef =
6213 FnType->getAs<LValueReferenceType>()) {
6214 FnType = FnTypeRef->getPointeeType();
6215 isLValueReference = true;
6216 } else if (const RValueReferenceType *FnTypeRef =
6217 FnType->getAs<RValueReferenceType>()) {
6218 FnType = FnTypeRef->getPointeeType();
6219 isRValueReference = true;
6220 }
6221 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
6222 FnType = FnTypePtr->getPointeeType();
6223 isPointer = true;
6224 }
6225 // Desugar down to a function type.
6226 FnType = QualType(FnType->getAs<FunctionType>(), 0);
6227 // Reconstruct the pointer/reference as appropriate.
6228 if (isPointer) FnType = S.Context.getPointerType(FnType);
6229 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
6230 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
6231
6232 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
6233 << FnType;
6234}
6235
6236void NoteBuiltinOperatorCandidate(Sema &S,
6237 const char *Opc,
6238 SourceLocation OpLoc,
6239 OverloadCandidate *Cand) {
6240 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
6241 std::string TypeStr("operator");
6242 TypeStr += Opc;
6243 TypeStr += "(";
6244 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6245 if (Cand->Conversions.size() == 1) {
6246 TypeStr += ")";
6247 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6248 } else {
6249 TypeStr += ", ";
6250 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6251 TypeStr += ")";
6252 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
6253 }
6254}
6255
6256void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
6257 OverloadCandidate *Cand) {
6258 unsigned NoOperands = Cand->Conversions.size();
6259 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
6260 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00006261 if (ICS.isBad()) break; // all meaningless after first invalid
6262 if (!ICS.isAmbiguous()) continue;
6263
John McCall120d63c2010-08-24 20:38:10 +00006264 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00006265 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00006266 }
6267}
6268
John McCall1b77e732010-01-15 23:32:50 +00006269SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
6270 if (Cand->Function)
6271 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00006272 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00006273 return Cand->Surrogate->getLocation();
6274 return SourceLocation();
6275}
6276
John McCallbf65c0b2010-01-12 00:48:53 +00006277struct CompareOverloadCandidatesForDisplay {
6278 Sema &S;
6279 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00006280
6281 bool operator()(const OverloadCandidate *L,
6282 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00006283 // Fast-path this check.
6284 if (L == R) return false;
6285
John McCall81201622010-01-08 04:41:39 +00006286 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00006287 if (L->Viable) {
6288 if (!R->Viable) return true;
6289
6290 // TODO: introduce a tri-valued comparison for overload
6291 // candidates. Would be more worthwhile if we had a sort
6292 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00006293 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6294 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00006295 } else if (R->Viable)
6296 return false;
John McCall81201622010-01-08 04:41:39 +00006297
John McCall1b77e732010-01-15 23:32:50 +00006298 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00006299
John McCall1b77e732010-01-15 23:32:50 +00006300 // Criteria by which we can sort non-viable candidates:
6301 if (!L->Viable) {
6302 // 1. Arity mismatches come after other candidates.
6303 if (L->FailureKind == ovl_fail_too_many_arguments ||
6304 L->FailureKind == ovl_fail_too_few_arguments)
6305 return false;
6306 if (R->FailureKind == ovl_fail_too_many_arguments ||
6307 R->FailureKind == ovl_fail_too_few_arguments)
6308 return true;
John McCall81201622010-01-08 04:41:39 +00006309
John McCall717e8912010-01-23 05:17:32 +00006310 // 2. Bad conversions come first and are ordered by the number
6311 // of bad conversions and quality of good conversions.
6312 if (L->FailureKind == ovl_fail_bad_conversion) {
6313 if (R->FailureKind != ovl_fail_bad_conversion)
6314 return true;
6315
6316 // If there's any ordering between the defined conversions...
6317 // FIXME: this might not be transitive.
6318 assert(L->Conversions.size() == R->Conversions.size());
6319
6320 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00006321 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6322 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00006323 switch (CompareImplicitConversionSequences(S,
6324 L->Conversions[I],
6325 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00006326 case ImplicitConversionSequence::Better:
6327 leftBetter++;
6328 break;
6329
6330 case ImplicitConversionSequence::Worse:
6331 leftBetter--;
6332 break;
6333
6334 case ImplicitConversionSequence::Indistinguishable:
6335 break;
6336 }
6337 }
6338 if (leftBetter > 0) return true;
6339 if (leftBetter < 0) return false;
6340
6341 } else if (R->FailureKind == ovl_fail_bad_conversion)
6342 return false;
6343
John McCall1b77e732010-01-15 23:32:50 +00006344 // TODO: others?
6345 }
6346
6347 // Sort everything else by location.
6348 SourceLocation LLoc = GetLocationForCandidate(L);
6349 SourceLocation RLoc = GetLocationForCandidate(R);
6350
6351 // Put candidates without locations (e.g. builtins) at the end.
6352 if (LLoc.isInvalid()) return false;
6353 if (RLoc.isInvalid()) return true;
6354
6355 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00006356 }
6357};
6358
John McCall717e8912010-01-23 05:17:32 +00006359/// CompleteNonViableCandidate - Normally, overload resolution only
6360/// computes up to the first
6361void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6362 Expr **Args, unsigned NumArgs) {
6363 assert(!Cand->Viable);
6364
6365 // Don't do anything on failures other than bad conversion.
6366 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6367
6368 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00006369 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCall717e8912010-01-23 05:17:32 +00006370 unsigned ConvCount = Cand->Conversions.size();
6371 while (true) {
6372 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6373 ConvIdx++;
6374 if (Cand->Conversions[ConvIdx - 1].isBad())
6375 break;
6376 }
6377
6378 if (ConvIdx == ConvCount)
6379 return;
6380
John McCallb1bdc622010-02-25 01:37:24 +00006381 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6382 "remaining conversion is initialized?");
6383
Douglas Gregor23ef6c02010-04-16 17:45:54 +00006384 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00006385 // operation somehow.
6386 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00006387
6388 const FunctionProtoType* Proto;
6389 unsigned ArgIdx = ConvIdx;
6390
6391 if (Cand->IsSurrogate) {
6392 QualType ConvType
6393 = Cand->Surrogate->getConversionType().getNonReferenceType();
6394 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6395 ConvType = ConvPtrType->getPointeeType();
6396 Proto = ConvType->getAs<FunctionProtoType>();
6397 ArgIdx--;
6398 } else if (Cand->Function) {
6399 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6400 if (isa<CXXMethodDecl>(Cand->Function) &&
6401 !isa<CXXConstructorDecl>(Cand->Function))
6402 ArgIdx--;
6403 } else {
6404 // Builtin binary operator with a bad first conversion.
6405 assert(ConvCount <= 3);
6406 for (; ConvIdx != ConvCount; ++ConvIdx)
6407 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006408 = TryCopyInitialization(S, Args[ConvIdx],
6409 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6410 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00006411 /*InOverloadResolution*/ true);
John McCall717e8912010-01-23 05:17:32 +00006412 return;
6413 }
6414
6415 // Fill in the rest of the conversions.
6416 unsigned NumArgsInProto = Proto->getNumArgs();
6417 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6418 if (ArgIdx < NumArgsInProto)
6419 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006420 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6421 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00006422 /*InOverloadResolution=*/true);
John McCall717e8912010-01-23 05:17:32 +00006423 else
6424 Cand->Conversions[ConvIdx].setEllipsis();
6425 }
6426}
6427
John McCalla1d7d622010-01-08 00:58:21 +00006428} // end anonymous namespace
6429
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006430/// PrintOverloadCandidates - When overload resolution fails, prints
6431/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00006432/// set.
John McCall120d63c2010-08-24 20:38:10 +00006433void OverloadCandidateSet::NoteCandidates(Sema &S,
6434 OverloadCandidateDisplayKind OCD,
6435 Expr **Args, unsigned NumArgs,
6436 const char *Opc,
6437 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00006438 // Sort the candidates by viability and position. Sorting directly would
6439 // be prohibitive, so we make a set of pointers and sort those.
6440 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00006441 if (OCD == OCD_AllCandidates) Cands.reserve(size());
6442 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00006443 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00006444 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00006445 else if (OCD == OCD_AllCandidates) {
John McCall120d63c2010-08-24 20:38:10 +00006446 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006447 if (Cand->Function || Cand->IsSurrogate)
6448 Cands.push_back(Cand);
6449 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6450 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00006451 }
6452 }
6453
John McCallbf65c0b2010-01-12 00:48:53 +00006454 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00006455 CompareOverloadCandidatesForDisplay(S));
John McCall81201622010-01-08 04:41:39 +00006456
John McCall1d318332010-01-12 00:44:57 +00006457 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00006458
John McCall81201622010-01-08 04:41:39 +00006459 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall120d63c2010-08-24 20:38:10 +00006460 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006461 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00006462 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6463 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00006464
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006465 // Set an arbitrary limit on the number of candidate functions we'll spam
6466 // the user with. FIXME: This limit should depend on details of the
6467 // candidate list.
6468 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6469 break;
6470 }
6471 ++CandsShown;
6472
John McCalla1d7d622010-01-08 00:58:21 +00006473 if (Cand->Function)
John McCall120d63c2010-08-24 20:38:10 +00006474 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00006475 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00006476 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006477 else {
6478 assert(Cand->Viable &&
6479 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00006480 // Generally we only see ambiguities including viable builtin
6481 // operators if overload resolution got screwed up by an
6482 // ambiguous user-defined conversion.
6483 //
6484 // FIXME: It's quite possible for different conversions to see
6485 // different ambiguities, though.
6486 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00006487 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00006488 ReportedAmbiguousConversions = true;
6489 }
John McCalla1d7d622010-01-08 00:58:21 +00006490
John McCall1d318332010-01-12 00:44:57 +00006491 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00006492 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006493 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006494 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006495
6496 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00006497 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006498}
6499
John McCall9aa472c2010-03-19 07:35:19 +00006500static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCallc373d482010-01-27 01:50:18 +00006501 if (isa<UnresolvedLookupExpr>(E))
John McCall9aa472c2010-03-19 07:35:19 +00006502 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00006503
John McCall9aa472c2010-03-19 07:35:19 +00006504 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00006505}
6506
Douglas Gregor904eed32008-11-10 20:40:00 +00006507/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6508/// an overloaded function (C++ [over.over]), where @p From is an
6509/// expression with overloaded function type and @p ToType is the type
6510/// we're trying to resolve to. For example:
6511///
6512/// @code
6513/// int f(double);
6514/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00006515///
Douglas Gregor904eed32008-11-10 20:40:00 +00006516/// int (*pfd)(double) = f; // selects f(double)
6517/// @endcode
6518///
6519/// This routine returns the resulting FunctionDecl if it could be
6520/// resolved, and NULL otherwise. When @p Complain is true, this
6521/// routine will emit diagnostics if there is an error.
6522FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00006523Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall6bb80172010-03-30 21:47:33 +00006524 bool Complain,
6525 DeclAccessPair &FoundResult) {
Douglas Gregor904eed32008-11-10 20:40:00 +00006526 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00006527 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00006528 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00006529 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00006530 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00006531 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00006532 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00006533 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00006534 FunctionType = MemTypePtr->getPointeeType();
6535 IsMember = true;
6536 }
Douglas Gregor904eed32008-11-10 20:40:00 +00006537
Douglas Gregor904eed32008-11-10 20:40:00 +00006538 // C++ [over.over]p1:
6539 // [...] [Note: any redundant set of parentheses surrounding the
6540 // overloaded function name is ignored (5.1). ]
Douglas Gregor904eed32008-11-10 20:40:00 +00006541 // C++ [over.over]p1:
6542 // [...] The overloaded function name can be preceded by the &
6543 // operator.
John McCallc988fab2010-08-24 23:26:21 +00006544 // However, remember whether the expression has member-pointer form:
6545 // C++ [expr.unary.op]p4:
6546 // A pointer to member is only formed when an explicit & is used
6547 // and its operand is a qualified-id not enclosed in
6548 // parentheses.
John McCall9c72c602010-08-27 09:08:28 +00006549 OverloadExpr::FindResult Ovl = OverloadExpr::find(From);
6550 OverloadExpr *OvlExpr = Ovl.Expression;
John McCallc988fab2010-08-24 23:26:21 +00006551
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006552 // We expect a pointer or reference to function, or a function pointer.
6553 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6554 if (!FunctionType->isFunctionType()) {
6555 if (Complain)
6556 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6557 << OvlExpr->getName() << ToType;
6558
6559 return 0;
6560 }
6561
John McCallfb97e752010-08-24 22:52:39 +00006562 // If the overload expression doesn't have the form of a pointer to
John McCallc988fab2010-08-24 23:26:21 +00006563 // member, don't try to convert it to a pointer-to-member type.
John McCall9c72c602010-08-27 09:08:28 +00006564 if (IsMember && !Ovl.HasFormOfMemberPointer) {
John McCallfb97e752010-08-24 22:52:39 +00006565 if (!Complain) return 0;
6566
6567 // TODO: Should we condition this on whether any functions might
6568 // have matched, or is it more appropriate to do that in callers?
6569 // TODO: a fixit wouldn't hurt.
6570 Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
6571 << ToType << OvlExpr->getSourceRange();
6572 return 0;
6573 }
6574
6575 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6576 if (OvlExpr->hasExplicitTemplateArgs()) {
6577 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6578 ExplicitTemplateArgs = &ETABuffer;
6579 }
6580
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006581 assert(From->getType() == Context.OverloadTy);
Douglas Gregor904eed32008-11-10 20:40:00 +00006582
Douglas Gregor904eed32008-11-10 20:40:00 +00006583 // Look through all of the overloaded functions, searching for one
6584 // whose type matches exactly.
John McCall9aa472c2010-03-19 07:35:19 +00006585 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb7a09262010-04-01 18:32:35 +00006586 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
Douglas Gregor9b623632010-10-12 23:32:35 +00006587
Douglas Gregor00aeb522009-07-08 23:33:52 +00006588 bool FoundNonTemplateFunction = false;
John McCall7bb12da2010-02-02 06:20:04 +00006589 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6590 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00006591 // Look through any using declarations to find the underlying function.
6592 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6593
Douglas Gregor904eed32008-11-10 20:40:00 +00006594 // C++ [over.over]p3:
6595 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00006596 // targets of type "pointer-to-function" or "reference-to-function."
6597 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00006598 // type "pointer-to-member-function."
6599 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00006600
Mike Stump1eb44332009-09-09 15:08:12 +00006601 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthbd647292009-12-29 06:17:27 +00006602 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006603 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00006604 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00006605 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00006606 // static when converting to member pointer.
6607 if (Method->isStatic() == IsMember)
6608 continue;
6609 } else if (IsMember)
6610 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00006611
Douglas Gregor00aeb522009-07-08 23:33:52 +00006612 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00006613 // If the name is a function template, template argument deduction is
6614 // done (14.8.2.2), and if the argument deduction succeeds, the
6615 // resulting template argument list is used to generate a single
6616 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00006617 // overloaded functions considered.
Douglas Gregor83314aa2009-07-08 20:55:45 +00006618 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00006619 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor83314aa2009-07-08 20:55:45 +00006620 if (TemplateDeductionResult Result
John McCall7bb12da2010-02-02 06:20:04 +00006621 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00006622 FunctionType, Specialization, Info)) {
6623 // FIXME: make a note of the failed deduction for diagnostics.
6624 (void)Result;
6625 } else {
Douglas Gregorfbb6fad2010-09-29 21:14:36 +00006626 // Template argument deduction ensures that we have an exact match.
6627 // This function template specicalization works.
Douglas Gregor9b623632010-10-12 23:32:35 +00006628 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00006629 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00006630 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor9b623632010-10-12 23:32:35 +00006631 Matches.push_back(std::make_pair(I.getPair(), Specialization));
Douglas Gregor83314aa2009-07-08 20:55:45 +00006632 }
John McCallba135432009-11-21 08:51:07 +00006633
6634 continue;
Douglas Gregor83314aa2009-07-08 20:55:45 +00006635 }
Mike Stump1eb44332009-09-09 15:08:12 +00006636
Chandler Carruthbd647292009-12-29 06:17:27 +00006637 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00006638 // Skip non-static functions when converting to pointer, and static
6639 // when converting to member pointer.
6640 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00006641 continue;
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006642
6643 // If we have explicit template arguments, skip non-templates.
John McCall7bb12da2010-02-02 06:20:04 +00006644 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006645 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00006646 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00006647 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00006648
Chandler Carruthbd647292009-12-29 06:17:27 +00006649 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00006650 QualType ResultTy;
6651 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6652 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6653 ResultTy)) {
John McCall9aa472c2010-03-19 07:35:19 +00006654 Matches.push_back(std::make_pair(I.getPair(),
6655 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00006656 FoundNonTemplateFunction = true;
6657 }
Mike Stump1eb44332009-09-09 15:08:12 +00006658 }
Douglas Gregor904eed32008-11-10 20:40:00 +00006659 }
6660
Douglas Gregor00aeb522009-07-08 23:33:52 +00006661 // If there were 0 or 1 matches, we're done.
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006662 if (Matches.empty()) {
6663 if (Complain) {
6664 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6665 << OvlExpr->getName() << FunctionType;
6666 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6667 E = OvlExpr->decls_end();
6668 I != E; ++I)
6669 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6670 NoteOverloadCandidate(F);
6671 }
6672
Douglas Gregor00aeb522009-07-08 23:33:52 +00006673 return 0;
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006674 } else if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00006675 FunctionDecl *Result = Matches[0].second;
Douglas Gregor9b623632010-10-12 23:32:35 +00006676 FoundResult = Matches[0].first;
Sebastian Redl07ab2022009-10-17 21:12:09 +00006677 MarkDeclarationReferenced(From->getLocStart(), Result);
Douglas Gregor9b623632010-10-12 23:32:35 +00006678 if (Complain) {
John McCall6bb80172010-03-30 21:47:33 +00006679 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Douglas Gregor9b623632010-10-12 23:32:35 +00006680 }
Sebastian Redl07ab2022009-10-17 21:12:09 +00006681 return Result;
6682 }
Douglas Gregor00aeb522009-07-08 23:33:52 +00006683
6684 // C++ [over.over]p4:
6685 // If more than one function is selected, [...]
Douglas Gregor312a2022009-09-26 03:56:17 +00006686 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006687 // [...] and any given function template specialization F1 is
6688 // eliminated if the set contains a second function template
6689 // specialization whose function template is more specialized
6690 // than the function template of F1 according to the partial
6691 // ordering rules of 14.5.5.2.
6692
6693 // The algorithm specified above is quadratic. We instead use a
6694 // two-pass algorithm (similar to the one used to identify the
6695 // best viable function in an overload set) that identifies the
6696 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00006697
6698 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6699 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6700 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCallc373d482010-01-27 01:50:18 +00006701
6702 UnresolvedSetIterator Result =
John McCall9aa472c2010-03-19 07:35:19 +00006703 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redl07ab2022009-10-17 21:12:09 +00006704 TPOC_Other, From->getLocStart(),
6705 PDiag(),
6706 PDiag(diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00006707 << Matches[0].second->getDeclName(),
John McCall220ccbf2010-01-13 00:25:19 +00006708 PDiag(diag::note_ovl_candidate)
6709 << (unsigned) oc_function_template);
Douglas Gregor78c057e2010-09-12 08:16:09 +00006710 if (Result == MatchesCopy.end())
6711 return 0;
6712
John McCallc373d482010-01-27 01:50:18 +00006713 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall6bb80172010-03-30 21:47:33 +00006714 FoundResult = Matches[Result - MatchesCopy.begin()].first;
Douglas Gregor9b623632010-10-12 23:32:35 +00006715 if (Complain)
John McCall6bb80172010-03-30 21:47:33 +00006716 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCallc373d482010-01-27 01:50:18 +00006717 return cast<FunctionDecl>(*Result);
Douglas Gregor00aeb522009-07-08 23:33:52 +00006718 }
Mike Stump1eb44332009-09-09 15:08:12 +00006719
Douglas Gregor312a2022009-09-26 03:56:17 +00006720 // [...] any function template specializations in the set are
6721 // eliminated if the set also contains a non-template function, [...]
John McCallc373d482010-01-27 01:50:18 +00006722 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCall9aa472c2010-03-19 07:35:19 +00006723 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCallc373d482010-01-27 01:50:18 +00006724 ++I;
6725 else {
John McCall9aa472c2010-03-19 07:35:19 +00006726 Matches[I] = Matches[--N];
6727 Matches.set_size(N);
John McCallc373d482010-01-27 01:50:18 +00006728 }
6729 }
Douglas Gregor312a2022009-09-26 03:56:17 +00006730
Mike Stump1eb44332009-09-09 15:08:12 +00006731 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00006732 // selected function.
John McCallc373d482010-01-27 01:50:18 +00006733 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00006734 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall6bb80172010-03-30 21:47:33 +00006735 FoundResult = Matches[0].first;
Douglas Gregor9b623632010-10-12 23:32:35 +00006736 if (Complain)
John McCall9aa472c2010-03-19 07:35:19 +00006737 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
6738 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redl07ab2022009-10-17 21:12:09 +00006739 }
Mike Stump1eb44332009-09-09 15:08:12 +00006740
Douglas Gregor00aeb522009-07-08 23:33:52 +00006741 // FIXME: We should probably return the same thing that BestViableFunction
6742 // returns (even if we issue the diagnostics here).
Douglas Gregor8e960432010-11-08 03:40:48 +00006743 if (Complain) {
6744 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
6745 << Matches[0].second->getDeclName();
6746 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6747 NoteOverloadCandidate(Matches[I].second);
6748 }
6749
Douglas Gregor904eed32008-11-10 20:40:00 +00006750 return 0;
6751}
6752
Douglas Gregor4b52e252009-12-21 23:17:24 +00006753/// \brief Given an expression that refers to an overloaded function, try to
6754/// resolve that overloaded function expression down to a single function.
6755///
6756/// This routine can only resolve template-ids that refer to a single function
6757/// template, where that template-id refers to a single template whose template
6758/// arguments are either provided by the template-id or have defaults,
6759/// as described in C++0x [temp.arg.explicit]p3.
6760FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6761 // C++ [over.over]p1:
6762 // [...] [Note: any redundant set of parentheses surrounding the
6763 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00006764 // C++ [over.over]p1:
6765 // [...] The overloaded function name can be preceded by the &
6766 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00006767
6768 if (From->getType() != Context.OverloadTy)
6769 return 0;
6770
John McCall9c72c602010-08-27 09:08:28 +00006771 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
Douglas Gregor4b52e252009-12-21 23:17:24 +00006772
6773 // If we didn't actually find any template-ids, we're done.
John McCall7bb12da2010-02-02 06:20:04 +00006774 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00006775 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00006776
6777 TemplateArgumentListInfo ExplicitTemplateArgs;
6778 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor4b52e252009-12-21 23:17:24 +00006779
6780 // Look through all of the overloaded functions, searching for one
6781 // whose type matches exactly.
6782 FunctionDecl *Matched = 0;
John McCall7bb12da2010-02-02 06:20:04 +00006783 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6784 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00006785 // C++0x [temp.arg.explicit]p3:
6786 // [...] In contexts where deduction is done and fails, or in contexts
6787 // where deduction is not done, if a template argument list is
6788 // specified and it, along with any default template arguments,
6789 // identifies a single function template specialization, then the
6790 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00006791 FunctionTemplateDecl *FunctionTemplate
6792 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor4b52e252009-12-21 23:17:24 +00006793
6794 // C++ [over.over]p2:
6795 // If the name is a function template, template argument deduction is
6796 // done (14.8.2.2), and if the argument deduction succeeds, the
6797 // resulting template argument list is used to generate a single
6798 // function template specialization, which is added to the set of
6799 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00006800 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00006801 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00006802 if (TemplateDeductionResult Result
6803 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6804 Specialization, Info)) {
6805 // FIXME: make a note of the failed deduction for diagnostics.
6806 (void)Result;
6807 continue;
6808 }
6809
6810 // Multiple matches; we can't resolve to a single declaration.
6811 if (Matched)
6812 return 0;
6813
6814 Matched = Specialization;
6815 }
Douglas Gregor9b623632010-10-12 23:32:35 +00006816
Douglas Gregor4b52e252009-12-21 23:17:24 +00006817 return Matched;
6818}
6819
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006820/// \brief Add a single candidate to the overload set.
6821static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00006822 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00006823 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006824 Expr **Args, unsigned NumArgs,
6825 OverloadCandidateSet &CandidateSet,
6826 bool PartialOverloading) {
John McCall9aa472c2010-03-19 07:35:19 +00006827 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00006828 if (isa<UsingShadowDecl>(Callee))
6829 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6830
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006831 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00006832 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCall9aa472c2010-03-19 07:35:19 +00006833 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00006834 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006835 return;
John McCallba135432009-11-21 08:51:07 +00006836 }
6837
6838 if (FunctionTemplateDecl *FuncTemplate
6839 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00006840 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6841 ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00006842 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00006843 return;
6844 }
6845
6846 assert(false && "unhandled case in overloaded call candidate");
6847
6848 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006849}
6850
6851/// \brief Add the overload candidates named by callee and/or found by argument
6852/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00006853void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006854 Expr **Args, unsigned NumArgs,
6855 OverloadCandidateSet &CandidateSet,
6856 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00006857
6858#ifndef NDEBUG
6859 // Verify that ArgumentDependentLookup is consistent with the rules
6860 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006861 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006862 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6863 // and let Y be the lookup set produced by argument dependent
6864 // lookup (defined as follows). If X contains
6865 //
6866 // -- a declaration of a class member, or
6867 //
6868 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00006869 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006870 //
6871 // -- a declaration that is neither a function or a function
6872 // template
6873 //
6874 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00006875
John McCall3b4294e2009-12-16 12:17:52 +00006876 if (ULE->requiresADL()) {
6877 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6878 E = ULE->decls_end(); I != E; ++I) {
6879 assert(!(*I)->getDeclContext()->isRecord());
6880 assert(isa<UsingShadowDecl>(*I) ||
6881 !(*I)->getDeclContext()->isFunctionOrMethod());
6882 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00006883 }
6884 }
6885#endif
6886
John McCall3b4294e2009-12-16 12:17:52 +00006887 // It would be nice to avoid this copy.
6888 TemplateArgumentListInfo TABuffer;
6889 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6890 if (ULE->hasExplicitTemplateArgs()) {
6891 ULE->copyTemplateArgumentsInto(TABuffer);
6892 ExplicitTemplateArgs = &TABuffer;
6893 }
6894
6895 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6896 E = ULE->decls_end(); I != E; ++I)
John McCall9aa472c2010-03-19 07:35:19 +00006897 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00006898 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006899 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00006900
John McCall3b4294e2009-12-16 12:17:52 +00006901 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00006902 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6903 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006904 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006905 CandidateSet,
6906 PartialOverloading);
6907}
John McCall578b69b2009-12-16 08:11:27 +00006908
6909/// Attempts to recover from a call where no functions were found.
6910///
6911/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00006912static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006913BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00006914 UnresolvedLookupExpr *ULE,
6915 SourceLocation LParenLoc,
6916 Expr **Args, unsigned NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00006917 SourceLocation RParenLoc) {
John McCall578b69b2009-12-16 08:11:27 +00006918
6919 CXXScopeSpec SS;
6920 if (ULE->getQualifier()) {
6921 SS.setScopeRep(ULE->getQualifier());
6922 SS.setRange(ULE->getQualifierRange());
6923 }
6924
John McCall3b4294e2009-12-16 12:17:52 +00006925 TemplateArgumentListInfo TABuffer;
6926 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6927 if (ULE->hasExplicitTemplateArgs()) {
6928 ULE->copyTemplateArgumentsInto(TABuffer);
6929 ExplicitTemplateArgs = &TABuffer;
6930 }
6931
John McCall578b69b2009-12-16 08:11:27 +00006932 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6933 Sema::LookupOrdinaryName);
Douglas Gregor91f7ac72010-05-18 16:14:23 +00006934 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCallf312b1e2010-08-26 23:41:50 +00006935 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00006936
John McCall3b4294e2009-12-16 12:17:52 +00006937 assert(!R.empty() && "lookup results empty despite recovery");
6938
6939 // Build an implicit member call if appropriate. Just drop the
6940 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00006941 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00006942 if ((*R.begin())->isCXXClassMember())
6943 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6944 else if (ExplicitTemplateArgs)
6945 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6946 else
6947 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6948
6949 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00006950 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00006951
6952 // This shouldn't cause an infinite loop because we're giving it
6953 // an expression with non-empty lookup results, which should never
6954 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00006955 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +00006956 MultiExprArg(Args, NumArgs), RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00006957}
Douglas Gregord7a95972010-06-08 17:35:15 +00006958
Douglas Gregorf6b89692008-11-26 05:54:23 +00006959/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00006960/// (which eventually refers to the declaration Func) and the call
6961/// arguments Args/NumArgs, attempt to resolve the function call down
6962/// to a specific function. If overload resolution succeeds, returns
6963/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00006964/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00006965/// arguments and Fn, and returns NULL.
John McCall60d7b3a2010-08-24 06:29:42 +00006966ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006967Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00006968 SourceLocation LParenLoc,
6969 Expr **Args, unsigned NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00006970 SourceLocation RParenLoc) {
6971#ifndef NDEBUG
6972 if (ULE->requiresADL()) {
6973 // To do ADL, we must have found an unqualified name.
6974 assert(!ULE->getQualifier() && "qualified name with ADL");
6975
6976 // We don't perform ADL for implicit declarations of builtins.
6977 // Verify that this was correctly set up.
6978 FunctionDecl *F;
6979 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6980 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6981 F->getBuiltinID() && F->isImplicit())
6982 assert(0 && "performing ADL for builtin");
6983
6984 // We don't perform ADL in C.
6985 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6986 }
6987#endif
6988
John McCall5769d612010-02-08 23:07:23 +00006989 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00006990
John McCall3b4294e2009-12-16 12:17:52 +00006991 // Add the functions denoted by the callee to the set of candidate
6992 // functions, including those from argument-dependent lookup.
6993 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00006994
6995 // If we found nothing, try to recover.
6996 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6997 // bailout out if it fails.
John McCall3b4294e2009-12-16 12:17:52 +00006998 if (CandidateSet.empty())
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006999 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregora1a04782010-09-09 16:33:13 +00007000 RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00007001
Douglas Gregorf6b89692008-11-26 05:54:23 +00007002 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007003 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00007004 case OR_Success: {
7005 FunctionDecl *FDecl = Best->Function;
John McCall9aa472c2010-03-19 07:35:19 +00007006 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Douglas Gregor5f3aeb62010-10-13 00:27:52 +00007007 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(), ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00007008 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall3b4294e2009-12-16 12:17:52 +00007009 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
7010 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00007011
7012 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00007013 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00007014 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00007015 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007016 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00007017 break;
7018
7019 case OR_Ambiguous:
7020 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00007021 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007022 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00007023 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007024
7025 case OR_Deleted:
7026 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
7027 << Best->Function->isDeleted()
John McCall3b4294e2009-12-16 12:17:52 +00007028 << ULE->getName()
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007029 << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007030 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007031 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00007032 }
7033
Douglas Gregorff331c12010-07-25 18:17:45 +00007034 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00007035 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00007036}
7037
John McCall6e266892010-01-26 03:27:55 +00007038static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00007039 return Functions.size() > 1 ||
7040 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
7041}
7042
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007043/// \brief Create a unary operation that may resolve to an overloaded
7044/// operator.
7045///
7046/// \param OpLoc The location of the operator itself (e.g., '*').
7047///
7048/// \param OpcIn The UnaryOperator::Opcode that describes this
7049/// operator.
7050///
7051/// \param Functions The set of non-member functions that will be
7052/// considered by overload resolution. The caller needs to build this
7053/// set based on the context using, e.g.,
7054/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7055/// set should not contain any member functions; those will be added
7056/// by CreateOverloadedUnaryOp().
7057///
7058/// \param input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +00007059ExprResult
John McCall6e266892010-01-26 03:27:55 +00007060Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
7061 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +00007062 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007063 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007064
7065 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
7066 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
7067 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00007068 // TODO: provide better source location info.
7069 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007070
7071 Expr *Args[2] = { Input, 0 };
7072 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00007073
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007074 // For post-increment and post-decrement, add the implicit '0' as
7075 // the second argument, so that we know this is a post-increment or
7076 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +00007077 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007078 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00007079 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
7080 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007081 NumArgs = 2;
7082 }
7083
7084 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00007085 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +00007086 return Owned(new (Context) UnaryOperator(Input,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00007087 Opc,
7088 Context.DependentTy,
7089 OpLoc));
7090
John McCallc373d482010-01-27 01:50:18 +00007091 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00007092 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00007093 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00007094 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00007095 /*ADL*/ true, IsOverloaded(Fns),
7096 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007097 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
7098 &Args[0], NumArgs,
7099 Context.DependentTy,
7100 OpLoc));
7101 }
7102
7103 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00007104 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007105
7106 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00007107 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007108
7109 // Add operator candidates that are member functions.
7110 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
7111
John McCall6e266892010-01-26 03:27:55 +00007112 // Add candidates from ADL.
7113 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregordc81c882010-02-05 05:15:43 +00007114 Args, NumArgs,
John McCall6e266892010-01-26 03:27:55 +00007115 /*ExplicitTemplateArgs*/ 0,
7116 CandidateSet);
7117
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007118 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00007119 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007120
7121 // Perform overload resolution.
7122 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007123 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007124 case OR_Success: {
7125 // We found a built-in operator or an overloaded operator.
7126 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00007127
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007128 if (FnDecl) {
7129 // We matched an overloaded operator. Build a call to that
7130 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00007131
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007132 // Convert the arguments.
7133 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00007134 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00007135
John McCall6bb80172010-03-30 21:47:33 +00007136 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
7137 Best->FoundDecl, Method))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007138 return ExprError();
7139 } else {
7140 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00007141 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +00007142 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007143 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +00007144 FnDecl->getParamDecl(0)),
Douglas Gregore1a5c172009-12-23 17:40:29 +00007145 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +00007146 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +00007147 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007148 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00007149 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007150 }
7151
John McCallb697e082010-05-06 18:15:07 +00007152 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7153
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007154 // Determine the result type
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007155 QualType ResultTy = FnDecl->getCallResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00007156
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007157 // Build the actual expression node.
7158 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7159 SourceLocation());
7160 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00007161
Eli Friedman4c3b8962009-11-18 03:58:17 +00007162 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +00007163 CallExpr *TheCall =
Anders Carlsson26a2a072009-10-13 21:19:37 +00007164 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall9ae2f072010-08-23 23:25:46 +00007165 Args, NumArgs, ResultTy, OpLoc);
John McCallb697e082010-05-06 18:15:07 +00007166
John McCall9ae2f072010-08-23 23:25:46 +00007167 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +00007168 FnDecl))
7169 return ExprError();
7170
John McCall9ae2f072010-08-23 23:25:46 +00007171 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007172 } else {
7173 // We matched a built-in operator. Convert the arguments, then
7174 // break out so that we will build the appropriate built-in
7175 // operator node.
7176 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00007177 Best->Conversions[0], AA_Passing))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007178 return ExprError();
7179
7180 break;
7181 }
7182 }
7183
7184 case OR_No_Viable_Function:
7185 // No viable function; fall through to handling this as a
7186 // built-in operator, which will produce an error message for us.
7187 break;
7188
7189 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00007190 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007191 << UnaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +00007192 << Input->getType()
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007193 << Input->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007194 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
7195 Args, NumArgs,
7196 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007197 return ExprError();
7198
7199 case OR_Deleted:
7200 Diag(OpLoc, diag::err_ovl_deleted_oper)
7201 << Best->Function->isDeleted()
7202 << UnaryOperator::getOpcodeStr(Opc)
7203 << Input->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007204 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007205 return ExprError();
7206 }
7207
7208 // Either we found no viable overloaded operator or we matched a
7209 // built-in operator. In either case, fall through to trying to
7210 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +00007211 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007212}
7213
Douglas Gregor063daf62009-03-13 18:40:31 +00007214/// \brief Create a binary operation that may resolve to an overloaded
7215/// operator.
7216///
7217/// \param OpLoc The location of the operator itself (e.g., '+').
7218///
7219/// \param OpcIn The BinaryOperator::Opcode that describes this
7220/// operator.
7221///
7222/// \param Functions The set of non-member functions that will be
7223/// considered by overload resolution. The caller needs to build this
7224/// set based on the context using, e.g.,
7225/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7226/// set should not contain any member functions; those will be added
7227/// by CreateOverloadedBinOp().
7228///
7229/// \param LHS Left-hand argument.
7230/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +00007231ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00007232Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00007233 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00007234 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00007235 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00007236 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007237 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00007238
7239 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
7240 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
7241 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7242
7243 // If either side is type-dependent, create an appropriate dependent
7244 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007245 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00007246 if (Fns.empty()) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007247 // If there are no functions to store, just build a dependent
7248 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +00007249 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00007250 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
7251 Context.DependentTy, OpLoc));
7252
7253 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
7254 Context.DependentTy,
7255 Context.DependentTy,
7256 Context.DependentTy,
7257 OpLoc));
7258 }
John McCall6e266892010-01-26 03:27:55 +00007259
7260 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00007261 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00007262 // TODO: provide better source location info in DNLoc component.
7263 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +00007264 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00007265 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00007266 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00007267 /*ADL*/ true, IsOverloaded(Fns),
7268 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00007269 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00007270 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00007271 Context.DependentTy,
7272 OpLoc));
7273 }
7274
7275 // If this is the .* operator, which is not overloadable, just
7276 // create a built-in binary operator.
John McCall2de56d12010-08-25 11:45:40 +00007277 if (Opc == BO_PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007278 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00007279
Sebastian Redl275c2b42009-11-18 23:10:33 +00007280 // If this is the assignment operator, we only perform overload resolution
7281 // if the left-hand side is a class or enumeration type. This is actually
7282 // a hack. The standard requires that we do overload resolution between the
7283 // various built-in candidates, but as DR507 points out, this can lead to
7284 // problems. So we do it this way, which pretty much follows what GCC does.
7285 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +00007286 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007287 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00007288
Douglas Gregorbc736fc2009-03-13 23:49:33 +00007289 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00007290 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00007291
7292 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00007293 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00007294
7295 // Add operator candidates that are member functions.
7296 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
7297
John McCall6e266892010-01-26 03:27:55 +00007298 // Add candidates from ADL.
7299 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
7300 Args, 2,
7301 /*ExplicitTemplateArgs*/ 0,
7302 CandidateSet);
7303
Douglas Gregor063daf62009-03-13 18:40:31 +00007304 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00007305 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00007306
7307 // Perform overload resolution.
7308 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007309 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00007310 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00007311 // We found a built-in operator or an overloaded operator.
7312 FunctionDecl *FnDecl = Best->Function;
7313
7314 if (FnDecl) {
7315 // We matched an overloaded operator. Build a call to that
7316 // operator.
7317
7318 // Convert the arguments.
7319 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00007320 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +00007321 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00007322
John McCall60d7b3a2010-08-24 06:29:42 +00007323 ExprResult Arg1
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007324 = PerformCopyInitialization(
7325 InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007326 Context,
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007327 FnDecl->getParamDecl(0)),
7328 SourceLocation(),
7329 Owned(Args[1]));
7330 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00007331 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007332
Douglas Gregor5fccd362010-03-03 23:55:11 +00007333 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007334 Best->FoundDecl, Method))
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007335 return ExprError();
7336
7337 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00007338 } else {
7339 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00007340 ExprResult Arg0
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007341 = PerformCopyInitialization(
7342 InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007343 Context,
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007344 FnDecl->getParamDecl(0)),
7345 SourceLocation(),
7346 Owned(Args[0]));
7347 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00007348 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007349
John McCall60d7b3a2010-08-24 06:29:42 +00007350 ExprResult Arg1
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007351 = PerformCopyInitialization(
7352 InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007353 Context,
Douglas Gregor4c2458a2009-12-22 21:44:34 +00007354 FnDecl->getParamDecl(1)),
7355 SourceLocation(),
7356 Owned(Args[1]));
7357 if (Arg1.isInvalid())
7358 return ExprError();
7359 Args[0] = LHS = Arg0.takeAs<Expr>();
7360 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00007361 }
7362
John McCallb697e082010-05-06 18:15:07 +00007363 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7364
Douglas Gregor063daf62009-03-13 18:40:31 +00007365 // Determine the result type
7366 QualType ResultTy
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007367 = FnDecl->getType()->getAs<FunctionType>()
7368 ->getCallResultType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +00007369
7370 // Build the actual expression node.
7371 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00007372 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00007373 UsualUnaryConversions(FnExpr);
7374
John McCall9ae2f072010-08-23 23:25:46 +00007375 CXXOperatorCallExpr *TheCall =
7376 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
7377 Args, 2, ResultTy, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +00007378
John McCall9ae2f072010-08-23 23:25:46 +00007379 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00007380 FnDecl))
7381 return ExprError();
7382
John McCall9ae2f072010-08-23 23:25:46 +00007383 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +00007384 } else {
7385 // We matched a built-in operator. Convert the arguments, then
7386 // break out so that we will build the appropriate built-in
7387 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007388 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00007389 Best->Conversions[0], AA_Passing) ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007390 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00007391 Best->Conversions[1], AA_Passing))
Douglas Gregor063daf62009-03-13 18:40:31 +00007392 return ExprError();
7393
7394 break;
7395 }
7396 }
7397
Douglas Gregor33074752009-09-30 21:46:01 +00007398 case OR_No_Viable_Function: {
7399 // C++ [over.match.oper]p9:
7400 // If the operator is the operator , [...] and there are no
7401 // viable functions, then the operator is assumed to be the
7402 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +00007403 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +00007404 break;
7405
Sebastian Redl8593c782009-05-21 11:50:50 +00007406 // For class as left operand for assignment or compound assigment operator
7407 // do not fall through to handling in built-in, but report that no overloaded
7408 // assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +00007409 ExprResult Result = ExprError();
Douglas Gregor33074752009-09-30 21:46:01 +00007410 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +00007411 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00007412 Diag(OpLoc, diag::err_ovl_no_viable_oper)
7413 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007414 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00007415 } else {
7416 // No viable function; try to create a built-in operation, which will
7417 // produce an error. Then, show the non-viable candidates.
7418 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00007419 }
Douglas Gregor33074752009-09-30 21:46:01 +00007420 assert(Result.isInvalid() &&
7421 "C++ binary operator overloading is missing candidates!");
7422 if (Result.isInvalid())
John McCall120d63c2010-08-24 20:38:10 +00007423 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7424 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00007425 return move(Result);
7426 }
Douglas Gregor063daf62009-03-13 18:40:31 +00007427
7428 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00007429 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +00007430 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +00007431 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007432 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007433 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7434 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00007435 return ExprError();
7436
7437 case OR_Deleted:
7438 Diag(OpLoc, diag::err_ovl_deleted_oper)
7439 << Best->Function->isDeleted()
7440 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007441 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007442 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor063daf62009-03-13 18:40:31 +00007443 return ExprError();
John McCall1d318332010-01-12 00:44:57 +00007444 }
Douglas Gregor063daf62009-03-13 18:40:31 +00007445
Douglas Gregor33074752009-09-30 21:46:01 +00007446 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007447 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00007448}
7449
John McCall60d7b3a2010-08-24 06:29:42 +00007450ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +00007451Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7452 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +00007453 Expr *Base, Expr *Idx) {
7454 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +00007455 DeclarationName OpName =
7456 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7457
7458 // If either side is type-dependent, create an appropriate dependent
7459 // expression.
7460 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7461
John McCallc373d482010-01-27 01:50:18 +00007462 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00007463 // CHECKME: no 'operator' keyword?
7464 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7465 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +00007466 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00007467 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00007468 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00007469 /*ADL*/ true, /*Overloaded*/ false,
7470 UnresolvedSetIterator(),
7471 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +00007472 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00007473
Sebastian Redlf322ed62009-10-29 20:17:01 +00007474 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7475 Args, 2,
7476 Context.DependentTy,
7477 RLoc));
7478 }
7479
7480 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00007481 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007482
7483 // Subscript can only be overloaded as a member function.
7484
7485 // Add operator candidates that are member functions.
7486 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7487
7488 // Add builtin operator candidates.
7489 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7490
7491 // Perform overload resolution.
7492 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007493 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00007494 case OR_Success: {
7495 // We found a built-in operator or an overloaded operator.
7496 FunctionDecl *FnDecl = Best->Function;
7497
7498 if (FnDecl) {
7499 // We matched an overloaded operator. Build a call to that
7500 // operator.
7501
John McCall9aa472c2010-03-19 07:35:19 +00007502 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007503 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +00007504
Sebastian Redlf322ed62009-10-29 20:17:01 +00007505 // Convert the arguments.
7506 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007507 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007508 Best->FoundDecl, Method))
Sebastian Redlf322ed62009-10-29 20:17:01 +00007509 return ExprError();
7510
Anders Carlsson38f88ab2010-01-29 18:37:50 +00007511 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00007512 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +00007513 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007514 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +00007515 FnDecl->getParamDecl(0)),
7516 SourceLocation(),
7517 Owned(Args[1]));
7518 if (InputInit.isInvalid())
7519 return ExprError();
7520
7521 Args[1] = InputInit.takeAs<Expr>();
7522
Sebastian Redlf322ed62009-10-29 20:17:01 +00007523 // Determine the result type
7524 QualType ResultTy
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007525 = FnDecl->getType()->getAs<FunctionType>()
7526 ->getCallResultType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007527
7528 // Build the actual expression node.
7529 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7530 LLoc);
7531 UsualUnaryConversions(FnExpr);
7532
John McCall9ae2f072010-08-23 23:25:46 +00007533 CXXOperatorCallExpr *TheCall =
7534 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7535 FnExpr, Args, 2,
7536 ResultTy, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007537
John McCall9ae2f072010-08-23 23:25:46 +00007538 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +00007539 FnDecl))
7540 return ExprError();
7541
John McCall9ae2f072010-08-23 23:25:46 +00007542 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007543 } else {
7544 // We matched a built-in operator. Convert the arguments, then
7545 // break out so that we will build the appropriate built-in
7546 // operator node.
7547 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00007548 Best->Conversions[0], AA_Passing) ||
Sebastian Redlf322ed62009-10-29 20:17:01 +00007549 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00007550 Best->Conversions[1], AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00007551 return ExprError();
7552
7553 break;
7554 }
7555 }
7556
7557 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00007558 if (CandidateSet.empty())
7559 Diag(LLoc, diag::err_ovl_no_oper)
7560 << Args[0]->getType() << /*subscript*/ 0
7561 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7562 else
7563 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7564 << Args[0]->getType()
7565 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007566 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7567 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +00007568 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00007569 }
7570
7571 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00007572 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
7573 << "[]"
7574 << Args[0]->getType() << Args[1]->getType()
7575 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007576 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7577 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007578 return ExprError();
7579
7580 case OR_Deleted:
7581 Diag(LLoc, diag::err_ovl_deleted_oper)
7582 << Best->Function->isDeleted() << "[]"
7583 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007584 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7585 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007586 return ExprError();
7587 }
7588
7589 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +00007590 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007591}
7592
Douglas Gregor88a35142008-12-22 05:46:06 +00007593/// BuildCallToMemberFunction - Build a call to a member
7594/// function. MemExpr is the expression that refers to the member
7595/// function (and includes the object parameter), Args/NumArgs are the
7596/// arguments to the function call (not including the object
7597/// parameter). The caller needs to validate that the member
7598/// expression refers to a member function or an overloaded member
7599/// function.
John McCall60d7b3a2010-08-24 06:29:42 +00007600ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00007601Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7602 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +00007603 unsigned NumArgs, SourceLocation RParenLoc) {
Douglas Gregor88a35142008-12-22 05:46:06 +00007604 // Dig out the member expression. This holds both the object
7605 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00007606 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7607
John McCall129e2df2009-11-30 22:42:35 +00007608 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00007609 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +00007610 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007611 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +00007612 if (isa<MemberExpr>(NakedMemExpr)) {
7613 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00007614 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +00007615 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +00007616 Qualifier = MemExpr->getQualifier();
John McCall129e2df2009-11-30 22:42:35 +00007617 } else {
7618 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007619 Qualifier = UnresExpr->getQualifier();
7620
John McCall701c89e2009-12-03 04:06:58 +00007621 QualType ObjectType = UnresExpr->getBaseType();
John McCall129e2df2009-11-30 22:42:35 +00007622
Douglas Gregor88a35142008-12-22 05:46:06 +00007623 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +00007624 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00007625
John McCallaa81e162009-12-01 22:10:20 +00007626 // FIXME: avoid copy.
7627 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7628 if (UnresExpr->hasExplicitTemplateArgs()) {
7629 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7630 TemplateArgs = &TemplateArgsBuffer;
7631 }
7632
John McCall129e2df2009-11-30 22:42:35 +00007633 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7634 E = UnresExpr->decls_end(); I != E; ++I) {
7635
John McCall701c89e2009-12-03 04:06:58 +00007636 NamedDecl *Func = *I;
7637 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7638 if (isa<UsingShadowDecl>(Func))
7639 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7640
John McCall129e2df2009-11-30 22:42:35 +00007641 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00007642 // If explicit template arguments were provided, we can't call a
7643 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00007644 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00007645 continue;
7646
John McCall9aa472c2010-03-19 07:35:19 +00007647 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCall86820f52010-01-26 01:37:31 +00007648 Args, NumArgs,
John McCall701c89e2009-12-03 04:06:58 +00007649 CandidateSet, /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00007650 } else {
John McCall129e2df2009-11-30 22:42:35 +00007651 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +00007652 I.getPair(), ActingDC, TemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00007653 ObjectType, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00007654 CandidateSet,
7655 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00007656 }
Douglas Gregordec06662009-08-21 18:42:58 +00007657 }
Mike Stump1eb44332009-09-09 15:08:12 +00007658
John McCall129e2df2009-11-30 22:42:35 +00007659 DeclarationName DeclName = UnresExpr->getMemberName();
7660
Douglas Gregor88a35142008-12-22 05:46:06 +00007661 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007662 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
7663 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00007664 case OR_Success:
7665 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00007666 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +00007667 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007668 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +00007669 break;
7670
7671 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00007672 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00007673 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00007674 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007675 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00007676 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007677 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007678
7679 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00007680 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00007681 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007682 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00007683 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007684 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007685
7686 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00007687 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007688 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00007689 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007690 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007691 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007692 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007693 }
7694
John McCall6bb80172010-03-30 21:47:33 +00007695 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +00007696
John McCallaa81e162009-12-01 22:10:20 +00007697 // If overload resolution picked a static member, build a
7698 // non-member call based on that function.
7699 if (Method->isStatic()) {
7700 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7701 Args, NumArgs, RParenLoc);
7702 }
7703
John McCall129e2df2009-11-30 22:42:35 +00007704 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00007705 }
7706
7707 assert(Method && "Member call to something that isn't a method?");
John McCall9ae2f072010-08-23 23:25:46 +00007708 CXXMemberCallExpr *TheCall =
7709 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
7710 Method->getCallResultType(),
7711 RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +00007712
Anders Carlssoneed3e692009-10-10 00:06:20 +00007713 // Check for a valid return type.
7714 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +00007715 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +00007716 return ExprError();
Anders Carlssoneed3e692009-10-10 00:06:20 +00007717
Douglas Gregor88a35142008-12-22 05:46:06 +00007718 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +00007719 // We only need to do this if there was actually an overload; otherwise
7720 // it was done at lookup.
John McCallaa81e162009-12-01 22:10:20 +00007721 Expr *ObjectArg = MemExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00007722 if (!Method->isStatic() &&
John McCall6bb80172010-03-30 21:47:33 +00007723 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7724 FoundDecl, Method))
John McCallaa81e162009-12-01 22:10:20 +00007725 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007726 MemExpr->setBase(ObjectArg);
7727
7728 // Convert the rest of the arguments
Douglas Gregor5f970ee2010-05-04 18:18:31 +00007729 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +00007730 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00007731 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00007732 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007733
John McCall9ae2f072010-08-23 23:25:46 +00007734 if (CheckFunctionCall(Method, TheCall))
John McCallaa81e162009-12-01 22:10:20 +00007735 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00007736
John McCall9ae2f072010-08-23 23:25:46 +00007737 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +00007738}
7739
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007740/// BuildCallToObjectOfClassType - Build a call to an object of class
7741/// type (C++ [over.call.object]), which can end up invoking an
7742/// overloaded function call operator (@c operator()) or performing a
7743/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +00007744ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00007745Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00007746 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007747 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007748 SourceLocation RParenLoc) {
7749 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00007750 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00007751
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007752 // C++ [over.call.object]p1:
7753 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00007754 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007755 // candidate functions includes at least the function call
7756 // operators of T. The function call operators of T are obtained by
7757 // ordinary lookup of the name operator() in the context of
7758 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +00007759 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00007760 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00007761
7762 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007763 PDiag(diag::err_incomplete_object_call)
Douglas Gregor593564b2009-11-15 07:48:03 +00007764 << Object->getSourceRange()))
7765 return true;
7766
John McCalla24dc2e2009-11-17 02:14:36 +00007767 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7768 LookupQualifiedName(R, Record->getDecl());
7769 R.suppressDiagnostics();
7770
Douglas Gregor593564b2009-11-15 07:48:03 +00007771 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00007772 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00007773 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCall86820f52010-01-26 01:37:31 +00007774 Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00007775 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00007776 }
Douglas Gregor4a27d702009-10-21 06:18:39 +00007777
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007778 // C++ [over.call.object]p2:
7779 // In addition, for each conversion function declared in T of the
7780 // form
7781 //
7782 // operator conversion-type-id () cv-qualifier;
7783 //
7784 // where cv-qualifier is the same cv-qualification as, or a
7785 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00007786 // denotes the type "pointer to function of (P1,...,Pn) returning
7787 // R", or the type "reference to pointer to function of
7788 // (P1,...,Pn) returning R", or the type "reference to function
7789 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007790 // is also considered as a candidate function. Similarly,
7791 // surrogate call functions are added to the set of candidate
7792 // functions for each conversion function declared in an
7793 // accessible base class provided the function is not hidden
7794 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +00007795 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00007796 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00007797 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00007798 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00007799 NamedDecl *D = *I;
7800 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7801 if (isa<UsingShadowDecl>(D))
7802 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7803
Douglas Gregor4a27d702009-10-21 06:18:39 +00007804 // Skip over templated conversion functions; they aren't
7805 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00007806 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00007807 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007808
John McCall701c89e2009-12-03 04:06:58 +00007809 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCallba135432009-11-21 08:51:07 +00007810
Douglas Gregor4a27d702009-10-21 06:18:39 +00007811 // Strip the reference type (if any) and then the pointer type (if
7812 // any) to get down to what might be a function type.
7813 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7814 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7815 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007816
Douglas Gregor4a27d702009-10-21 06:18:39 +00007817 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall9aa472c2010-03-19 07:35:19 +00007818 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall701c89e2009-12-03 04:06:58 +00007819 Object->getType(), Args, NumArgs,
7820 CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007821 }
Mike Stump1eb44332009-09-09 15:08:12 +00007822
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007823 // Perform overload resolution.
7824 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00007825 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
7826 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007827 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007828 // Overload resolution succeeded; we'll build the appropriate call
7829 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007830 break;
7831
7832 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00007833 if (CandidateSet.empty())
7834 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7835 << Object->getType() << /*call*/ 1
7836 << Object->getSourceRange();
7837 else
7838 Diag(Object->getSourceRange().getBegin(),
7839 diag::err_ovl_no_viable_object_call)
7840 << Object->getType() << Object->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007841 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007842 break;
7843
7844 case OR_Ambiguous:
7845 Diag(Object->getSourceRange().getBegin(),
7846 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00007847 << Object->getType() << Object->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007848 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007849 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007850
7851 case OR_Deleted:
7852 Diag(Object->getSourceRange().getBegin(),
7853 diag::err_ovl_deleted_object_call)
7854 << Best->Function->isDeleted()
7855 << Object->getType() << Object->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00007856 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007857 break;
Mike Stump1eb44332009-09-09 15:08:12 +00007858 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007859
Douglas Gregorff331c12010-07-25 18:17:45 +00007860 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007861 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007862
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007863 if (Best->Function == 0) {
7864 // Since there is no function declaration, this is one of the
7865 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00007866 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007867 = cast<CXXConversionDecl>(
7868 Best->Conversions[0].UserDefined.ConversionFunction);
7869
John McCall9aa472c2010-03-19 07:35:19 +00007870 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007871 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00007872
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007873 // We selected one of the surrogate functions that converts the
7874 // object parameter to a function pointer. Perform the conversion
7875 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00007876
7877 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00007878 // and then call it.
John McCall6bb80172010-03-30 21:47:33 +00007879 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7880 Conv);
Fariborz Jahanianb7400232009-09-28 23:23:40 +00007881
John McCallf312b1e2010-08-26 23:41:50 +00007882 return ActOnCallExpr(S, CE, LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00007883 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007884 }
7885
John McCall9aa472c2010-03-19 07:35:19 +00007886 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007887 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00007888
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007889 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7890 // that calls this method, using Object for the implicit object
7891 // parameter and passing along the remaining arguments.
7892 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall183700f2009-09-21 23:43:11 +00007893 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007894
7895 unsigned NumArgsInProto = Proto->getNumArgs();
7896 unsigned NumArgsToCheck = NumArgs;
7897
7898 // Build the full argument list for the method call (the
7899 // implicit object parameter is placed at the beginning of the
7900 // list).
7901 Expr **MethodArgs;
7902 if (NumArgs < NumArgsInProto) {
7903 NumArgsToCheck = NumArgsInProto;
7904 MethodArgs = new Expr*[NumArgsInProto + 1];
7905 } else {
7906 MethodArgs = new Expr*[NumArgs + 1];
7907 }
7908 MethodArgs[0] = Object;
7909 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7910 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00007911
7912 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00007913 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007914 UsualUnaryConversions(NewFn);
7915
7916 // Once we've built TheCall, all of the expressions are properly
7917 // owned.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007918 QualType ResultTy = Method->getCallResultType();
John McCall9ae2f072010-08-23 23:25:46 +00007919 CXXOperatorCallExpr *TheCall =
7920 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
7921 MethodArgs, NumArgs + 1,
7922 ResultTy, RParenLoc);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007923 delete [] MethodArgs;
7924
John McCall9ae2f072010-08-23 23:25:46 +00007925 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +00007926 Method))
7927 return true;
7928
Douglas Gregor518fda12009-01-13 05:10:00 +00007929 // We may have default arguments. If so, we need to allocate more
7930 // slots in the call for them.
7931 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00007932 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00007933 else if (NumArgs > NumArgsInProto)
7934 NumArgsToCheck = NumArgsInProto;
7935
Chris Lattner312531a2009-04-12 08:11:20 +00007936 bool IsError = false;
7937
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007938 // Initialize the implicit object parameter.
Douglas Gregor5fccd362010-03-03 23:55:11 +00007939 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007940 Best->FoundDecl, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007941 TheCall->setArg(0, Object);
7942
Chris Lattner312531a2009-04-12 08:11:20 +00007943
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007944 // Check the argument types.
7945 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007946 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00007947 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007948 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00007949
Douglas Gregor518fda12009-01-13 05:10:00 +00007950 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +00007951
John McCall60d7b3a2010-08-24 06:29:42 +00007952 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +00007953 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00007954 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +00007955 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +00007956 SourceLocation(), Arg);
Anders Carlsson3faa4862010-01-29 18:43:53 +00007957
7958 IsError |= InputInit.isInvalid();
7959 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00007960 } else {
John McCall60d7b3a2010-08-24 06:29:42 +00007961 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +00007962 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7963 if (DefArg.isInvalid()) {
7964 IsError = true;
7965 break;
7966 }
7967
7968 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00007969 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007970
7971 TheCall->setArg(i + 1, Arg);
7972 }
7973
7974 // If this is a variadic call, handle args passed through "...".
7975 if (Proto->isVariadic()) {
7976 // Promote the arguments (C99 6.5.2.2p7).
7977 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7978 Expr *Arg = Args[i];
Chris Lattner40378332010-05-16 04:01:30 +00007979 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007980 TheCall->setArg(i + 1, Arg);
7981 }
7982 }
7983
Chris Lattner312531a2009-04-12 08:11:20 +00007984 if (IsError) return true;
7985
John McCall9ae2f072010-08-23 23:25:46 +00007986 if (CheckFunctionCall(Method, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00007987 return true;
7988
John McCall182f7092010-08-24 06:09:16 +00007989 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007990}
7991
Douglas Gregor8ba10742008-11-20 16:27:02 +00007992/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00007993/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00007994/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +00007995ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00007996Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00007997 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00007998
John McCall5769d612010-02-08 23:07:23 +00007999 SourceLocation Loc = Base->getExprLoc();
8000
Douglas Gregor8ba10742008-11-20 16:27:02 +00008001 // C++ [over.ref]p1:
8002 //
8003 // [...] An expression x->m is interpreted as (x.operator->())->m
8004 // for a class object x of type T if T::operator->() exists and if
8005 // the operator is selected as the best match function by the
8006 // overload resolution mechanism (13.3).
Douglas Gregor8ba10742008-11-20 16:27:02 +00008007 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +00008008 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +00008009 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008010
John McCall5769d612010-02-08 23:07:23 +00008011 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +00008012 PDiag(diag::err_typecheck_incomplete_tag)
8013 << Base->getSourceRange()))
8014 return ExprError();
8015
John McCalla24dc2e2009-11-17 02:14:36 +00008016 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
8017 LookupQualifiedName(R, BaseRecord->getDecl());
8018 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00008019
8020 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00008021 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00008022 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00008023 /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00008024 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00008025
8026 // Perform overload resolution.
8027 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00008028 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00008029 case OR_Success:
8030 // Overload resolution succeeded; we'll build the call below.
8031 break;
8032
8033 case OR_No_Viable_Function:
8034 if (CandidateSet.empty())
8035 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008036 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00008037 else
8038 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008039 << "operator->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008040 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008041 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00008042
8043 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00008044 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8045 << "->" << Base->getType() << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008046 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008047 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008048
8049 case OR_Deleted:
8050 Diag(OpLoc, diag::err_ovl_deleted_oper)
8051 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00008052 << "->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008053 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008054 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00008055 }
8056
John McCall9aa472c2010-03-19 07:35:19 +00008057 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00008058 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +00008059
Douglas Gregor8ba10742008-11-20 16:27:02 +00008060 // Convert the object parameter.
8061 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00008062 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
8063 Best->FoundDecl, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00008064 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00008065
Douglas Gregor8ba10742008-11-20 16:27:02 +00008066 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00008067 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
8068 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00008069 UsualUnaryConversions(FnExpr);
Anders Carlsson15ea3782009-10-13 22:43:21 +00008070
Douglas Gregor5291c3c2010-07-13 08:18:22 +00008071 QualType ResultTy = Method->getCallResultType();
John McCall9ae2f072010-08-23 23:25:46 +00008072 CXXOperatorCallExpr *TheCall =
8073 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
8074 &Base, 1, ResultTy, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +00008075
John McCall9ae2f072010-08-23 23:25:46 +00008076 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00008077 Method))
8078 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00008079 return Owned(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00008080}
8081
Douglas Gregor904eed32008-11-10 20:40:00 +00008082/// FixOverloadedFunctionReference - E is an expression that refers to
8083/// a C++ overloaded function (possibly with some parentheses and
8084/// perhaps a '&' around it). We have resolved the overloaded function
8085/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00008086/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +00008087Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +00008088 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00008089 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00008090 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
8091 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00008092 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00008093 return PE;
Douglas Gregor699ee522009-11-20 19:42:02 +00008094
8095 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
8096 }
8097
8098 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00008099 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
8100 Found, Fn);
Douglas Gregor097bfb12009-10-23 22:18:25 +00008101 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00008102 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00008103 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +00008104 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +00008105 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00008106 return ICE;
Douglas Gregor699ee522009-11-20 19:42:02 +00008107
John McCallf871d0c2010-08-07 06:22:56 +00008108 return ImplicitCastExpr::Create(Context, ICE->getType(),
8109 ICE->getCastKind(),
8110 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +00008111 ICE->getValueKind());
Douglas Gregor699ee522009-11-20 19:42:02 +00008112 }
8113
8114 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +00008115 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00008116 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00008117 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8118 if (Method->isStatic()) {
8119 // Do nothing: static member functions aren't any different
8120 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00008121 } else {
John McCallf7a1a742009-11-24 19:00:30 +00008122 // Fix the sub expression, which really has to be an
8123 // UnresolvedLookupExpr holding an overloaded member function
8124 // or template.
John McCall6bb80172010-03-30 21:47:33 +00008125 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8126 Found, Fn);
John McCallba135432009-11-21 08:51:07 +00008127 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00008128 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +00008129
John McCallba135432009-11-21 08:51:07 +00008130 assert(isa<DeclRefExpr>(SubExpr)
8131 && "fixed to something other than a decl ref");
8132 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
8133 && "fixed to a member ref with no nested name qualifier");
8134
8135 // We have taken the address of a pointer to member
8136 // function. Perform the computation here so that we get the
8137 // appropriate pointer to member type.
8138 QualType ClassType
8139 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
8140 QualType MemPtrType
8141 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
8142
John McCall2de56d12010-08-25 11:45:40 +00008143 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
John McCallba135432009-11-21 08:51:07 +00008144 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00008145 }
8146 }
John McCall6bb80172010-03-30 21:47:33 +00008147 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8148 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00008149 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +00008150 return UnOp;
Anders Carlsson96ad5332009-10-21 17:16:23 +00008151
John McCall2de56d12010-08-25 11:45:40 +00008152 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +00008153 Context.getPointerType(SubExpr->getType()),
8154 UnOp->getOperatorLoc());
Douglas Gregor699ee522009-11-20 19:42:02 +00008155 }
John McCallba135432009-11-21 08:51:07 +00008156
8157 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00008158 // FIXME: avoid copy.
8159 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00008160 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00008161 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
8162 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00008163 }
8164
John McCallba135432009-11-21 08:51:07 +00008165 return DeclRefExpr::Create(Context,
8166 ULE->getQualifier(),
8167 ULE->getQualifierRange(),
8168 Fn,
8169 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00008170 Fn->getType(),
8171 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00008172 }
8173
John McCall129e2df2009-11-30 22:42:35 +00008174 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00008175 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00008176 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8177 if (MemExpr->hasExplicitTemplateArgs()) {
8178 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8179 TemplateArgs = &TemplateArgsBuffer;
8180 }
John McCalld5532b62009-11-23 01:53:49 +00008181
John McCallaa81e162009-12-01 22:10:20 +00008182 Expr *Base;
8183
8184 // If we're filling in
8185 if (MemExpr->isImplicitAccess()) {
8186 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
8187 return DeclRefExpr::Create(Context,
8188 MemExpr->getQualifier(),
8189 MemExpr->getQualifierRange(),
8190 Fn,
8191 MemExpr->getMemberLoc(),
8192 Fn->getType(),
8193 TemplateArgs);
Douglas Gregor828a1972010-01-07 23:12:05 +00008194 } else {
8195 SourceLocation Loc = MemExpr->getMemberLoc();
8196 if (MemExpr->getQualifier())
8197 Loc = MemExpr->getQualifierRange().getBegin();
8198 Base = new (Context) CXXThisExpr(Loc,
8199 MemExpr->getBaseType(),
8200 /*isImplicit=*/true);
8201 }
John McCallaa81e162009-12-01 22:10:20 +00008202 } else
John McCall3fa5cae2010-10-26 07:05:15 +00008203 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +00008204
8205 return MemberExpr::Create(Context, Base,
Douglas Gregor699ee522009-11-20 19:42:02 +00008206 MemExpr->isArrow(),
8207 MemExpr->getQualifier(),
8208 MemExpr->getQualifierRange(),
8209 Fn,
John McCall6bb80172010-03-30 21:47:33 +00008210 Found,
Abramo Bagnara25777432010-08-11 22:01:17 +00008211 MemExpr->getMemberNameInfo(),
John McCallaa81e162009-12-01 22:10:20 +00008212 TemplateArgs,
Douglas Gregor699ee522009-11-20 19:42:02 +00008213 Fn->getType());
8214 }
8215
John McCall3fa5cae2010-10-26 07:05:15 +00008216 llvm_unreachable("Invalid reference to overloaded function");
8217 return E;
Douglas Gregor904eed32008-11-10 20:40:00 +00008218}
8219
John McCall60d7b3a2010-08-24 06:29:42 +00008220ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
8221 DeclAccessPair Found,
8222 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +00008223 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +00008224}
8225
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008226} // end namespace clang