blob: f8f04defb1b63e017f8fb635c5e924620ae46b4e [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
Douglas Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Sema.h"
15#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000017#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000018#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000019#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000021#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000023#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000025#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000027#include <algorithm>
28
29namespace clang {
30
31/// GetConversionCategory - Retrieve the implicit conversion
32/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000033ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000034GetConversionCategory(ImplicitConversionKind Kind) {
35 static const ImplicitConversionCategory
36 Category[(int)ICK_Num_Conversion_Kinds] = {
37 ICC_Identity,
38 ICC_Lvalue_Transformation,
39 ICC_Lvalue_Transformation,
40 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +000041 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000042 ICC_Qualification_Adjustment,
43 ICC_Promotion,
44 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000045 ICC_Promotion,
46 ICC_Conversion,
47 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000048 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000053 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000054 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +000055 ICC_Conversion,
56 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000057 ICC_Conversion
58 };
59 return Category[(int)Kind];
60}
61
62/// GetConversionRank - Retrieve the implicit conversion rank
63/// corresponding to the given implicit conversion kind.
64ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
65 static const ImplicitConversionRank
66 Rank[(int)ICK_Num_Conversion_Kinds] = {
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Exact_Match,
70 ICR_Exact_Match,
71 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +000072 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000073 ICR_Promotion,
74 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000075 ICR_Promotion,
76 ICR_Conversion,
77 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000078 ICR_Conversion,
79 ICR_Conversion,
80 ICR_Conversion,
81 ICR_Conversion,
82 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000083 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000084 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +000085 ICR_Conversion,
86 ICR_Conversion,
Chandler Carruth23a370f2010-02-25 07:20:54 +000087 ICR_Complex_Real_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000088 };
89 return Rank[(int)Kind];
90}
91
92/// GetImplicitConversionName - Return the name of this kind of
93/// implicit conversion.
94const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +000095 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000096 "No conversion",
97 "Lvalue-to-rvalue",
98 "Array-to-pointer",
99 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000100 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000101 "Qualification",
102 "Integral promotion",
103 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000104 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000105 "Integral conversion",
106 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000107 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000108 "Floating-integral conversion",
109 "Pointer conversion",
110 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000111 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000112 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000113 "Derived-to-base conversion",
114 "Vector conversion",
115 "Vector splat",
116 "Complex-real conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000117 };
118 return Name[Kind];
119}
120
Douglas Gregor60d62c22008-10-31 16:23:19 +0000121/// StandardConversionSequence - Set the standard conversion
122/// sequence to the identity conversion.
123void StandardConversionSequence::setAsIdentityConversion() {
124 First = ICK_Identity;
125 Second = ICK_Identity;
126 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000127 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000128 ReferenceBinding = false;
129 DirectBinding = false;
Sebastian Redl85002392009-03-29 22:46:24 +0000130 RRefBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000131 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000132}
133
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000134/// getRank - Retrieve the rank of this standard conversion sequence
135/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
136/// implicit conversions.
137ImplicitConversionRank StandardConversionSequence::getRank() const {
138 ImplicitConversionRank Rank = ICR_Exact_Match;
139 if (GetConversionRank(First) > Rank)
140 Rank = GetConversionRank(First);
141 if (GetConversionRank(Second) > Rank)
142 Rank = GetConversionRank(Second);
143 if (GetConversionRank(Third) > Rank)
144 Rank = GetConversionRank(Third);
145 return Rank;
146}
147
148/// isPointerConversionToBool - Determines whether this conversion is
149/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000150/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000151/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000152bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000153 // Note that FromType has not necessarily been transformed by the
154 // array-to-pointer or function-to-pointer implicit conversions, so
155 // check for their presence as well as checking whether FromType is
156 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000157 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000158 (getFromType()->isPointerType() ||
159 getFromType()->isObjCObjectPointerType() ||
160 getFromType()->isBlockPointerType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000161 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
162 return true;
163
164 return false;
165}
166
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000167/// isPointerConversionToVoidPointer - Determines whether this
168/// conversion is a conversion of a pointer to a void pointer. This is
169/// used as part of the ranking of standard conversion sequences (C++
170/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000171bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000172StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000173isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000174 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000175 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000176
177 // Note that FromType has not necessarily been transformed by the
178 // array-to-pointer implicit conversion, so check for its presence
179 // and redo the conversion to get a pointer.
180 if (First == ICK_Array_To_Pointer)
181 FromType = Context.getArrayDecayedType(FromType);
182
Douglas Gregor01919692009-12-13 21:37:05 +0000183 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000184 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000185 return ToPtrType->getPointeeType()->isVoidType();
186
187 return false;
188}
189
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000190/// DebugPrint - Print this standard conversion sequence to standard
191/// error. Useful for debugging overloading issues.
192void StandardConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000193 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000194 bool PrintedSomething = false;
195 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000196 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000197 PrintedSomething = true;
198 }
199
200 if (Second != ICK_Identity) {
201 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000202 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000203 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000204 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000205
206 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000207 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000208 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000209 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000210 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000211 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000212 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000213 PrintedSomething = true;
214 }
215
216 if (Third != ICK_Identity) {
217 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000218 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000219 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000220 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000221 PrintedSomething = true;
222 }
223
224 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000225 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000226 }
227}
228
229/// DebugPrint - Print this user-defined conversion sequence to standard
230/// error. Useful for debugging overloading issues.
231void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000232 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000233 if (Before.First || Before.Second || Before.Third) {
234 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000235 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000236 }
Benjamin Kramer900fc632010-04-17 09:33:03 +0000237 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000238 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000239 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000240 After.DebugPrint();
241 }
242}
243
244/// DebugPrint - Print this implicit conversion sequence to standard
245/// error. Useful for debugging overloading issues.
246void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000247 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000248 switch (ConversionKind) {
249 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000250 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000251 Standard.DebugPrint();
252 break;
253 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000254 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000255 UserDefined.DebugPrint();
256 break;
257 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000258 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000259 break;
John McCall1d318332010-01-12 00:44:57 +0000260 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000261 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000262 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000263 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000264 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000265 break;
266 }
267
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000268 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000269}
270
John McCall1d318332010-01-12 00:44:57 +0000271void AmbiguousConversionSequence::construct() {
272 new (&conversions()) ConversionSet();
273}
274
275void AmbiguousConversionSequence::destruct() {
276 conversions().~ConversionSet();
277}
278
279void
280AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
281 FromTypePtr = O.FromTypePtr;
282 ToTypePtr = O.ToTypePtr;
283 new (&conversions()) ConversionSet(O.conversions());
284}
285
Douglas Gregora9333192010-05-08 17:41:32 +0000286namespace {
287 // Structure used by OverloadCandidate::DeductionFailureInfo to store
288 // template parameter and template argument information.
289 struct DFIParamWithArguments {
290 TemplateParameter Param;
291 TemplateArgument FirstArg;
292 TemplateArgument SecondArg;
293 };
294}
295
296/// \brief Convert from Sema's representation of template deduction information
297/// to the form used in overload-candidate information.
298OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000299static MakeDeductionFailureInfo(ASTContext &Context,
300 Sema::TemplateDeductionResult TDK,
Douglas Gregorec20f462010-05-08 20:07:26 +0000301 Sema::TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000302 OverloadCandidate::DeductionFailureInfo Result;
303 Result.Result = static_cast<unsigned>(TDK);
304 Result.Data = 0;
305 switch (TDK) {
306 case Sema::TDK_Success:
307 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000308 case Sema::TDK_TooManyArguments:
309 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000310 break;
311
312 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000313 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000314 Result.Data = Info.Param.getOpaqueValue();
315 break;
316
Douglas Gregora9333192010-05-08 17:41:32 +0000317 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000318 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000319 // FIXME: Should allocate from normal heap so that we can free this later.
320 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000321 Saved->Param = Info.Param;
322 Saved->FirstArg = Info.FirstArg;
323 Saved->SecondArg = Info.SecondArg;
324 Result.Data = Saved;
325 break;
326 }
327
328 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000329 Result.Data = Info.take();
330 break;
331
Douglas Gregora9333192010-05-08 17:41:32 +0000332 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000333 case Sema::TDK_FailedOverloadResolution:
334 break;
335 }
336
337 return Result;
338}
John McCall1d318332010-01-12 00:44:57 +0000339
Douglas Gregora9333192010-05-08 17:41:32 +0000340void OverloadCandidate::DeductionFailureInfo::Destroy() {
341 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
342 case Sema::TDK_Success:
343 case Sema::TDK_InstantiationDepth:
344 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000345 case Sema::TDK_TooManyArguments:
346 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000347 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000348 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 Gregoraaa045d2010-05-08 20:20:05 +0000352 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000353 Data = 0;
354 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000355
356 case Sema::TDK_SubstitutionFailure:
357 // FIXME: Destroy the template arugment list?
358 Data = 0;
359 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000360
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000361 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000362 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000363 case Sema::TDK_FailedOverloadResolution:
364 break;
365 }
366}
367
368TemplateParameter
369OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
370 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
371 case Sema::TDK_Success:
372 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000373 case Sema::TDK_TooManyArguments:
374 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000375 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000376 return TemplateParameter();
377
378 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000379 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000380 return TemplateParameter::getFromOpaqueValue(Data);
381
382 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000383 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000384 return static_cast<DFIParamWithArguments*>(Data)->Param;
385
386 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000387 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000388 case Sema::TDK_FailedOverloadResolution:
389 break;
390 }
391
392 return TemplateParameter();
393}
Douglas Gregorec20f462010-05-08 20:07:26 +0000394
395TemplateArgumentList *
396OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
397 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
398 case Sema::TDK_Success:
399 case Sema::TDK_InstantiationDepth:
400 case Sema::TDK_TooManyArguments:
401 case Sema::TDK_TooFewArguments:
402 case Sema::TDK_Incomplete:
403 case Sema::TDK_InvalidExplicitArguments:
404 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000405 case Sema::TDK_Underqualified:
Douglas Gregorec20f462010-05-08 20:07:26 +0000406 return 0;
407
408 case Sema::TDK_SubstitutionFailure:
409 return static_cast<TemplateArgumentList*>(Data);
410
411 // Unhandled
412 case Sema::TDK_NonDeducedMismatch:
413 case Sema::TDK_FailedOverloadResolution:
414 break;
415 }
416
417 return 0;
418}
419
Douglas Gregora9333192010-05-08 17:41:32 +0000420const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
421 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
422 case Sema::TDK_Success:
423 case Sema::TDK_InstantiationDepth:
424 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000425 case Sema::TDK_TooManyArguments:
426 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000427 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000428 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000429 return 0;
430
Douglas Gregora9333192010-05-08 17:41:32 +0000431 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000432 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000433 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
434
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000435 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000436 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000437 case Sema::TDK_FailedOverloadResolution:
438 break;
439 }
440
441 return 0;
442}
443
444const TemplateArgument *
445OverloadCandidate::DeductionFailureInfo::getSecondArg() {
446 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
447 case Sema::TDK_Success:
448 case Sema::TDK_InstantiationDepth:
449 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000450 case Sema::TDK_TooManyArguments:
451 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000452 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000453 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000454 return 0;
455
Douglas Gregora9333192010-05-08 17:41:32 +0000456 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000457 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000458 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
459
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000460 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000461 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000462 case Sema::TDK_FailedOverloadResolution:
463 break;
464 }
465
466 return 0;
467}
468
469void OverloadCandidateSet::clear() {
Douglas Gregora9333192010-05-08 17:41:32 +0000470 inherited::clear();
471 Functions.clear();
472}
473
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000474// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000475// overload of the declarations in Old. This routine returns false if
476// New and Old cannot be overloaded, e.g., if New has the same
477// signature as some function in Old (C++ 1.3.10) or if the Old
478// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000479// it does return false, MatchedDecl will point to the decl that New
480// cannot be overloaded with. This decl may be a UsingShadowDecl on
481// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000482//
483// Example: Given the following input:
484//
485// void f(int, float); // #1
486// void f(int, int); // #2
487// int f(int, int); // #3
488//
489// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000490// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000491//
John McCall51fa86f2009-12-02 08:47:38 +0000492// When we process #2, Old contains only the FunctionDecl for #1. By
493// comparing the parameter types, we see that #1 and #2 are overloaded
494// (since they have different signatures), so this routine returns
495// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000496//
John McCall51fa86f2009-12-02 08:47:38 +0000497// When we process #3, Old is an overload set containing #1 and #2. We
498// compare the signatures of #3 to #1 (they're overloaded, so we do
499// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
500// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000501// signature), IsOverload returns false and MatchedDecl will be set to
502// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000503//
504// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
505// into a class by a using declaration. The rules for whether to hide
506// shadow declarations ignore some properties which otherwise figure
507// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000508Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000509Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
510 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000511 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000512 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000513 NamedDecl *OldD = *I;
514
515 bool OldIsUsingDecl = false;
516 if (isa<UsingShadowDecl>(OldD)) {
517 OldIsUsingDecl = true;
518
519 // We can always introduce two using declarations into the same
520 // context, even if they have identical signatures.
521 if (NewIsUsingDecl) continue;
522
523 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
524 }
525
526 // If either declaration was introduced by a using declaration,
527 // we'll need to use slightly different rules for matching.
528 // Essentially, these rules are the normal rules, except that
529 // function templates hide function templates with different
530 // return types or template parameter lists.
531 bool UseMemberUsingDeclRules =
532 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
533
John McCall51fa86f2009-12-02 08:47:38 +0000534 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000535 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
536 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
537 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
538 continue;
539 }
540
John McCall871b2e72009-12-09 03:35:25 +0000541 Match = *I;
542 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000543 }
John McCall51fa86f2009-12-02 08:47:38 +0000544 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000545 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
546 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
547 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
548 continue;
549 }
550
John McCall871b2e72009-12-09 03:35:25 +0000551 Match = *I;
552 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000553 }
John McCall9f54ad42009-12-10 09:41:52 +0000554 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
555 // We can overload with these, which can show up when doing
556 // redeclaration checks for UsingDecls.
557 assert(Old.getLookupKind() == LookupUsingDeclName);
558 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
559 // Optimistically assume that an unresolved using decl will
560 // overload; if it doesn't, we'll have to diagnose during
561 // template instantiation.
562 } else {
John McCall68263142009-11-18 22:49:29 +0000563 // (C++ 13p1):
564 // Only function declarations can be overloaded; object and type
565 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000566 Match = *I;
567 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000568 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000569 }
John McCall68263142009-11-18 22:49:29 +0000570
John McCall871b2e72009-12-09 03:35:25 +0000571 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000572}
573
John McCallad00b772010-06-16 08:42:20 +0000574bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
575 bool UseUsingDeclRules) {
John McCall7b492022010-08-12 07:09:11 +0000576 // If both of the functions are extern "C", then they are not
577 // overloads.
578 if (Old->isExternC() && New->isExternC())
579 return false;
580
John McCall68263142009-11-18 22:49:29 +0000581 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
582 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
583
584 // C++ [temp.fct]p2:
585 // A function template can be overloaded with other function templates
586 // and with normal (non-template) functions.
587 if ((OldTemplate == 0) != (NewTemplate == 0))
588 return true;
589
590 // Is the function New an overload of the function Old?
591 QualType OldQType = Context.getCanonicalType(Old->getType());
592 QualType NewQType = Context.getCanonicalType(New->getType());
593
594 // Compare the signatures (C++ 1.3.10) of the two functions to
595 // determine whether they are overloads. If we find any mismatch
596 // in the signature, they are overloads.
597
598 // If either of these functions is a K&R-style function (no
599 // prototype), then we consider them to have matching signatures.
600 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
601 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
602 return false;
603
604 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
605 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
606
607 // The signature of a function includes the types of its
608 // parameters (C++ 1.3.10), which includes the presence or absence
609 // of the ellipsis; see C++ DR 357).
610 if (OldQType != NewQType &&
611 (OldType->getNumArgs() != NewType->getNumArgs() ||
612 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000613 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000614 return true;
615
616 // C++ [temp.over.link]p4:
617 // The signature of a function template consists of its function
618 // signature, its return type and its template parameter list. The names
619 // of the template parameters are significant only for establishing the
620 // relationship between the template parameters and the rest of the
621 // signature.
622 //
623 // We check the return type and template parameter lists for function
624 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +0000625 //
626 // However, we don't consider either of these when deciding whether
627 // a member introduced by a shadow declaration is hidden.
628 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +0000629 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
630 OldTemplate->getTemplateParameters(),
631 false, TPL_TemplateMatch) ||
632 OldType->getResultType() != NewType->getResultType()))
633 return true;
634
635 // If the function is a class member, its signature includes the
636 // cv-qualifiers (if any) on the function itself.
637 //
638 // As part of this, also check whether one of the member functions
639 // is static, in which case they are not overloads (C++
640 // 13.1p2). While not part of the definition of the signature,
641 // this check is important to determine whether these functions
642 // can be overloaded.
643 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
644 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
645 if (OldMethod && NewMethod &&
646 !OldMethod->isStatic() && !NewMethod->isStatic() &&
647 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
648 return true;
649
650 // The signatures match; this is not an overload.
651 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000652}
653
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000654/// TryImplicitConversion - Attempt to perform an implicit conversion
655/// from the given expression (Expr) to the given type (ToType). This
656/// function returns an implicit conversion sequence that can be used
657/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000658///
659/// void f(float f);
660/// void g(int i) { f(i); }
661///
662/// this routine would produce an implicit conversion sequence to
663/// describe the initialization of f from i, which will be a standard
664/// conversion sequence containing an lvalue-to-rvalue conversion (C++
665/// 4.1) followed by a floating-integral conversion (C++ 4.9).
666//
667/// Note that this routine only determines how the conversion can be
668/// performed; it does not actually perform the conversion. As such,
669/// it will not produce any diagnostics if no conversion is available,
670/// but will instead return an implicit conversion sequence of kind
671/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000672///
673/// If @p SuppressUserConversions, then user-defined conversions are
674/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000675/// If @p AllowExplicit, then explicit user-defined conversions are
676/// permitted.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000677ImplicitConversionSequence
Anders Carlsson2974b5c2009-08-27 17:14:02 +0000678Sema::TryImplicitConversion(Expr* From, QualType ToType,
679 bool SuppressUserConversions,
Douglas Gregor74e386e2010-04-16 18:00:29 +0000680 bool AllowExplicit,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000681 bool InOverloadResolution) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000682 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +0000683 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
John McCall1d318332010-01-12 00:44:57 +0000684 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +0000685 return ICS;
686 }
687
688 if (!getLangOptions().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +0000689 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +0000690 return ICS;
691 }
692
Douglas Gregor604eb652010-08-11 02:15:33 +0000693 // C++ [over.ics.user]p4:
694 // A conversion of an expression of class type to the same class
695 // type is given Exact Match rank, and a conversion of an
696 // expression of class type to a base class of that type is
697 // given Conversion rank, in spite of the fact that a copy/move
698 // constructor (i.e., a user-defined conversion function) is
699 // called for those cases.
700 QualType FromType = From->getType();
701 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
702 (Context.hasSameUnqualifiedType(FromType, ToType) ||
703 IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000704 ICS.setStandard();
705 ICS.Standard.setAsIdentityConversion();
706 ICS.Standard.setFromType(FromType);
707 ICS.Standard.setAllToTypes(ToType);
708
709 // We don't actually check at this point whether there is a valid
710 // copy/move constructor, since overloading just assumes that it
711 // exists. When we actually perform initialization, we'll find the
712 // appropriate constructor to copy the returned object, if needed.
713 ICS.Standard.CopyConstructor = 0;
Douglas Gregor604eb652010-08-11 02:15:33 +0000714
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000715 // Determine whether this is considered a derived-to-base conversion.
716 if (!Context.hasSameUnqualifiedType(FromType, ToType))
717 ICS.Standard.Second = ICK_Derived_To_Base;
Douglas Gregor604eb652010-08-11 02:15:33 +0000718
719 return ICS;
720 }
721
722 if (SuppressUserConversions) {
723 // We're not in the case above, so there is no conversion that
724 // we can perform.
725 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000726 return ICS;
727 }
728
729 // Attempt user-defined conversion.
John McCall5769d612010-02-08 23:07:23 +0000730 OverloadCandidateSet Conversions(From->getExprLoc());
731 OverloadingResult UserDefResult
732 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000733 AllowExplicit);
John McCall5769d612010-02-08 23:07:23 +0000734
735 if (UserDefResult == OR_Success) {
John McCall1d318332010-01-12 00:44:57 +0000736 ICS.setUserDefined();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000737 // C++ [over.ics.user]p4:
738 // A conversion of an expression of class type to the same class
739 // type is given Exact Match rank, and a conversion of an
740 // expression of class type to a base class of that type is
741 // given Conversion rank, in spite of the fact that a copy
742 // constructor (i.e., a user-defined conversion function) is
743 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000744 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000745 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000746 QualType FromCanon
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000747 = Context.getCanonicalType(From->getType().getUnqualifiedType());
748 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor9e9199d2009-12-22 00:34:07 +0000749 if (Constructor->isCopyConstructor() &&
Douglas Gregor0d6d12b2009-12-22 00:21:20 +0000750 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000751 // Turn this into a "standard" conversion sequence, so that it
752 // gets ranked with standard conversion sequences.
John McCall1d318332010-01-12 00:44:57 +0000753 ICS.setStandard();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000754 ICS.Standard.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +0000755 ICS.Standard.setFromType(From->getType());
Douglas Gregorad323a82010-01-27 03:51:04 +0000756 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000757 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000758 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000759 ICS.Standard.Second = ICK_Derived_To_Base;
760 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000761 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000762
763 // C++ [over.best.ics]p4:
764 // However, when considering the argument of a user-defined
765 // conversion function that is a candidate by 13.3.1.3 when
766 // invoked for the copying of the temporary in the second step
767 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
768 // 13.3.1.6 in all cases, only standard conversion sequences and
769 // ellipsis conversion sequences are allowed.
John McCalladbb8f82010-01-13 09:16:55 +0000770 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCallb1bdc622010-02-25 01:37:24 +0000771 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCalladbb8f82010-01-13 09:16:55 +0000772 }
John McCallcefd3ad2010-01-13 22:30:33 +0000773 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall1d318332010-01-12 00:44:57 +0000774 ICS.setAmbiguous();
775 ICS.Ambiguous.setFromType(From->getType());
776 ICS.Ambiguous.setToType(ToType);
777 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
778 Cand != Conversions.end(); ++Cand)
779 if (Cand->Viable)
780 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000781 } else {
John McCallb1bdc622010-02-25 01:37:24 +0000782 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000783 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000784
785 return ICS;
786}
787
Douglas Gregor575c63a2010-04-16 22:27:05 +0000788/// PerformImplicitConversion - Perform an implicit conversion of the
789/// expression From to the type ToType. Returns true if there was an
790/// error, false otherwise. The expression From is replaced with the
791/// converted expression. Flavor is the kind of conversion we're
792/// performing, used in the error message. If @p AllowExplicit,
793/// explicit user-defined conversions are permitted.
794bool
795Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
796 AssignmentAction Action, bool AllowExplicit) {
797 ImplicitConversionSequence ICS;
798 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
799}
800
801bool
802Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
803 AssignmentAction Action, bool AllowExplicit,
804 ImplicitConversionSequence& ICS) {
805 ICS = TryImplicitConversion(From, ToType,
806 /*SuppressUserConversions=*/false,
807 AllowExplicit,
808 /*InOverloadResolution=*/false);
809 return PerformImplicitConversion(From, ToType, ICS, Action);
810}
811
Douglas Gregor43c79c22009-12-09 00:47:37 +0000812/// \brief Determine whether the conversion from FromType to ToType is a valid
813/// conversion that strips "noreturn" off the nested function type.
814static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
815 QualType ToType, QualType &ResultTy) {
816 if (Context.hasSameUnqualifiedType(FromType, ToType))
817 return false;
818
819 // Strip the noreturn off the type we're converting from; noreturn can
820 // safely be removed.
821 FromType = Context.getNoReturnType(FromType, false);
822 if (!Context.hasSameUnqualifiedType(FromType, ToType))
823 return false;
824
825 ResultTy = FromType;
826 return true;
827}
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000828
829/// \brief Determine whether the conversion from FromType to ToType is a valid
830/// vector conversion.
831///
832/// \param ICK Will be set to the vector conversion kind, if this is a vector
833/// conversion.
834static bool IsVectorConversion(ASTContext &Context, QualType FromType,
835 QualType ToType, ImplicitConversionKind &ICK) {
836 // We need at least one of these types to be a vector type to have a vector
837 // conversion.
838 if (!ToType->isVectorType() && !FromType->isVectorType())
839 return false;
840
841 // Identical types require no conversions.
842 if (Context.hasSameUnqualifiedType(FromType, ToType))
843 return false;
844
845 // There are no conversions between extended vector types, only identity.
846 if (ToType->isExtVectorType()) {
847 // There are no conversions between extended vector types other than the
848 // identity conversion.
849 if (FromType->isExtVectorType())
850 return false;
851
852 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +0000853 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000854 ICK = ICK_Vector_Splat;
855 return true;
856 }
857 }
Douglas Gregor255210e2010-08-06 10:14:59 +0000858
859 // We can perform the conversion between vector types in the following cases:
860 // 1)vector types are equivalent AltiVec and GCC vector types
861 // 2)lax vector conversions are permitted and the vector types are of the
862 // same size
863 if (ToType->isVectorType() && FromType->isVectorType()) {
864 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruthc45eb9c2010-08-08 05:02:51 +0000865 (Context.getLangOptions().LaxVectorConversions &&
866 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +0000867 ICK = ICK_Vector_Conversion;
868 return true;
869 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000870 }
Douglas Gregor255210e2010-08-06 10:14:59 +0000871
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000872 return false;
873}
Douglas Gregor43c79c22009-12-09 00:47:37 +0000874
Douglas Gregor60d62c22008-10-31 16:23:19 +0000875/// IsStandardConversion - Determines whether there is a standard
876/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
877/// expression From to the type ToType. Standard conversion sequences
878/// only consider non-class types; for conversions that involve class
879/// types, use TryImplicitConversion. If a conversion exists, SCS will
880/// contain the standard conversion sequence required to perform this
881/// conversion and this routine will return true. Otherwise, this
882/// routine will return false and the value of SCS is unspecified.
Mike Stump1eb44332009-09-09 15:08:12 +0000883bool
884Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000885 bool InOverloadResolution,
Mike Stump1eb44332009-09-09 15:08:12 +0000886 StandardConversionSequence &SCS) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000887 QualType FromType = From->getType();
888
Douglas Gregor60d62c22008-10-31 16:23:19 +0000889 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000890 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +0000891 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000892 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +0000893 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000894 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000895
Douglas Gregorf9201e02009-02-11 23:02:49 +0000896 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +0000897 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +0000898 if (FromType->isRecordType() || ToType->isRecordType()) {
899 if (getLangOptions().CPlusPlus)
900 return false;
901
Mike Stump1eb44332009-09-09 15:08:12 +0000902 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000903 }
904
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000905 // The first conversion can be an lvalue-to-rvalue conversion,
906 // array-to-pointer conversion, or function-to-pointer conversion
907 // (C++ 4p1).
908
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000909 if (FromType == Context.OverloadTy) {
910 DeclAccessPair AccessPair;
911 if (FunctionDecl *Fn
912 = ResolveAddressOfOverloadedFunction(From, ToType, false,
913 AccessPair)) {
914 // We were able to resolve the address of the overloaded function,
915 // so we can convert to the type of that function.
916 FromType = Fn->getType();
917 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
918 if (!Method->isStatic()) {
919 Type *ClassType
920 = Context.getTypeDeclType(Method->getParent()).getTypePtr();
921 FromType = Context.getMemberPointerType(FromType, ClassType);
922 }
923 }
924
925 // If the "from" expression takes the address of the overloaded
926 // function, update the type of the resulting expression accordingly.
927 if (FromType->getAs<FunctionType>())
928 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
929 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
930 FromType = Context.getPointerType(FromType);
931
932 // Check that we've computed the proper type after overload resolution.
933 assert(Context.hasSameType(FromType,
934 FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
935 } else {
936 return false;
937 }
938 }
Mike Stump1eb44332009-09-09 15:08:12 +0000939 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000940 // An lvalue (3.10) of a non-function, non-array type T can be
941 // converted to an rvalue.
942 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000943 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000944 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor063daf62009-03-13 18:40:31 +0000945 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000946 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000947
948 // If T is a non-class type, the type of the rvalue is the
949 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +0000950 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
951 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000952 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000953 } else if (FromType->isArrayType()) {
954 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000955 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000956
957 // An lvalue or rvalue of type "array of N T" or "array of unknown
958 // bound of T" can be converted to an rvalue of type "pointer to
959 // T" (C++ 4.2p1).
960 FromType = Context.getArrayDecayedType(FromType);
961
962 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
963 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +0000964 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000965
966 // For the purpose of ranking in overload resolution
967 // (13.3.3.1.1), this conversion is considered an
968 // array-to-pointer conversion followed by a qualification
969 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000970 SCS.Second = ICK_Identity;
971 SCS.Third = ICK_Qualification;
Douglas Gregorad323a82010-01-27 03:51:04 +0000972 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000973 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000974 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000975 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
976 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000977 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000978
979 // An lvalue of function type T can be converted to an rvalue of
980 // type "pointer to T." The result is a pointer to the
981 // function. (C++ 4.3p1).
982 FromType = Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000983 } else {
984 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000985 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000986 }
Douglas Gregorad323a82010-01-27 03:51:04 +0000987 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000988
989 // The second conversion can be an integral promotion, floating
990 // point promotion, integral conversion, floating point conversion,
991 // floating-integral conversion, pointer conversion,
992 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +0000993 // For overloading in C, this can also be a "compatible-type"
994 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +0000995 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000996 ImplicitConversionKind SecondICK = ICK_Identity;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000997 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000998 // The unqualified versions of the types are the same: there's no
999 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001000 SCS.Second = ICK_Identity;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001001 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001002 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001003 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001004 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001005 } else if (IsFloatingPointPromotion(FromType, ToType)) {
1006 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001007 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001008 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001009 } else if (IsComplexPromotion(FromType, ToType)) {
1010 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001011 SCS.Second = ICK_Complex_Promotion;
1012 FromType = ToType.getUnqualifiedType();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001013 } else if (FromType->isIntegralOrEnumerationType() &&
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001014 ToType->isIntegralType(Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001015 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001016 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001017 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001018 } else if (FromType->isComplexType() && ToType->isComplexType()) {
1019 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001020 SCS.Second = ICK_Complex_Conversion;
1021 FromType = ToType.getUnqualifiedType();
Chandler Carruth23a370f2010-02-25 07:20:54 +00001022 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
1023 (ToType->isComplexType() && FromType->isArithmeticType())) {
1024 // Complex-real conversions (C99 6.3.1.7)
1025 SCS.Second = ICK_Complex_Real;
1026 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001027 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001028 // Floating point conversions (C++ 4.8).
1029 SCS.Second = ICK_Floating_Conversion;
1030 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001031 } else if ((FromType->isRealFloatingType() &&
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001032 ToType->isIntegralType(Context) && !ToType->isBooleanType()) ||
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001033 (FromType->isIntegralOrEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001034 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001035 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001036 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001037 FromType = ToType.getUnqualifiedType();
Anders Carlsson08972922009-08-28 15:33:32 +00001038 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1039 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001040 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001041 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001042 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregorce940492009-09-25 04:25:58 +00001043 } else if (IsMemberPointerConversion(From, FromType, ToType,
1044 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001045 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001046 SCS.Second = ICK_Pointer_Member;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001047 } else if (ToType->isBooleanType() &&
1048 (FromType->isArithmeticType() ||
1049 FromType->isEnumeralType() ||
Fariborz Jahanian1f7711d2009-12-11 21:23:13 +00001050 FromType->isAnyPointerType() ||
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001051 FromType->isBlockPointerType() ||
1052 FromType->isMemberPointerType() ||
Douglas Gregor00619622010-06-22 23:41:02 +00001053 FromType->isNullPtrType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001054 // Boolean conversions (C++ 4.12).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001055 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001056 FromType = Context.BoolTy;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001057 } else if (IsVectorConversion(Context, FromType, ToType, SecondICK)) {
1058 SCS.Second = SecondICK;
1059 FromType = ToType.getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00001060 } else if (!getLangOptions().CPlusPlus &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001061 Context.typesAreCompatible(ToType, FromType)) {
1062 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001063 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001064 FromType = ToType.getUnqualifiedType();
Douglas Gregor43c79c22009-12-09 00:47:37 +00001065 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
1066 // Treat a conversion that strips "noreturn" as an identity conversion.
1067 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001068 } else {
1069 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001070 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001071 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001072 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001073
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001074 QualType CanonFrom;
1075 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001076 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +00001077 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001078 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001079 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001080 CanonFrom = Context.getCanonicalType(FromType);
1081 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001082 } else {
1083 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001084 SCS.Third = ICK_Identity;
1085
Mike Stump1eb44332009-09-09 15:08:12 +00001086 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001087 // [...] Any difference in top-level cv-qualification is
1088 // subsumed by the initialization itself and does not constitute
1089 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001090 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +00001091 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00001092 if (CanonFrom.getLocalUnqualifiedType()
1093 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001094 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1095 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001096 FromType = ToType;
1097 CanonFrom = CanonTo;
1098 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001099 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001100 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001101
1102 // If we have not converted the argument type to the parameter type,
1103 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001104 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001105 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001106
Douglas Gregor60d62c22008-10-31 16:23:19 +00001107 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001108}
1109
1110/// IsIntegralPromotion - Determines whether the conversion from the
1111/// expression From (whose potentially-adjusted type is FromType) to
1112/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1113/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001114bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001115 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001116 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001117 if (!To) {
1118 return false;
1119 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001120
1121 // An rvalue of type char, signed char, unsigned char, short int, or
1122 // unsigned short int can be converted to an rvalue of type int if
1123 // int can represent all the values of the source type; otherwise,
1124 // the source rvalue can be converted to an rvalue of type unsigned
1125 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001126 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1127 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001128 if (// We can promote any signed, promotable integer type to an int
1129 (FromType->isSignedIntegerType() ||
1130 // We can promote any unsigned integer type whose size is
1131 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001132 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001133 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001134 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001135 }
1136
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001137 return To->getKind() == BuiltinType::UInt;
1138 }
1139
1140 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
1141 // can be converted to an rvalue of the first of the following types
1142 // that can represent all the values of its underlying type: int,
1143 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall842aef82009-12-09 09:09:27 +00001144
1145 // We pre-calculate the promotion type for enum types.
1146 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
1147 if (ToType->isIntegerType())
1148 return Context.hasSameUnqualifiedType(ToType,
1149 FromEnumType->getDecl()->getPromotionType());
1150
1151 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001152 // Determine whether the type we're converting from is signed or
1153 // unsigned.
1154 bool FromIsSigned;
1155 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall842aef82009-12-09 09:09:27 +00001156
1157 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1158 FromIsSigned = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001159
1160 // The types we'll try to promote to, in the appropriate
1161 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001162 QualType PromoteTypes[6] = {
1163 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001164 Context.LongTy, Context.UnsignedLongTy ,
1165 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001166 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001167 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001168 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1169 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001170 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001171 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1172 // We found the type that we can promote to. If this is the
1173 // type we wanted, we have a promotion. Otherwise, no
1174 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001175 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001176 }
1177 }
1178 }
1179
1180 // An rvalue for an integral bit-field (9.6) can be converted to an
1181 // rvalue of type int if int can represent all the values of the
1182 // bit-field; otherwise, it can be converted to unsigned int if
1183 // unsigned int can represent all the values of the bit-field. If
1184 // the bit-field is larger yet, no integral promotion applies to
1185 // it. If the bit-field has an enumerated type, it is treated as any
1186 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001187 // FIXME: We should delay checking of bit-fields until we actually perform the
1188 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001189 using llvm::APSInt;
1190 if (From)
1191 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001192 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001193 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001194 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1195 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1196 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001197
Douglas Gregor86f19402008-12-20 23:49:58 +00001198 // Are we promoting to an int from a bitfield that fits in an int?
1199 if (BitWidth < ToSize ||
1200 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1201 return To->getKind() == BuiltinType::Int;
1202 }
Mike Stump1eb44332009-09-09 15:08:12 +00001203
Douglas Gregor86f19402008-12-20 23:49:58 +00001204 // Are we promoting to an unsigned int from an unsigned bitfield
1205 // that fits into an unsigned int?
1206 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1207 return To->getKind() == BuiltinType::UInt;
1208 }
Mike Stump1eb44332009-09-09 15:08:12 +00001209
Douglas Gregor86f19402008-12-20 23:49:58 +00001210 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001211 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001212 }
Mike Stump1eb44332009-09-09 15:08:12 +00001213
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001214 // An rvalue of type bool can be converted to an rvalue of type int,
1215 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001216 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001217 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001218 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001219
1220 return false;
1221}
1222
1223/// IsFloatingPointPromotion - Determines whether the conversion from
1224/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1225/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001226bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001227 /// An rvalue of type float can be converted to an rvalue of type
1228 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +00001229 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1230 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001231 if (FromBuiltin->getKind() == BuiltinType::Float &&
1232 ToBuiltin->getKind() == BuiltinType::Double)
1233 return true;
1234
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001235 // C99 6.3.1.5p1:
1236 // When a float is promoted to double or long double, or a
1237 // double is promoted to long double [...].
1238 if (!getLangOptions().CPlusPlus &&
1239 (FromBuiltin->getKind() == BuiltinType::Float ||
1240 FromBuiltin->getKind() == BuiltinType::Double) &&
1241 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1242 return true;
1243 }
1244
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001245 return false;
1246}
1247
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001248/// \brief Determine if a conversion is a complex promotion.
1249///
1250/// A complex promotion is defined as a complex -> complex conversion
1251/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001252/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001253bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001254 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001255 if (!FromComplex)
1256 return false;
1257
John McCall183700f2009-09-21 23:43:11 +00001258 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001259 if (!ToComplex)
1260 return false;
1261
1262 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001263 ToComplex->getElementType()) ||
1264 IsIntegralPromotion(0, FromComplex->getElementType(),
1265 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001266}
1267
Douglas Gregorcb7de522008-11-26 23:31:11 +00001268/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1269/// the pointer type FromPtr to a pointer to type ToPointee, with the
1270/// same type qualifiers as FromPtr has on its pointee type. ToType,
1271/// if non-empty, will be a pointer to ToType that may or may not have
1272/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +00001273static QualType
1274BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001275 QualType ToPointee, QualType ToType,
1276 ASTContext &Context) {
1277 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1278 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001279 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001280
1281 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001282 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001283 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001284 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001285 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001286
1287 // Build a pointer to ToPointee. It has the right qualifiers
1288 // already.
1289 return Context.getPointerType(ToPointee);
1290 }
1291
1292 // Just build a canonical type that has the right qualifiers.
John McCall0953e762009-09-24 19:53:00 +00001293 return Context.getPointerType(
Douglas Gregora4923eb2009-11-16 21:35:15 +00001294 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1295 Quals));
Douglas Gregorcb7de522008-11-26 23:31:11 +00001296}
1297
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001298/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1299/// the FromType, which is an objective-c pointer, to ToType, which may or may
1300/// not have the right set of qualifiers.
1301static QualType
1302BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1303 QualType ToType,
1304 ASTContext &Context) {
1305 QualType CanonFromType = Context.getCanonicalType(FromType);
1306 QualType CanonToType = Context.getCanonicalType(ToType);
1307 Qualifiers Quals = CanonFromType.getQualifiers();
1308
1309 // Exact qualifier match -> return the pointer type we're converting to.
1310 if (CanonToType.getLocalQualifiers() == Quals)
1311 return ToType;
1312
1313 // Just build a canonical type that has the right qualifiers.
1314 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1315}
1316
Mike Stump1eb44332009-09-09 15:08:12 +00001317static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001318 bool InOverloadResolution,
1319 ASTContext &Context) {
1320 // Handle value-dependent integral null pointer constants correctly.
1321 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1322 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001323 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001324 return !InOverloadResolution;
1325
Douglas Gregorce940492009-09-25 04:25:58 +00001326 return Expr->isNullPointerConstant(Context,
1327 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1328 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001329}
Mike Stump1eb44332009-09-09 15:08:12 +00001330
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001331/// IsPointerConversion - Determines whether the conversion of the
1332/// expression From, which has the (possibly adjusted) type FromType,
1333/// can be converted to the type ToType via a pointer conversion (C++
1334/// 4.10). If so, returns true and places the converted type (that
1335/// might differ from ToType in its cv-qualifiers at some level) into
1336/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001337///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001338/// This routine also supports conversions to and from block pointers
1339/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1340/// pointers to interfaces. FIXME: Once we've determined the
1341/// appropriate overloading rules for Objective-C, we may want to
1342/// split the Objective-C checks into a different routine; however,
1343/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001344/// conversions, so for now they live here. IncompatibleObjC will be
1345/// set if the conversion is an allowed Objective-C conversion that
1346/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001347bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001348 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001349 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001350 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001351 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +00001352 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1353 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001354
Mike Stump1eb44332009-09-09 15:08:12 +00001355 // Conversion from a null pointer constant to any Objective-C pointer type.
1356 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001357 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001358 ConvertedType = ToType;
1359 return true;
1360 }
1361
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001362 // Blocks: Block pointers can be converted to void*.
1363 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001364 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001365 ConvertedType = ToType;
1366 return true;
1367 }
1368 // Blocks: A null pointer constant can be converted to a block
1369 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001370 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001371 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001372 ConvertedType = ToType;
1373 return true;
1374 }
1375
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001376 // If the left-hand-side is nullptr_t, the right side can be a null
1377 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001378 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001379 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001380 ConvertedType = ToType;
1381 return true;
1382 }
1383
Ted Kremenek6217b802009-07-29 21:53:49 +00001384 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001385 if (!ToTypePtr)
1386 return false;
1387
1388 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001389 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001390 ConvertedType = ToType;
1391 return true;
1392 }
Sebastian Redl07779722008-10-31 14:43:28 +00001393
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001394 // Beyond this point, both types need to be pointers
1395 // , including objective-c pointers.
1396 QualType ToPointeeType = ToTypePtr->getPointeeType();
1397 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1398 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1399 ToType, Context);
1400 return true;
1401
1402 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001403 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001404 if (!FromTypePtr)
1405 return false;
1406
1407 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001408
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00001409 // If the unqualified pointee types are the same, this can't be a
1410 // pointer conversion, so don't do all of the work below.
1411 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1412 return false;
1413
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001414 // An rvalue of type "pointer to cv T," where T is an object type,
1415 // can be converted to an rvalue of type "pointer to cv void" (C++
1416 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00001417 if (FromPointeeType->isIncompleteOrObjectType() &&
1418 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001419 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001420 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001421 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001422 return true;
1423 }
1424
Douglas Gregorf9201e02009-02-11 23:02:49 +00001425 // When we're overloading in C, we allow a special kind of pointer
1426 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001427 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001428 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001429 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001430 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001431 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001432 return true;
1433 }
1434
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001435 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001436 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001437 // An rvalue of type "pointer to cv D," where D is a class type,
1438 // can be converted to an rvalue of type "pointer to cv B," where
1439 // B is a base class (clause 10) of D. If B is an inaccessible
1440 // (clause 11) or ambiguous (10.2) base class of D, a program that
1441 // necessitates this conversion is ill-formed. The result of the
1442 // conversion is a pointer to the base class sub-object of the
1443 // derived class object. The null pointer value is converted to
1444 // the null pointer value of the destination type.
1445 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001446 // Note that we do not check for ambiguity or inaccessibility
1447 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001448 if (getLangOptions().CPlusPlus &&
1449 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001450 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001451 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001452 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001453 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001454 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001455 ToType, Context);
1456 return true;
1457 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001458
Douglas Gregorc7887512008-12-19 19:13:09 +00001459 return false;
1460}
1461
1462/// isObjCPointerConversion - Determines whether this is an
1463/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1464/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001465bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001466 QualType& ConvertedType,
1467 bool &IncompatibleObjC) {
1468 if (!getLangOptions().ObjC1)
1469 return false;
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001470
Steve Naroff14108da2009-07-10 23:34:53 +00001471 // First, we handle all conversions on ObjC object pointer types.
John McCall183700f2009-09-21 23:43:11 +00001472 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001473 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001474 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001475
Steve Naroff14108da2009-07-10 23:34:53 +00001476 if (ToObjCPtr && FromObjCPtr) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00001477 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001478 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001479 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001480 ConvertedType = ToType;
1481 return true;
1482 }
1483 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001484 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001485 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001486 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001487 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001488 ConvertedType = ToType;
1489 return true;
1490 }
1491 // Objective C++: We're able to convert from a pointer to an
1492 // interface to a pointer to a different interface.
1493 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00001494 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1495 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1496 if (getLangOptions().CPlusPlus && LHS && RHS &&
1497 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1498 FromObjCPtr->getPointeeType()))
1499 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00001500 ConvertedType = ToType;
1501 return true;
1502 }
1503
1504 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1505 // Okay: this is some kind of implicit downcast of Objective-C
1506 // interfaces, which is permitted. However, we're going to
1507 // complain about it.
1508 IncompatibleObjC = true;
1509 ConvertedType = FromType;
1510 return true;
1511 }
Mike Stump1eb44332009-09-09 15:08:12 +00001512 }
Steve Naroff14108da2009-07-10 23:34:53 +00001513 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001514 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001515 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001516 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001517 else if (const BlockPointerType *ToBlockPtr =
1518 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00001519 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001520 // to a block pointer type.
1521 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1522 ConvertedType = ToType;
1523 return true;
1524 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001525 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001526 }
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001527 else if (FromType->getAs<BlockPointerType>() &&
1528 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1529 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00001530 // pointer to any object.
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001531 ConvertedType = ToType;
1532 return true;
1533 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001534 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001535 return false;
1536
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001537 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001538 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001539 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001540 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001541 FromPointeeType = FromBlockPtr->getPointeeType();
1542 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001543 return false;
1544
Douglas Gregorc7887512008-12-19 19:13:09 +00001545 // If we have pointers to pointers, recursively check whether this
1546 // is an Objective-C conversion.
1547 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1548 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1549 IncompatibleObjC)) {
1550 // We always complain about this conversion.
1551 IncompatibleObjC = true;
1552 ConvertedType = ToType;
1553 return true;
1554 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001555 // Allow conversion of pointee being objective-c pointer to another one;
1556 // as in I* to id.
1557 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1558 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1559 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1560 IncompatibleObjC)) {
1561 ConvertedType = ToType;
1562 return true;
1563 }
1564
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001565 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001566 // differences in the argument and result types are in Objective-C
1567 // pointer conversions. If so, we permit the conversion (but
1568 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001569 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001570 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001571 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001572 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001573 if (FromFunctionType && ToFunctionType) {
1574 // If the function types are exactly the same, this isn't an
1575 // Objective-C pointer conversion.
1576 if (Context.getCanonicalType(FromPointeeType)
1577 == Context.getCanonicalType(ToPointeeType))
1578 return false;
1579
1580 // Perform the quick checks that will tell us whether these
1581 // function types are obviously different.
1582 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1583 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1584 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1585 return false;
1586
1587 bool HasObjCConversion = false;
1588 if (Context.getCanonicalType(FromFunctionType->getResultType())
1589 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1590 // Okay, the types match exactly. Nothing to do.
1591 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1592 ToFunctionType->getResultType(),
1593 ConvertedType, IncompatibleObjC)) {
1594 // Okay, we have an Objective-C pointer conversion.
1595 HasObjCConversion = true;
1596 } else {
1597 // Function types are too different. Abort.
1598 return false;
1599 }
Mike Stump1eb44332009-09-09 15:08:12 +00001600
Douglas Gregorc7887512008-12-19 19:13:09 +00001601 // Check argument types.
1602 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1603 ArgIdx != NumArgs; ++ArgIdx) {
1604 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1605 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1606 if (Context.getCanonicalType(FromArgType)
1607 == Context.getCanonicalType(ToArgType)) {
1608 // Okay, the types match exactly. Nothing to do.
1609 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1610 ConvertedType, IncompatibleObjC)) {
1611 // Okay, we have an Objective-C pointer conversion.
1612 HasObjCConversion = true;
1613 } else {
1614 // Argument types are too different. Abort.
1615 return false;
1616 }
1617 }
1618
1619 if (HasObjCConversion) {
1620 // We had an Objective-C conversion. Allow this pointer
1621 // conversion, but complain about it.
1622 ConvertedType = ToType;
1623 IncompatibleObjC = true;
1624 return true;
1625 }
1626 }
1627
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001628 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001629}
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001630
1631/// FunctionArgTypesAreEqual - This routine checks two function proto types
1632/// for equlity of their argument types. Caller has already checked that
1633/// they have same number of arguments. This routine assumes that Objective-C
1634/// pointer types which only differ in their protocol qualifiers are equal.
1635bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1636 FunctionProtoType* NewType){
1637 if (!getLangOptions().ObjC1)
1638 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1639 NewType->arg_type_begin());
1640
1641 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1642 N = NewType->arg_type_begin(),
1643 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1644 QualType ToType = (*O);
1645 QualType FromType = (*N);
1646 if (ToType != FromType) {
1647 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1648 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00001649 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1650 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1651 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1652 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001653 continue;
1654 }
John McCallc12c5bb2010-05-15 11:32:37 +00001655 else if (const ObjCObjectPointerType *PTTo =
1656 ToType->getAs<ObjCObjectPointerType>()) {
1657 if (const ObjCObjectPointerType *PTFr =
1658 FromType->getAs<ObjCObjectPointerType>())
1659 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1660 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001661 }
1662 return false;
1663 }
1664 }
1665 return true;
1666}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001667
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001668/// CheckPointerConversion - Check the pointer conversion from the
1669/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001670/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001671/// conversions for which IsPointerConversion has already returned
1672/// true. It returns true and produces a diagnostic if there was an
1673/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001674bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001675 CastExpr::CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001676 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001677 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001678 QualType FromType = From->getType();
1679
Douglas Gregord7a95972010-06-08 17:35:15 +00001680 if (CXXBoolLiteralExpr* LitBool
1681 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
1682 if (LitBool->getValue() == false)
1683 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1684 << ToType;
1685
Ted Kremenek6217b802009-07-29 21:53:49 +00001686 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1687 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001688 QualType FromPointeeType = FromPtrType->getPointeeType(),
1689 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001690
Douglas Gregor5fccd362010-03-03 23:55:11 +00001691 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1692 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001693 // We must have a derived-to-base conversion. Check an
1694 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001695 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1696 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001697 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001698 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001699 return true;
1700
1701 // The conversion was successful.
1702 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001703 }
1704 }
Mike Stump1eb44332009-09-09 15:08:12 +00001705 if (const ObjCObjectPointerType *FromPtrType =
John McCall183700f2009-09-21 23:43:11 +00001706 FromType->getAs<ObjCObjectPointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001707 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00001708 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001709 // Objective-C++ conversions are always okay.
1710 // FIXME: We should have a different class of conversions for the
1711 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001712 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001713 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001714
Steve Naroff14108da2009-07-10 23:34:53 +00001715 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001716 return false;
1717}
1718
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001719/// IsMemberPointerConversion - Determines whether the conversion of the
1720/// expression From, which has the (possibly adjusted) type FromType, can be
1721/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1722/// If so, returns true and places the converted type (that might differ from
1723/// ToType in its cv-qualifiers at some level) into ConvertedType.
1724bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregorce940492009-09-25 04:25:58 +00001725 QualType ToType,
1726 bool InOverloadResolution,
1727 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001728 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001729 if (!ToTypePtr)
1730 return false;
1731
1732 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00001733 if (From->isNullPointerConstant(Context,
1734 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1735 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001736 ConvertedType = ToType;
1737 return true;
1738 }
1739
1740 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001741 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001742 if (!FromTypePtr)
1743 return false;
1744
1745 // A pointer to member of B can be converted to a pointer to member of D,
1746 // where D is derived from B (C++ 4.11p2).
1747 QualType FromClass(FromTypePtr->getClass(), 0);
1748 QualType ToClass(ToTypePtr->getClass(), 0);
1749 // FIXME: What happens when these are dependent? Is this function even called?
1750
1751 if (IsDerivedFrom(ToClass, FromClass)) {
1752 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1753 ToClass.getTypePtr());
1754 return true;
1755 }
1756
1757 return false;
1758}
Douglas Gregor43c79c22009-12-09 00:47:37 +00001759
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001760/// CheckMemberPointerConversion - Check the member pointer conversion from the
1761/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00001762/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001763/// for which IsMemberPointerConversion has already returned true. It returns
1764/// true and produces a diagnostic if there was an error, or returns false
1765/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001766bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001767 CastExpr::CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001768 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001769 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001770 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001771 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001772 if (!FromPtrType) {
1773 // This must be a null pointer to member pointer conversion
Douglas Gregorce940492009-09-25 04:25:58 +00001774 assert(From->isNullPointerConstant(Context,
1775 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001776 "Expr must be null pointer constant!");
1777 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001778 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001779 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001780
Ted Kremenek6217b802009-07-29 21:53:49 +00001781 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001782 assert(ToPtrType && "No member pointer cast has a target type "
1783 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001784
Sebastian Redl21593ac2009-01-28 18:33:18 +00001785 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1786 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001787
Sebastian Redl21593ac2009-01-28 18:33:18 +00001788 // FIXME: What about dependent types?
1789 assert(FromClass->isRecordType() && "Pointer into non-class.");
1790 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001791
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001792 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001793 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00001794 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1795 assert(DerivationOkay &&
1796 "Should not have been called if derivation isn't OK.");
1797 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001798
Sebastian Redl21593ac2009-01-28 18:33:18 +00001799 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1800 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001801 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1802 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1803 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1804 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001805 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001806
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001807 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001808 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1809 << FromClass << ToClass << QualType(VBase, 0)
1810 << From->getSourceRange();
1811 return true;
1812 }
1813
John McCall6b2accb2010-02-10 09:31:12 +00001814 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00001815 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1816 Paths.front(),
1817 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00001818
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001819 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001820 BuildBasePathArray(Paths, BasePath);
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001821 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001822 return false;
1823}
1824
Douglas Gregor98cd5992008-10-21 23:43:52 +00001825/// IsQualificationConversion - Determines whether the conversion from
1826/// an rvalue of type FromType to ToType is a qualification conversion
1827/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001828bool
1829Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001830 FromType = Context.getCanonicalType(FromType);
1831 ToType = Context.getCanonicalType(ToType);
1832
1833 // If FromType and ToType are the same type, this is not a
1834 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00001835 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00001836 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001837
Douglas Gregor98cd5992008-10-21 23:43:52 +00001838 // (C++ 4.4p4):
1839 // A conversion can add cv-qualifiers at levels other than the first
1840 // in multi-level pointers, subject to the following rules: [...]
1841 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001842 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00001843 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001844 // Within each iteration of the loop, we check the qualifiers to
1845 // determine if this still looks like a qualification
1846 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001847 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001848 // until there are no more pointers or pointers-to-members left to
1849 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001850 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001851
1852 // -- for every j > 0, if const is in cv 1,j then const is in cv
1853 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001854 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001855 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001856
Douglas Gregor98cd5992008-10-21 23:43:52 +00001857 // -- if the cv 1,j and cv 2,j are different, then const is in
1858 // every cv for 0 < k < j.
1859 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001860 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001861 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001862
Douglas Gregor98cd5992008-10-21 23:43:52 +00001863 // Keep track of whether all prior cv-qualifiers in the "to" type
1864 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00001865 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00001866 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001867 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001868
1869 // We are left with FromType and ToType being the pointee types
1870 // after unwrapping the original FromType and ToType the same number
1871 // of types. If we unwrapped any pointers, and if FromType and
1872 // ToType have the same unqualified type (since we checked
1873 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001874 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00001875}
1876
Douglas Gregor734d9862009-01-30 23:27:23 +00001877/// Determines whether there is a user-defined conversion sequence
1878/// (C++ [over.ics.user]) that converts expression From to the type
1879/// ToType. If such a conversion exists, User will contain the
1880/// user-defined conversion sequence that performs such a conversion
1881/// and this routine will return true. Otherwise, this routine returns
1882/// false and User is unspecified.
1883///
Douglas Gregor734d9862009-01-30 23:27:23 +00001884/// \param AllowExplicit true if the conversion should consider C++0x
1885/// "explicit" conversion functions as well as non-explicit conversion
1886/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor20093b42009-12-09 23:02:17 +00001887OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1888 UserDefinedConversionSequence& User,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001889 OverloadCandidateSet& CandidateSet,
1890 bool AllowExplicit) {
1891 // Whether we will only visit constructors.
1892 bool ConstructorsOnly = false;
1893
1894 // If the type we are conversion to is a class type, enumerate its
1895 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00001896 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001897 // C++ [over.match.ctor]p1:
1898 // When objects of class type are direct-initialized (8.5), or
1899 // copy-initialized from an expression of the same or a
1900 // derived class type (8.5), overload resolution selects the
1901 // constructor. [...] For copy-initialization, the candidate
1902 // functions are all the converting constructors (12.3.1) of
1903 // that class. The argument list is the expression-list within
1904 // the parentheses of the initializer.
1905 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1906 (From->getType()->getAs<RecordType>() &&
1907 IsDerivedFrom(From->getType(), ToType)))
1908 ConstructorsOnly = true;
1909
Douglas Gregor393896f2009-11-05 13:06:35 +00001910 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1911 // We're not going to find any constructors.
1912 } else if (CXXRecordDecl *ToRecordDecl
1913 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001914 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00001915 for (llvm::tie(Con, ConEnd) = LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001916 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00001917 NamedDecl *D = *Con;
1918 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1919
Douglas Gregordec06662009-08-21 18:42:58 +00001920 // Find the constructor (which may be a template).
1921 CXXConstructorDecl *Constructor = 0;
1922 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00001923 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00001924 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00001925 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00001926 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1927 else
John McCall9aa472c2010-03-19 07:35:19 +00001928 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001929
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00001930 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00001931 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001932 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00001933 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001934 /*ExplicitArgs*/ 0,
John McCalld5532b62009-11-23 01:53:49 +00001935 &From, 1, CandidateSet,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001936 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00001937 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001938 // Allow one user-defined conversion when user specifies a
1939 // From->ToType conversion via an static cast (c-style, etc).
John McCall9aa472c2010-03-19 07:35:19 +00001940 AddOverloadCandidate(Constructor, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001941 &From, 1, CandidateSet,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001942 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00001943 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001944 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001945 }
1946 }
1947
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001948 // Enumerate conversion functions, if we're allowed to.
1949 if (ConstructorsOnly) {
Mike Stump1eb44332009-09-09 15:08:12 +00001950 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001951 PDiag(0) << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00001952 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00001953 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001954 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001955 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001956 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1957 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00001958 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00001959 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001960 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001961 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00001962 DeclAccessPair FoundDecl = I.getPair();
1963 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00001964 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1965 if (isa<UsingShadowDecl>(D))
1966 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1967
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001968 CXXConversionDecl *Conv;
1969 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00001970 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1971 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001972 else
John McCall32daa422010-03-31 01:36:47 +00001973 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001974
1975 if (AllowExplicit || !Conv->isExplicit()) {
1976 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00001977 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001978 ActingContext, From, ToType,
1979 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001980 else
John McCall9aa472c2010-03-19 07:35:19 +00001981 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCall86820f52010-01-26 01:37:31 +00001982 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001983 }
1984 }
1985 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001986 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001987
1988 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001989 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001990 case OR_Success:
1991 // Record the standard conversion we used and the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00001992 if (CXXConstructorDecl *Constructor
Douglas Gregor60d62c22008-10-31 16:23:19 +00001993 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1994 // C++ [over.ics.user]p1:
1995 // If the user-defined conversion is specified by a
1996 // constructor (12.3.1), the initial standard conversion
1997 // sequence converts the source type to the type required by
1998 // the argument of the constructor.
1999 //
Douglas Gregor60d62c22008-10-31 16:23:19 +00002000 QualType ThisType = Constructor->getThisType(Context);
John McCall1d318332010-01-12 00:44:57 +00002001 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002002 User.EllipsisConversion = true;
2003 else {
2004 User.Before = Best->Conversions[0].Standard;
2005 User.EllipsisConversion = false;
2006 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002007 User.ConversionFunction = Constructor;
2008 User.After.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +00002009 User.After.setFromType(
2010 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregorad323a82010-01-27 03:51:04 +00002011 User.After.setAllToTypes(ToType);
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002012 return OR_Success;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002013 } else if (CXXConversionDecl *Conversion
2014 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2015 // C++ [over.ics.user]p1:
2016 //
2017 // [...] If the user-defined conversion is specified by a
2018 // conversion function (12.3.2), the initial standard
2019 // conversion sequence converts the source type to the
2020 // implicit object parameter of the conversion function.
2021 User.Before = Best->Conversions[0].Standard;
2022 User.ConversionFunction = Conversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002023 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002024
2025 // C++ [over.ics.user]p2:
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002026 // The second standard conversion sequence converts the
2027 // result of the user-defined conversion to the target type
2028 // for the sequence. Since an implicit conversion sequence
2029 // is an initialization, the special rules for
2030 // initialization by user-defined conversion apply when
2031 // selecting the best user-defined conversion for a
2032 // user-defined conversion sequence (see 13.3.3 and
2033 // 13.3.3.1).
2034 User.After = Best->FinalConversion;
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002035 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002036 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002037 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002038 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002039 }
Mike Stump1eb44332009-09-09 15:08:12 +00002040
Douglas Gregor60d62c22008-10-31 16:23:19 +00002041 case OR_No_Viable_Function:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002042 return OR_No_Viable_Function;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002043 case OR_Deleted:
Douglas Gregor60d62c22008-10-31 16:23:19 +00002044 // No conversion here! We're done.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002045 return OR_Deleted;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002046
2047 case OR_Ambiguous:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002048 return OR_Ambiguous;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002049 }
2050
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002051 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002052}
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002053
2054bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002055Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002056 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00002057 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002058 OverloadingResult OvResult =
2059 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002060 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002061 if (OvResult == OR_Ambiguous)
2062 Diag(From->getSourceRange().getBegin(),
2063 diag::err_typecheck_ambiguous_condition)
2064 << From->getType() << ToType << From->getSourceRange();
2065 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2066 Diag(From->getSourceRange().getBegin(),
2067 diag::err_typecheck_nonviable_condition)
2068 << From->getType() << ToType << From->getSourceRange();
2069 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002070 return false;
John McCallcbce6062010-01-12 07:18:19 +00002071 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002072 return true;
2073}
Douglas Gregor60d62c22008-10-31 16:23:19 +00002074
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002075/// CompareImplicitConversionSequences - Compare two implicit
2076/// conversion sequences to determine whether one is better than the
2077/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump1eb44332009-09-09 15:08:12 +00002078ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002079Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
2080 const ImplicitConversionSequence& ICS2)
2081{
2082 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2083 // conversion sequences (as defined in 13.3.3.1)
2084 // -- a standard conversion sequence (13.3.3.1.1) is a better
2085 // conversion sequence than a user-defined conversion sequence or
2086 // an ellipsis conversion sequence, and
2087 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2088 // conversion sequence than an ellipsis conversion sequence
2089 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002090 //
John McCall1d318332010-01-12 00:44:57 +00002091 // C++0x [over.best.ics]p10:
2092 // For the purpose of ranking implicit conversion sequences as
2093 // described in 13.3.3.2, the ambiguous conversion sequence is
2094 // treated as a user-defined sequence that is indistinguishable
2095 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002096 if (ICS1.getKindRank() < ICS2.getKindRank())
2097 return ImplicitConversionSequence::Better;
2098 else if (ICS2.getKindRank() < ICS1.getKindRank())
2099 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002100
Benjamin Kramerb6eee072010-04-18 12:05:54 +00002101 // The following checks require both conversion sequences to be of
2102 // the same kind.
2103 if (ICS1.getKind() != ICS2.getKind())
2104 return ImplicitConversionSequence::Indistinguishable;
2105
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002106 // Two implicit conversion sequences of the same form are
2107 // indistinguishable conversion sequences unless one of the
2108 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00002109 if (ICS1.isStandard())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002110 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00002111 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002112 // User-defined conversion sequence U1 is a better conversion
2113 // sequence than another user-defined conversion sequence U2 if
2114 // they contain the same user-defined conversion function or
2115 // constructor and if the second standard conversion sequence of
2116 // U1 is better than the second standard conversion sequence of
2117 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002118 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002119 ICS2.UserDefined.ConversionFunction)
2120 return CompareStandardConversionSequences(ICS1.UserDefined.After,
2121 ICS2.UserDefined.After);
2122 }
2123
2124 return ImplicitConversionSequence::Indistinguishable;
2125}
2126
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002127static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2128 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2129 Qualifiers Quals;
2130 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2131 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2132 }
2133
2134 return Context.hasSameUnqualifiedType(T1, T2);
2135}
2136
Douglas Gregorad323a82010-01-27 03:51:04 +00002137// Per 13.3.3.2p3, compare the given standard conversion sequences to
2138// determine if one is a proper subset of the other.
2139static ImplicitConversionSequence::CompareKind
2140compareStandardConversionSubsets(ASTContext &Context,
2141 const StandardConversionSequence& SCS1,
2142 const StandardConversionSequence& SCS2) {
2143 ImplicitConversionSequence::CompareKind Result
2144 = ImplicitConversionSequence::Indistinguishable;
2145
Douglas Gregorae65f4b2010-05-23 22:10:15 +00002146 // the identity conversion sequence is considered to be a subsequence of
2147 // any non-identity conversion sequence
2148 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2149 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2150 return ImplicitConversionSequence::Better;
2151 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2152 return ImplicitConversionSequence::Worse;
2153 }
2154
Douglas Gregorad323a82010-01-27 03:51:04 +00002155 if (SCS1.Second != SCS2.Second) {
2156 if (SCS1.Second == ICK_Identity)
2157 Result = ImplicitConversionSequence::Better;
2158 else if (SCS2.Second == ICK_Identity)
2159 Result = ImplicitConversionSequence::Worse;
2160 else
2161 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002162 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00002163 return ImplicitConversionSequence::Indistinguishable;
2164
2165 if (SCS1.Third == SCS2.Third) {
2166 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2167 : ImplicitConversionSequence::Indistinguishable;
2168 }
2169
2170 if (SCS1.Third == ICK_Identity)
2171 return Result == ImplicitConversionSequence::Worse
2172 ? ImplicitConversionSequence::Indistinguishable
2173 : ImplicitConversionSequence::Better;
2174
2175 if (SCS2.Third == ICK_Identity)
2176 return Result == ImplicitConversionSequence::Better
2177 ? ImplicitConversionSequence::Indistinguishable
2178 : ImplicitConversionSequence::Worse;
2179
2180 return ImplicitConversionSequence::Indistinguishable;
2181}
2182
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002183/// CompareStandardConversionSequences - Compare two standard
2184/// conversion sequences to determine whether one is better than the
2185/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002186ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002187Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
2188 const StandardConversionSequence& SCS2)
2189{
2190 // Standard conversion sequence S1 is a better conversion sequence
2191 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2192
2193 // -- S1 is a proper subsequence of S2 (comparing the conversion
2194 // sequences in the canonical form defined by 13.3.3.1.1,
2195 // excluding any Lvalue Transformation; the identity conversion
2196 // sequence is considered to be a subsequence of any
2197 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00002198 if (ImplicitConversionSequence::CompareKind CK
2199 = compareStandardConversionSubsets(Context, SCS1, SCS2))
2200 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002201
2202 // -- the rank of S1 is better than the rank of S2 (by the rules
2203 // defined below), or, if not that,
2204 ImplicitConversionRank Rank1 = SCS1.getRank();
2205 ImplicitConversionRank Rank2 = SCS2.getRank();
2206 if (Rank1 < Rank2)
2207 return ImplicitConversionSequence::Better;
2208 else if (Rank2 < Rank1)
2209 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002210
Douglas Gregor57373262008-10-22 14:17:15 +00002211 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2212 // are indistinguishable unless one of the following rules
2213 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00002214
Douglas Gregor57373262008-10-22 14:17:15 +00002215 // A conversion that is not a conversion of a pointer, or
2216 // pointer to member, to bool is better than another conversion
2217 // that is such a conversion.
2218 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2219 return SCS2.isPointerConversionToBool()
2220 ? ImplicitConversionSequence::Better
2221 : ImplicitConversionSequence::Worse;
2222
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002223 // C++ [over.ics.rank]p4b2:
2224 //
2225 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002226 // conversion of B* to A* is better than conversion of B* to
2227 // void*, and conversion of A* to void* is better than conversion
2228 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00002229 bool SCS1ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002230 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002231 bool SCS2ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002232 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002233 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2234 // Exactly one of the conversion sequences is a conversion to
2235 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002236 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2237 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002238 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2239 // Neither conversion sequence converts to a void pointer; compare
2240 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002241 if (ImplicitConversionSequence::CompareKind DerivedCK
2242 = CompareDerivedToBaseConversions(SCS1, SCS2))
2243 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002244 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2245 // Both conversion sequences are conversions to void
2246 // pointers. Compare the source types to determine if there's an
2247 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00002248 QualType FromType1 = SCS1.getFromType();
2249 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002250
2251 // Adjust the types we're converting from via the array-to-pointer
2252 // conversion, if we need to.
2253 if (SCS1.First == ICK_Array_To_Pointer)
2254 FromType1 = Context.getArrayDecayedType(FromType1);
2255 if (SCS2.First == ICK_Array_To_Pointer)
2256 FromType2 = Context.getArrayDecayedType(FromType2);
2257
Douglas Gregor01919692009-12-13 21:37:05 +00002258 QualType FromPointee1
2259 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2260 QualType FromPointee2
2261 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002262
Douglas Gregor01919692009-12-13 21:37:05 +00002263 if (IsDerivedFrom(FromPointee2, FromPointee1))
2264 return ImplicitConversionSequence::Better;
2265 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2266 return ImplicitConversionSequence::Worse;
2267
2268 // Objective-C++: If one interface is more specific than the
2269 // other, it is the better one.
John McCallc12c5bb2010-05-15 11:32:37 +00002270 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2271 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor01919692009-12-13 21:37:05 +00002272 if (FromIface1 && FromIface1) {
2273 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2274 return ImplicitConversionSequence::Better;
2275 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2276 return ImplicitConversionSequence::Worse;
2277 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002278 }
Douglas Gregor57373262008-10-22 14:17:15 +00002279
2280 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2281 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00002282 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00002283 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002284 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00002285
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002286 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002287 // C++0x [over.ics.rank]p3b4:
2288 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2289 // implicit object parameter of a non-static member function declared
2290 // without a ref-qualifier, and S1 binds an rvalue reference to an
2291 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00002292 // FIXME: We don't know if we're dealing with the implicit object parameter,
2293 // or if the member function in this case has a ref qualifier.
2294 // (Of course, we don't have ref qualifiers yet.)
2295 if (SCS1.RRefBinding != SCS2.RRefBinding)
2296 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2297 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002298
2299 // C++ [over.ics.rank]p3b4:
2300 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2301 // which the references refer are the same type except for
2302 // top-level cv-qualifiers, and the type to which the reference
2303 // initialized by S2 refers is more cv-qualified than the type
2304 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00002305 QualType T1 = SCS1.getToType(2);
2306 QualType T2 = SCS2.getToType(2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002307 T1 = Context.getCanonicalType(T1);
2308 T2 = Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002309 Qualifiers T1Quals, T2Quals;
2310 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2311 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2312 if (UnqualT1 == UnqualT2) {
2313 // If the type is an array type, promote the element qualifiers to the type
2314 // for comparison.
2315 if (isa<ArrayType>(T1) && T1Quals)
2316 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2317 if (isa<ArrayType>(T2) && T2Quals)
2318 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002319 if (T2.isMoreQualifiedThan(T1))
2320 return ImplicitConversionSequence::Better;
2321 else if (T1.isMoreQualifiedThan(T2))
2322 return ImplicitConversionSequence::Worse;
2323 }
2324 }
Douglas Gregor57373262008-10-22 14:17:15 +00002325
2326 return ImplicitConversionSequence::Indistinguishable;
2327}
2328
2329/// CompareQualificationConversions - Compares two standard conversion
2330/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00002331/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2332ImplicitConversionSequence::CompareKind
Douglas Gregor57373262008-10-22 14:17:15 +00002333Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump1eb44332009-09-09 15:08:12 +00002334 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00002335 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00002336 // -- S1 and S2 differ only in their qualification conversion and
2337 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2338 // cv-qualification signature of type T1 is a proper subset of
2339 // the cv-qualification signature of type T2, and S1 is not the
2340 // deprecated string literal array-to-pointer conversion (4.2).
2341 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2342 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2343 return ImplicitConversionSequence::Indistinguishable;
2344
2345 // FIXME: the example in the standard doesn't use a qualification
2346 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00002347 QualType T1 = SCS1.getToType(2);
2348 QualType T2 = SCS2.getToType(2);
Douglas Gregor57373262008-10-22 14:17:15 +00002349 T1 = Context.getCanonicalType(T1);
2350 T2 = Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002351 Qualifiers T1Quals, T2Quals;
2352 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2353 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00002354
2355 // If the types are the same, we won't learn anything by unwrapped
2356 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00002357 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00002358 return ImplicitConversionSequence::Indistinguishable;
2359
Chandler Carruth28e318c2009-12-29 07:16:59 +00002360 // If the type is an array type, promote the element qualifiers to the type
2361 // for comparison.
2362 if (isa<ArrayType>(T1) && T1Quals)
2363 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2364 if (isa<ArrayType>(T2) && T2Quals)
2365 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2366
Mike Stump1eb44332009-09-09 15:08:12 +00002367 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00002368 = ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002369 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00002370 // Within each iteration of the loop, we check the qualifiers to
2371 // determine if this still looks like a qualification
2372 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002373 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00002374 // until there are no more pointers or pointers-to-members left
2375 // to unwrap. This essentially mimics what
2376 // IsQualificationConversion does, but here we're checking for a
2377 // strict subset of qualifiers.
2378 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2379 // The qualifiers are the same, so this doesn't tell us anything
2380 // about how the sequences rank.
2381 ;
2382 else if (T2.isMoreQualifiedThan(T1)) {
2383 // T1 has fewer qualifiers, so it could be the better sequence.
2384 if (Result == ImplicitConversionSequence::Worse)
2385 // Neither has qualifiers that are a subset of the other's
2386 // qualifiers.
2387 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002388
Douglas Gregor57373262008-10-22 14:17:15 +00002389 Result = ImplicitConversionSequence::Better;
2390 } else if (T1.isMoreQualifiedThan(T2)) {
2391 // T2 has fewer qualifiers, so it could be the better sequence.
2392 if (Result == ImplicitConversionSequence::Better)
2393 // Neither has qualifiers that are a subset of the other's
2394 // qualifiers.
2395 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002396
Douglas Gregor57373262008-10-22 14:17:15 +00002397 Result = ImplicitConversionSequence::Worse;
2398 } else {
2399 // Qualifiers are disjoint.
2400 return ImplicitConversionSequence::Indistinguishable;
2401 }
2402
2403 // If the types after this point are equivalent, we're done.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002404 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00002405 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002406 }
2407
Douglas Gregor57373262008-10-22 14:17:15 +00002408 // Check that the winning standard conversion sequence isn't using
2409 // the deprecated string literal array to pointer conversion.
2410 switch (Result) {
2411 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00002412 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002413 Result = ImplicitConversionSequence::Indistinguishable;
2414 break;
2415
2416 case ImplicitConversionSequence::Indistinguishable:
2417 break;
2418
2419 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00002420 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002421 Result = ImplicitConversionSequence::Indistinguishable;
2422 break;
2423 }
2424
2425 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002426}
2427
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002428/// CompareDerivedToBaseConversions - Compares two standard conversion
2429/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00002430/// various kinds of derived-to-base conversions (C++
2431/// [over.ics.rank]p4b3). As part of these checks, we also look at
2432/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002433ImplicitConversionSequence::CompareKind
2434Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2435 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00002436 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002437 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00002438 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002439 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002440
2441 // Adjust the types we're converting from via the array-to-pointer
2442 // conversion, if we need to.
2443 if (SCS1.First == ICK_Array_To_Pointer)
2444 FromType1 = Context.getArrayDecayedType(FromType1);
2445 if (SCS2.First == ICK_Array_To_Pointer)
2446 FromType2 = Context.getArrayDecayedType(FromType2);
2447
2448 // Canonicalize all of the types.
2449 FromType1 = Context.getCanonicalType(FromType1);
2450 ToType1 = Context.getCanonicalType(ToType1);
2451 FromType2 = Context.getCanonicalType(FromType2);
2452 ToType2 = Context.getCanonicalType(ToType2);
2453
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002454 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002455 //
2456 // If class B is derived directly or indirectly from class A and
2457 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002458 //
2459 // For Objective-C, we let A, B, and C also be Objective-C
2460 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002461
2462 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00002463 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00002464 SCS2.Second == ICK_Pointer_Conversion &&
2465 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2466 FromType1->isPointerType() && FromType2->isPointerType() &&
2467 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002468 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002469 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002470 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002471 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002472 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002473 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002474 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002475 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002476
John McCallc12c5bb2010-05-15 11:32:37 +00002477 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2478 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2479 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2480 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002481
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002482 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002483 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2484 if (IsDerivedFrom(ToPointee1, ToPointee2))
2485 return ImplicitConversionSequence::Better;
2486 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2487 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00002488
2489 if (ToIface1 && ToIface2) {
2490 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2491 return ImplicitConversionSequence::Better;
2492 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2493 return ImplicitConversionSequence::Worse;
2494 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002495 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002496
2497 // -- conversion of B* to A* is better than conversion of C* to A*,
2498 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2499 if (IsDerivedFrom(FromPointee2, FromPointee1))
2500 return ImplicitConversionSequence::Better;
2501 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2502 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00002503
Douglas Gregorcb7de522008-11-26 23:31:11 +00002504 if (FromIface1 && FromIface2) {
2505 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2506 return ImplicitConversionSequence::Better;
2507 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2508 return ImplicitConversionSequence::Worse;
2509 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002510 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002511 }
2512
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002513 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002514 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2515 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2516 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2517 const MemberPointerType * FromMemPointer1 =
2518 FromType1->getAs<MemberPointerType>();
2519 const MemberPointerType * ToMemPointer1 =
2520 ToType1->getAs<MemberPointerType>();
2521 const MemberPointerType * FromMemPointer2 =
2522 FromType2->getAs<MemberPointerType>();
2523 const MemberPointerType * ToMemPointer2 =
2524 ToType2->getAs<MemberPointerType>();
2525 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2526 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2527 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2528 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2529 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2530 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2531 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2532 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002533 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002534 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2535 if (IsDerivedFrom(ToPointee1, ToPointee2))
2536 return ImplicitConversionSequence::Worse;
2537 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2538 return ImplicitConversionSequence::Better;
2539 }
2540 // conversion of B::* to C::* is better than conversion of A::* to C::*
2541 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2542 if (IsDerivedFrom(FromPointee1, FromPointee2))
2543 return ImplicitConversionSequence::Better;
2544 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2545 return ImplicitConversionSequence::Worse;
2546 }
2547 }
2548
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002549 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002550 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00002551 // -- binding of an expression of type C to a reference of type
2552 // B& is better than binding an expression of type C to a
2553 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002554 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2555 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002556 if (IsDerivedFrom(ToType1, ToType2))
2557 return ImplicitConversionSequence::Better;
2558 else if (IsDerivedFrom(ToType2, ToType1))
2559 return ImplicitConversionSequence::Worse;
2560 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002561
Douglas Gregor225c41e2008-11-03 19:09:14 +00002562 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00002563 // -- binding of an expression of type B to a reference of type
2564 // A& is better than binding an expression of type C to a
2565 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002566 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2567 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002568 if (IsDerivedFrom(FromType2, FromType1))
2569 return ImplicitConversionSequence::Better;
2570 else if (IsDerivedFrom(FromType1, FromType2))
2571 return ImplicitConversionSequence::Worse;
2572 }
2573 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002574
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002575 return ImplicitConversionSequence::Indistinguishable;
2576}
2577
Douglas Gregorabe183d2010-04-13 16:31:36 +00002578/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2579/// determine whether they are reference-related,
2580/// reference-compatible, reference-compatible with added
2581/// qualification, or incompatible, for use in C++ initialization by
2582/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2583/// type, and the first type (T1) is the pointee type of the reference
2584/// type being initialized.
2585Sema::ReferenceCompareResult
2586Sema::CompareReferenceRelationship(SourceLocation Loc,
2587 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00002588 bool &DerivedToBase,
2589 bool &ObjCConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002590 assert(!OrigT1->isReferenceType() &&
2591 "T1 must be the pointee type of the reference type");
2592 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2593
2594 QualType T1 = Context.getCanonicalType(OrigT1);
2595 QualType T2 = Context.getCanonicalType(OrigT2);
2596 Qualifiers T1Quals, T2Quals;
2597 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2598 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2599
2600 // C++ [dcl.init.ref]p4:
2601 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2602 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2603 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00002604 DerivedToBase = false;
2605 ObjCConversion = false;
2606 if (UnqualT1 == UnqualT2) {
2607 // Nothing to do.
2608 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00002609 IsDerivedFrom(UnqualT2, UnqualT1))
2610 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00002611 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2612 UnqualT2->isObjCObjectOrInterfaceType() &&
2613 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2614 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002615 else
2616 return Ref_Incompatible;
2617
2618 // At this point, we know that T1 and T2 are reference-related (at
2619 // least).
2620
2621 // If the type is an array type, promote the element qualifiers to the type
2622 // for comparison.
2623 if (isa<ArrayType>(T1) && T1Quals)
2624 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2625 if (isa<ArrayType>(T2) && T2Quals)
2626 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2627
2628 // C++ [dcl.init.ref]p4:
2629 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2630 // reference-related to T2 and cv1 is the same cv-qualification
2631 // as, or greater cv-qualification than, cv2. For purposes of
2632 // overload resolution, cases for which cv1 is greater
2633 // cv-qualification than cv2 are identified as
2634 // reference-compatible with added qualification (see 13.3.3.2).
2635 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2636 return Ref_Compatible;
2637 else if (T1.isMoreQualifiedThan(T2))
2638 return Ref_Compatible_With_Added_Qualification;
2639 else
2640 return Ref_Related;
2641}
2642
Douglas Gregor604eb652010-08-11 02:15:33 +00002643/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00002644/// with DeclType. Return true if something definite is found.
2645static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00002646FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2647 QualType DeclType, SourceLocation DeclLoc,
2648 Expr *Init, QualType T2, bool AllowRvalues,
2649 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00002650 assert(T2->isRecordType() && "Can only find conversions of record types.");
2651 CXXRecordDecl *T2RecordDecl
2652 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2653
Douglas Gregor604eb652010-08-11 02:15:33 +00002654 QualType ToType
2655 = AllowRvalues? DeclType->getAs<ReferenceType>()->getPointeeType()
2656 : DeclType;
2657
Sebastian Redl4680bf22010-06-30 18:13:39 +00002658 OverloadCandidateSet CandidateSet(DeclLoc);
2659 const UnresolvedSetImpl *Conversions
2660 = T2RecordDecl->getVisibleConversionFunctions();
2661 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2662 E = Conversions->end(); I != E; ++I) {
2663 NamedDecl *D = *I;
2664 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2665 if (isa<UsingShadowDecl>(D))
2666 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2667
2668 FunctionTemplateDecl *ConvTemplate
2669 = dyn_cast<FunctionTemplateDecl>(D);
2670 CXXConversionDecl *Conv;
2671 if (ConvTemplate)
2672 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2673 else
2674 Conv = cast<CXXConversionDecl>(D);
2675
Douglas Gregor604eb652010-08-11 02:15:33 +00002676 // If this is an explicit conversion, and we're not allowed to consider
2677 // explicit conversions, skip it.
2678 if (!AllowExplicit && Conv->isExplicit())
2679 continue;
2680
2681 if (AllowRvalues) {
2682 bool DerivedToBase = false;
2683 bool ObjCConversion = false;
2684 if (!ConvTemplate &&
2685 S.CompareReferenceRelationship(DeclLoc,
2686 Conv->getConversionType().getNonReferenceType().getUnqualifiedType(),
2687 DeclType.getNonReferenceType().getUnqualifiedType(),
2688 DerivedToBase, ObjCConversion)
2689 == Sema::Ref_Incompatible)
2690 continue;
2691 } else {
2692 // If the conversion function doesn't return a reference type,
2693 // it can't be considered for this conversion. An rvalue reference
2694 // is only acceptable if its referencee is a function type.
2695
2696 const ReferenceType *RefType =
2697 Conv->getConversionType()->getAs<ReferenceType>();
2698 if (!RefType ||
2699 (!RefType->isLValueReferenceType() &&
2700 !RefType->getPointeeType()->isFunctionType()))
2701 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002702 }
Douglas Gregor604eb652010-08-11 02:15:33 +00002703
2704 if (ConvTemplate)
2705 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2706 Init, ToType, CandidateSet);
2707 else
2708 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2709 ToType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002710 }
2711
2712 OverloadCandidateSet::iterator Best;
2713 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2714 case OR_Success:
2715 // C++ [over.ics.ref]p1:
2716 //
2717 // [...] If the parameter binds directly to the result of
2718 // applying a conversion function to the argument
2719 // expression, the implicit conversion sequence is a
2720 // user-defined conversion sequence (13.3.3.1.2), with the
2721 // second standard conversion sequence either an identity
2722 // conversion or, if the conversion function returns an
2723 // entity of a type that is a derived class of the parameter
2724 // type, a derived-to-base Conversion.
2725 if (!Best->FinalConversion.DirectBinding)
2726 return false;
2727
2728 ICS.setUserDefined();
2729 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2730 ICS.UserDefined.After = Best->FinalConversion;
2731 ICS.UserDefined.ConversionFunction = Best->Function;
2732 ICS.UserDefined.EllipsisConversion = false;
2733 assert(ICS.UserDefined.After.ReferenceBinding &&
2734 ICS.UserDefined.After.DirectBinding &&
2735 "Expected a direct reference binding!");
2736 return true;
2737
2738 case OR_Ambiguous:
2739 ICS.setAmbiguous();
2740 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2741 Cand != CandidateSet.end(); ++Cand)
2742 if (Cand->Viable)
2743 ICS.Ambiguous.addConversion(Cand->Function);
2744 return true;
2745
2746 case OR_No_Viable_Function:
2747 case OR_Deleted:
2748 // There was no suitable conversion, or we found a deleted
2749 // conversion; continue with other checks.
2750 return false;
2751 }
Eric Christopher1c3d5022010-06-30 18:36:32 +00002752
2753 return false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002754}
2755
Douglas Gregorabe183d2010-04-13 16:31:36 +00002756/// \brief Compute an implicit conversion sequence for reference
2757/// initialization.
2758static ImplicitConversionSequence
2759TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2760 SourceLocation DeclLoc,
2761 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00002762 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002763 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2764
2765 // Most paths end in a failed conversion.
2766 ImplicitConversionSequence ICS;
2767 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2768
2769 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2770 QualType T2 = Init->getType();
2771
2772 // If the initializer is the address of an overloaded function, try
2773 // to resolve the overloaded function. If all goes well, T2 is the
2774 // type of the resulting function.
2775 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2776 DeclAccessPair Found;
2777 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2778 false, Found))
2779 T2 = Fn->getType();
2780 }
2781
2782 // Compute some basic properties of the types and the initializer.
2783 bool isRValRef = DeclType->isRValueReferenceType();
2784 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002785 bool ObjCConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002786 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002787 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00002788 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
2789 ObjCConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002790
Douglas Gregorabe183d2010-04-13 16:31:36 +00002791
Sebastian Redl4680bf22010-06-30 18:13:39 +00002792 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00002793 // A reference to type "cv1 T1" is initialized by an expression
2794 // of type "cv2 T2" as follows:
2795
Sebastian Redl4680bf22010-06-30 18:13:39 +00002796 // -- If reference is an lvalue reference and the initializer expression
2797 // The next bullet point (T1 is a function) is pretty much equivalent to this
2798 // one, so it's handled here.
2799 if (!isRValRef || T1->isFunctionType()) {
2800 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2801 // reference-compatible with "cv2 T2," or
2802 //
2803 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2804 if (InitCategory.isLValue() &&
2805 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002806 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00002807 // When a parameter of reference type binds directly (8.5.3)
2808 // to an argument expression, the implicit conversion sequence
2809 // is the identity conversion, unless the argument expression
2810 // has a type that is a derived class of the parameter type,
2811 // in which case the implicit conversion sequence is a
2812 // derived-to-base Conversion (13.3.3.1).
2813 ICS.setStandard();
2814 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00002815 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2816 : ObjCConversion? ICK_Compatible_Conversion
2817 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002818 ICS.Standard.Third = ICK_Identity;
2819 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2820 ICS.Standard.setToType(0, T2);
2821 ICS.Standard.setToType(1, T1);
2822 ICS.Standard.setToType(2, T1);
2823 ICS.Standard.ReferenceBinding = true;
2824 ICS.Standard.DirectBinding = true;
2825 ICS.Standard.RRefBinding = isRValRef;
2826 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002827
Sebastian Redl4680bf22010-06-30 18:13:39 +00002828 // Nothing more to do: the inaccessibility/ambiguity check for
2829 // derived-to-base conversions is suppressed when we're
2830 // computing the implicit conversion sequence (C++
2831 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00002832 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002833 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00002834
Sebastian Redl4680bf22010-06-30 18:13:39 +00002835 // -- has a class type (i.e., T2 is a class type), where T1 is
2836 // not reference-related to T2, and can be implicitly
2837 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2838 // is reference-compatible with "cv3 T3" 92) (this
2839 // conversion is selected by enumerating the applicable
2840 // conversion functions (13.3.1.6) and choosing the best
2841 // one through overload resolution (13.3)),
2842 if (!SuppressUserConversions && T2->isRecordType() &&
2843 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2844 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00002845 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2846 Init, T2, /*AllowRvalues=*/false,
2847 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00002848 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002849 }
2850 }
2851
Sebastian Redl4680bf22010-06-30 18:13:39 +00002852 // -- Otherwise, the reference shall be an lvalue reference to a
2853 // non-volatile const type (i.e., cv1 shall be const), or the reference
2854 // shall be an rvalue reference and the initializer expression shall be
2855 // an rvalue or have a function type.
Douglas Gregor66821b52010-04-18 09:22:00 +00002856 //
2857 // We actually handle one oddity of C++ [over.ics.ref] at this
2858 // point, which is that, due to p2 (which short-circuits reference
2859 // binding by only attempting a simple conversion for non-direct
2860 // bindings) and p3's strange wording, we allow a const volatile
2861 // reference to bind to an rvalue. Hence the check for the presence
2862 // of "const" rather than checking for "const" being the only
2863 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00002864 // This is also the point where rvalue references and lvalue inits no longer
2865 // go together.
2866 if ((!isRValRef && !T1.isConstQualified()) ||
2867 (isRValRef && InitCategory.isLValue()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00002868 return ICS;
2869
Sebastian Redl4680bf22010-06-30 18:13:39 +00002870 // -- If T1 is a function type, then
2871 // -- if T2 is the same type as T1, the reference is bound to the
2872 // initializer expression lvalue;
2873 // -- if T2 is a class type and the initializer expression can be
2874 // implicitly converted to an lvalue of type T1 [...], the
2875 // reference is bound to the function lvalue that is the result
2876 // of the conversion;
2877 // This is the same as for the lvalue case above, so it was handled there.
2878 // -- otherwise, the program is ill-formed.
2879 // This is the one difference to the lvalue case.
2880 if (T1->isFunctionType())
2881 return ICS;
2882
2883 // -- Otherwise, if T2 is a class type and
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002884 // -- the initializer expression is an rvalue and "cv1 T1"
2885 // is reference-compatible with "cv2 T2," or
Douglas Gregorabe183d2010-04-13 16:31:36 +00002886 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002887 // -- T1 is not reference-related to T2 and the initializer
2888 // expression can be implicitly converted to an rvalue
2889 // of type "cv3 T3" (this conversion is selected by
2890 // enumerating the applicable conversion functions
2891 // (13.3.1.6) and choosing the best one through overload
2892 // resolution (13.3)),
Douglas Gregorabe183d2010-04-13 16:31:36 +00002893 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002894 // then the reference is bound to the initializer
2895 // expression rvalue in the first case and to the object
2896 // that is the result of the conversion in the second case
2897 // (or, in either case, to the appropriate base class
2898 // subobject of the object).
Douglas Gregor604eb652010-08-11 02:15:33 +00002899 if (T2->isRecordType()) {
2900 // First case: "cv1 T1" is reference-compatible with "cv2 T2". This is a
2901 // direct binding in C++0x but not in C++03.
2902 if (InitCategory.isRValue() &&
2903 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2904 ICS.setStandard();
2905 ICS.Standard.First = ICK_Identity;
2906 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2907 : ObjCConversion? ICK_Compatible_Conversion
2908 : ICK_Identity;
2909 ICS.Standard.Third = ICK_Identity;
2910 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2911 ICS.Standard.setToType(0, T2);
2912 ICS.Standard.setToType(1, T1);
2913 ICS.Standard.setToType(2, T1);
2914 ICS.Standard.ReferenceBinding = true;
2915 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
2916 ICS.Standard.RRefBinding = isRValRef;
2917 ICS.Standard.CopyConstructor = 0;
2918 return ICS;
2919 }
2920
2921 // Second case: not reference-related.
2922 if (RefRelationship == Sema::Ref_Incompatible &&
2923 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2924 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2925 Init, T2, /*AllowRvalues=*/true,
2926 AllowExplicit))
2927 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002928 }
Douglas Gregor604eb652010-08-11 02:15:33 +00002929
Douglas Gregorabe183d2010-04-13 16:31:36 +00002930 // -- Otherwise, a temporary of type "cv1 T1" is created and
2931 // initialized from the initializer expression using the
2932 // rules for a non-reference copy initialization (8.5). The
2933 // reference is then bound to the temporary. If T1 is
2934 // reference-related to T2, cv1 must be the same
2935 // cv-qualification as, or greater cv-qualification than,
2936 // cv2; otherwise, the program is ill-formed.
2937 if (RefRelationship == Sema::Ref_Related) {
2938 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2939 // we would be reference-compatible or reference-compatible with
2940 // added qualification. But that wasn't the case, so the reference
2941 // initialization fails.
2942 return ICS;
2943 }
2944
2945 // If at least one of the types is a class type, the types are not
2946 // related, and we aren't allowed any user conversions, the
2947 // reference binding fails. This case is important for breaking
2948 // recursion, since TryImplicitConversion below will attempt to
2949 // create a temporary through the use of a copy constructor.
2950 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2951 (T1->isRecordType() || T2->isRecordType()))
2952 return ICS;
2953
2954 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00002955 // When a parameter of reference type is not bound directly to
2956 // an argument expression, the conversion sequence is the one
2957 // required to convert the argument expression to the
2958 // underlying type of the reference according to
2959 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2960 // to copy-initializing a temporary of the underlying type with
2961 // the argument expression. Any difference in top-level
2962 // cv-qualification is subsumed by the initialization itself
2963 // and does not constitute a conversion.
2964 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2965 /*AllowExplicit=*/false,
Douglas Gregorabe183d2010-04-13 16:31:36 +00002966 /*InOverloadResolution=*/false);
2967
2968 // Of course, that's still a reference binding.
2969 if (ICS.isStandard()) {
2970 ICS.Standard.ReferenceBinding = true;
2971 ICS.Standard.RRefBinding = isRValRef;
2972 } else if (ICS.isUserDefined()) {
2973 ICS.UserDefined.After.ReferenceBinding = true;
2974 ICS.UserDefined.After.RRefBinding = isRValRef;
2975 }
2976 return ICS;
2977}
2978
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002979/// TryCopyInitialization - Try to copy-initialize a value of type
2980/// ToType from the expression From. Return the implicit conversion
2981/// sequence required to pass this argument, which may be a bad
2982/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00002983/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00002984/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00002985static ImplicitConversionSequence
2986TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregorb7f9e6a2010-04-16 17:53:55 +00002987 bool SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00002988 bool InOverloadResolution) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002989 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00002990 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00002991 /*FIXME:*/From->getLocStart(),
2992 SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00002993 /*AllowExplicit=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002994
Douglas Gregor74eb6582010-04-16 17:51:22 +00002995 return S.TryImplicitConversion(From, ToType,
2996 SuppressUserConversions,
2997 /*AllowExplicit=*/false,
Douglas Gregor74eb6582010-04-16 17:51:22 +00002998 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002999}
3000
Douglas Gregor96176b32008-11-18 23:14:02 +00003001/// TryObjectArgumentInitialization - Try to initialize the object
3002/// parameter of the given member function (@c Method) from the
3003/// expression @p From.
3004ImplicitConversionSequence
John McCall651f3ee2010-01-14 03:28:57 +00003005Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall701c89e2009-12-03 04:06:58 +00003006 CXXMethodDecl *Method,
3007 CXXRecordDecl *ActingContext) {
3008 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00003009 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3010 // const volatile object.
3011 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3012 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
3013 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00003014
3015 // Set up the conversion sequence as a "bad" conversion, to allow us
3016 // to exit early.
3017 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00003018
3019 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00003020 QualType FromType = OrigFromType;
Ted Kremenek6217b802009-07-29 21:53:49 +00003021 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00003022 FromType = PT->getPointeeType();
3023
3024 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00003025
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00003026 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor96176b32008-11-18 23:14:02 +00003027 // where X is the class of which the function is a member
3028 // (C++ [over.match.funcs]p4). However, when finding an implicit
3029 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00003030 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00003031 // (C++ [over.match.funcs]p5). We perform a simplified version of
3032 // reference binding here, that allows class rvalues to bind to
3033 // non-constant references.
3034
3035 // First check the qualifiers. We don't care about lvalue-vs-rvalue
3036 // with the implicit object parameter (C++ [over.match.funcs]p5).
3037 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00003038 if (ImplicitParamType.getCVRQualifiers()
3039 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00003040 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00003041 ICS.setBad(BadConversionSequence::bad_qualifiers,
3042 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003043 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003044 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003045
3046 // Check that we have either the same type or a derived type. It
3047 // affects the conversion rank.
3048 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00003049 ImplicitConversionKind SecondKind;
3050 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3051 SecondKind = ICK_Identity;
3052 } else if (IsDerivedFrom(FromType, ClassType))
3053 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00003054 else {
John McCallb1bdc622010-02-25 01:37:24 +00003055 ICS.setBad(BadConversionSequence::unrelated_class,
3056 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003057 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003058 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003059
3060 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00003061 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00003062 ICS.Standard.setAsIdentityConversion();
3063 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00003064 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003065 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003066 ICS.Standard.ReferenceBinding = true;
3067 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00003068 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003069 return ICS;
3070}
3071
3072/// PerformObjectArgumentInitialization - Perform initialization of
3073/// the implicit object parameter for the given Method with the given
3074/// expression.
3075bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00003076Sema::PerformObjectArgumentInitialization(Expr *&From,
3077 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00003078 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00003079 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003080 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00003081 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00003082 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003083
Ted Kremenek6217b802009-07-29 21:53:49 +00003084 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003085 FromRecordType = PT->getPointeeType();
3086 DestType = Method->getThisType(Context);
3087 } else {
3088 FromRecordType = From->getType();
3089 DestType = ImplicitParamRecordType;
3090 }
3091
John McCall701c89e2009-12-03 04:06:58 +00003092 // Note that we always use the true parent context when performing
3093 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003094 ImplicitConversionSequence ICS
John McCall701c89e2009-12-03 04:06:58 +00003095 = TryObjectArgumentInitialization(From->getType(), Method,
3096 Method->getParent());
John McCall1d318332010-01-12 00:44:57 +00003097 if (ICS.isBad())
Douglas Gregor96176b32008-11-18 23:14:02 +00003098 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003099 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00003100 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003101
Douglas Gregor5fccd362010-03-03 23:55:11 +00003102 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall6bb80172010-03-30 21:47:33 +00003103 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor96176b32008-11-18 23:14:02 +00003104
Douglas Gregor5fccd362010-03-03 23:55:11 +00003105 if (!Context.hasSameType(From->getType(), DestType))
Anders Carlssonf1b48b72010-04-24 16:57:13 +00003106 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
Sebastian Redl906082e2010-07-20 04:20:21 +00003107 From->getType()->isPointerType() ?
3108 ImplicitCastExpr::RValue : ImplicitCastExpr::LValue);
Douglas Gregor96176b32008-11-18 23:14:02 +00003109 return false;
3110}
3111
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003112/// TryContextuallyConvertToBool - Attempt to contextually convert the
3113/// expression From to bool (C++0x [conv]p3).
3114ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00003115 // FIXME: This is pretty broken.
Mike Stump1eb44332009-09-09 15:08:12 +00003116 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00003117 // FIXME: Are these flags correct?
3118 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00003119 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00003120 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003121}
3122
3123/// PerformContextuallyConvertToBool - Perform a contextual conversion
3124/// of the expression From to bool (C++0x [conv]p3).
3125bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
3126 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall1d318332010-01-12 00:44:57 +00003127 if (!ICS.isBad())
3128 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003129
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003130 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003131 return Diag(From->getSourceRange().getBegin(),
3132 diag::err_typecheck_bool_condition)
3133 << From->getType() << From->getSourceRange();
3134 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003135}
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003136
3137/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3138/// expression From to 'id'.
3139ImplicitConversionSequence Sema::TryContextuallyConvertToObjCId(Expr *From) {
John McCallc12c5bb2010-05-15 11:32:37 +00003140 QualType Ty = Context.getObjCIdType();
3141 return TryImplicitConversion(From, Ty,
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003142 // FIXME: Are these flags correct?
3143 /*SuppressUserConversions=*/false,
3144 /*AllowExplicit=*/true,
3145 /*InOverloadResolution=*/false);
3146}
3147
3148/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3149/// of the expression From to 'id'.
3150bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCallc12c5bb2010-05-15 11:32:37 +00003151 QualType Ty = Context.getObjCIdType();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003152 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(From);
3153 if (!ICS.isBad())
3154 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3155 return true;
3156}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003157
Douglas Gregorc30614b2010-06-29 23:17:37 +00003158/// \brief Attempt to convert the given expression to an integral or
3159/// enumeration type.
3160///
3161/// This routine will attempt to convert an expression of class type to an
3162/// integral or enumeration type, if that class type only has a single
3163/// conversion to an integral or enumeration type.
3164///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003165/// \param Loc The source location of the construct that requires the
3166/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00003167///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003168/// \param FromE The expression we're converting from.
3169///
3170/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3171/// have integral or enumeration type.
3172///
3173/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3174/// incomplete class type.
3175///
3176/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3177/// explicit conversion function (because no implicit conversion functions
3178/// were available). This is a recovery mode.
3179///
3180/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3181/// showing which conversion was picked.
3182///
3183/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3184/// conversion function that could convert to integral or enumeration type.
3185///
3186/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3187/// usable conversion function.
3188///
3189/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3190/// function, which may be an extension in this case.
3191///
3192/// \returns The expression, converted to an integral or enumeration type if
3193/// successful.
Douglas Gregorc30614b2010-06-29 23:17:37 +00003194Sema::OwningExprResult
3195Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, ExprArg FromE,
3196 const PartialDiagnostic &NotIntDiag,
3197 const PartialDiagnostic &IncompleteDiag,
3198 const PartialDiagnostic &ExplicitConvDiag,
3199 const PartialDiagnostic &ExplicitConvNote,
3200 const PartialDiagnostic &AmbigDiag,
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003201 const PartialDiagnostic &AmbigNote,
3202 const PartialDiagnostic &ConvDiag) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00003203 Expr *From = static_cast<Expr *>(FromE.get());
3204
3205 // We can't perform any more checking for type-dependent expressions.
3206 if (From->isTypeDependent())
3207 return move(FromE);
3208
3209 // If the expression already has integral or enumeration type, we're golden.
3210 QualType T = From->getType();
3211 if (T->isIntegralOrEnumerationType())
3212 return move(FromE);
3213
3214 // FIXME: Check for missing '()' if T is a function type?
3215
3216 // If we don't have a class type in C++, there's no way we can get an
3217 // expression of integral or enumeration type.
3218 const RecordType *RecordTy = T->getAs<RecordType>();
3219 if (!RecordTy || !getLangOptions().CPlusPlus) {
3220 Diag(Loc, NotIntDiag)
3221 << T << From->getSourceRange();
Douglas Gregoracb0bd82010-06-29 23:25:20 +00003222 return move(FromE);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003223 }
3224
3225 // We must have a complete class type.
3226 if (RequireCompleteType(Loc, T, IncompleteDiag))
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003227 return move(FromE);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003228
3229 // Look for a conversion to an integral or enumeration type.
3230 UnresolvedSet<4> ViableConversions;
3231 UnresolvedSet<4> ExplicitConversions;
3232 const UnresolvedSetImpl *Conversions
3233 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3234
3235 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3236 E = Conversions->end();
3237 I != E;
3238 ++I) {
3239 if (CXXConversionDecl *Conversion
3240 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3241 if (Conversion->getConversionType().getNonReferenceType()
3242 ->isIntegralOrEnumerationType()) {
3243 if (Conversion->isExplicit())
3244 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3245 else
3246 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3247 }
3248 }
3249
3250 switch (ViableConversions.size()) {
3251 case 0:
3252 if (ExplicitConversions.size() == 1) {
3253 DeclAccessPair Found = ExplicitConversions[0];
3254 CXXConversionDecl *Conversion
3255 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3256
3257 // The user probably meant to invoke the given explicit
3258 // conversion; use it.
3259 QualType ConvTy
3260 = Conversion->getConversionType().getNonReferenceType();
3261 std::string TypeStr;
3262 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3263
3264 Diag(Loc, ExplicitConvDiag)
3265 << T << ConvTy
3266 << FixItHint::CreateInsertion(From->getLocStart(),
3267 "static_cast<" + TypeStr + ">(")
3268 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3269 ")");
3270 Diag(Conversion->getLocation(), ExplicitConvNote)
3271 << ConvTy->isEnumeralType() << ConvTy;
3272
3273 // If we aren't in a SFINAE context, build a call to the
3274 // explicit conversion function.
3275 if (isSFINAEContext())
3276 return ExprError();
3277
3278 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
3279 From = BuildCXXMemberCallExpr(FromE.takeAs<Expr>(), Found, Conversion);
3280 FromE = Owned(From);
3281 }
3282
3283 // We'll complain below about a non-integral condition type.
3284 break;
3285
3286 case 1: {
3287 // Apply this conversion.
3288 DeclAccessPair Found = ViableConversions[0];
3289 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003290
3291 CXXConversionDecl *Conversion
3292 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3293 QualType ConvTy
3294 = Conversion->getConversionType().getNonReferenceType();
3295 if (ConvDiag.getDiagID()) {
3296 if (isSFINAEContext())
3297 return ExprError();
3298
3299 Diag(Loc, ConvDiag)
3300 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3301 }
3302
Douglas Gregorc30614b2010-06-29 23:17:37 +00003303 From = BuildCXXMemberCallExpr(FromE.takeAs<Expr>(), Found,
3304 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
3305 FromE = Owned(From);
3306 break;
3307 }
3308
3309 default:
3310 Diag(Loc, AmbigDiag)
3311 << T << From->getSourceRange();
3312 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3313 CXXConversionDecl *Conv
3314 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3315 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3316 Diag(Conv->getLocation(), AmbigNote)
3317 << ConvTy->isEnumeralType() << ConvTy;
3318 }
Douglas Gregoracb0bd82010-06-29 23:25:20 +00003319 return move(FromE);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003320 }
3321
Douglas Gregoracb0bd82010-06-29 23:25:20 +00003322 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorc30614b2010-06-29 23:17:37 +00003323 Diag(Loc, NotIntDiag)
3324 << From->getType() << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00003325
3326 return move(FromE);
3327}
3328
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003329/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00003330/// candidate functions, using the given function call arguments. If
3331/// @p SuppressUserConversions, then don't allow user-defined
3332/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003333///
3334/// \para PartialOverloading true if we are performing "partial" overloading
3335/// based on an incomplete set of function arguments. This feature is used by
3336/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00003337void
3338Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00003339 DeclAccessPair FoundDecl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003340 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00003341 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00003342 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003343 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00003344 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003345 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003346 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00003347 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00003348 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00003349
Douglas Gregor88a35142008-12-22 05:46:06 +00003350 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003351 if (!isa<CXXConstructorDecl>(Method)) {
3352 // If we get here, it's because we're calling a member function
3353 // that is named without a member access expression (e.g.,
3354 // "this->f") that was either written explicitly or created
3355 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00003356 // function, e.g., X::f(). We use an empty type for the implied
3357 // object argument (C++ [over.call.func]p3), and the acting context
3358 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00003359 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall701c89e2009-12-03 04:06:58 +00003360 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003361 SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003362 return;
3363 }
3364 // We treat a constructor like a non-member function, since its object
3365 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00003366 }
3367
Douglas Gregorfd476482009-11-13 23:59:09 +00003368 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00003369 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00003370
Douglas Gregor7edfb692009-11-23 12:27:39 +00003371 // Overload resolution is always an unevaluated context.
3372 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3373
Douglas Gregor66724ea2009-11-14 01:20:54 +00003374 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3375 // C++ [class.copy]p3:
3376 // A member function template is never instantiated to perform the copy
3377 // of a class object to an object of its class type.
3378 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3379 if (NumArgs == 1 &&
3380 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor12116062010-02-21 18:30:38 +00003381 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3382 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00003383 return;
3384 }
3385
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003386 // Add this candidate
3387 CandidateSet.push_back(OverloadCandidate());
3388 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003389 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003390 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00003391 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003392 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003393 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003394
3395 unsigned NumArgsInProto = Proto->getNumArgs();
3396
3397 // (C++ 13.3.2p2): A candidate function having fewer than m
3398 // parameters is viable only if it has an ellipsis in its parameter
3399 // list (8.3.5).
Douglas Gregor5bd1a112009-09-23 14:56:09 +00003400 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3401 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003402 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003403 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003404 return;
3405 }
3406
3407 // (C++ 13.3.2p2): A candidate function having more than m parameters
3408 // is viable only if the (m+1)st parameter has a default argument
3409 // (8.3.6). For the purposes of overload resolution, the
3410 // parameter list is truncated on the right, so that there are
3411 // exactly m parameters.
3412 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003413 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003414 // Not enough arguments.
3415 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003416 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003417 return;
3418 }
3419
3420 // Determine the implicit conversion sequences for each of the
3421 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003422 Candidate.Conversions.resize(NumArgs);
3423 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3424 if (ArgIdx < NumArgsInProto) {
3425 // (C++ 13.3.2p3): for F to be a viable function, there shall
3426 // exist for each argument an implicit conversion sequence
3427 // (13.3.3.1) that converts that argument to the corresponding
3428 // parameter of F.
3429 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003430 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003431 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003432 SuppressUserConversions,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003433 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003434 if (Candidate.Conversions[ArgIdx].isBad()) {
3435 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003436 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00003437 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00003438 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003439 } else {
3440 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3441 // argument for which there is no corresponding parameter is
3442 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003443 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003444 }
3445 }
3446}
3447
Douglas Gregor063daf62009-03-13 18:40:31 +00003448/// \brief Add all of the function declarations in the given function set to
3449/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00003450void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00003451 Expr **Args, unsigned NumArgs,
3452 OverloadCandidateSet& CandidateSet,
3453 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00003454 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00003455 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3456 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003457 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003458 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003459 cast<CXXMethodDecl>(FD)->getParent(),
3460 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003461 CandidateSet, SuppressUserConversions);
3462 else
John McCall9aa472c2010-03-19 07:35:19 +00003463 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00003464 SuppressUserConversions);
3465 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003466 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00003467 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3468 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003469 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003470 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00003471 /*FIXME: explicit args */ 0,
John McCall701c89e2009-12-03 04:06:58 +00003472 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003473 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00003474 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00003475 else
John McCall9aa472c2010-03-19 07:35:19 +00003476 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCalld5532b62009-11-23 01:53:49 +00003477 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00003478 Args, NumArgs, CandidateSet,
3479 SuppressUserConversions);
3480 }
Douglas Gregor364e0212009-06-27 21:05:07 +00003481 }
Douglas Gregor063daf62009-03-13 18:40:31 +00003482}
3483
John McCall314be4e2009-11-17 07:50:12 +00003484/// AddMethodCandidate - Adds a named decl (which is some kind of
3485/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00003486void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003487 QualType ObjectType,
John McCall314be4e2009-11-17 07:50:12 +00003488 Expr **Args, unsigned NumArgs,
3489 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003490 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00003491 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003492 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00003493
3494 if (isa<UsingShadowDecl>(Decl))
3495 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3496
3497 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3498 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3499 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00003500 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3501 /*ExplicitArgs*/ 0,
John McCall701c89e2009-12-03 04:06:58 +00003502 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00003503 CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003504 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003505 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003506 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall701c89e2009-12-03 04:06:58 +00003507 ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003508 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003509 }
3510}
3511
Douglas Gregor96176b32008-11-18 23:14:02 +00003512/// AddMethodCandidate - Adds the given C++ member function to the set
3513/// of candidate functions, using the given function call arguments
3514/// and the object argument (@c Object). For example, in a call
3515/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3516/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3517/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00003518/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00003519void
John McCall9aa472c2010-03-19 07:35:19 +00003520Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003521 CXXRecordDecl *ActingContext, QualType ObjectType,
3522 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00003523 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003524 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00003525 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003526 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00003527 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003528 assert(!isa<CXXConstructorDecl>(Method) &&
3529 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00003530
Douglas Gregor3f396022009-09-28 04:47:19 +00003531 if (!CandidateSet.isNewCandidate(Method))
3532 return;
3533
Douglas Gregor7edfb692009-11-23 12:27:39 +00003534 // Overload resolution is always an unevaluated context.
3535 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3536
Douglas Gregor96176b32008-11-18 23:14:02 +00003537 // Add this candidate
3538 CandidateSet.push_back(OverloadCandidate());
3539 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003540 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00003541 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003542 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003543 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003544
3545 unsigned NumArgsInProto = Proto->getNumArgs();
3546
3547 // (C++ 13.3.2p2): A candidate function having fewer than m
3548 // parameters is viable only if it has an ellipsis in its parameter
3549 // list (8.3.5).
3550 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3551 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003552 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003553 return;
3554 }
3555
3556 // (C++ 13.3.2p2): A candidate function having more than m parameters
3557 // is viable only if the (m+1)st parameter has a default argument
3558 // (8.3.6). For the purposes of overload resolution, the
3559 // parameter list is truncated on the right, so that there are
3560 // exactly m parameters.
3561 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3562 if (NumArgs < MinRequiredArgs) {
3563 // Not enough arguments.
3564 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003565 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003566 return;
3567 }
3568
3569 Candidate.Viable = true;
3570 Candidate.Conversions.resize(NumArgs + 1);
3571
John McCall701c89e2009-12-03 04:06:58 +00003572 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00003573 // The implicit object argument is ignored.
3574 Candidate.IgnoreObjectArgument = true;
3575 else {
3576 // Determine the implicit conversion sequence for the object
3577 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00003578 Candidate.Conversions[0]
3579 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00003580 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003581 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003582 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00003583 return;
3584 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003585 }
3586
3587 // Determine the implicit conversion sequences for each of the
3588 // arguments.
3589 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3590 if (ArgIdx < NumArgsInProto) {
3591 // (C++ 13.3.2p3): for F to be a viable function, there shall
3592 // exist for each argument an implicit conversion sequence
3593 // (13.3.3.1) that converts that argument to the corresponding
3594 // parameter of F.
3595 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003596 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003597 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003598 SuppressUserConversions,
Anders Carlsson08972922009-08-28 15:33:32 +00003599 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003600 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00003601 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003602 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00003603 break;
3604 }
3605 } else {
3606 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3607 // argument for which there is no corresponding parameter is
3608 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003609 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00003610 }
3611 }
3612}
Douglas Gregora9333192010-05-08 17:41:32 +00003613
Douglas Gregor6b906862009-08-21 00:16:32 +00003614/// \brief Add a C++ member function template as a candidate to the candidate
3615/// set, using template argument deduction to produce an appropriate member
3616/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003617void
Douglas Gregor6b906862009-08-21 00:16:32 +00003618Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00003619 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003620 CXXRecordDecl *ActingContext,
John McCalld5532b62009-11-23 01:53:49 +00003621 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00003622 QualType ObjectType,
3623 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003624 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003625 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003626 if (!CandidateSet.isNewCandidate(MethodTmpl))
3627 return;
3628
Douglas Gregor6b906862009-08-21 00:16:32 +00003629 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003630 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00003631 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003632 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00003633 // candidate functions in the usual way.113) A given name can refer to one
3634 // or more function templates and also to a set of overloaded non-template
3635 // functions. In such a case, the candidate functions generated from each
3636 // function template are combined with the set of non-template candidate
3637 // functions.
John McCall5769d612010-02-08 23:07:23 +00003638 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00003639 FunctionDecl *Specialization = 0;
3640 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003641 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003642 Args, NumArgs, Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003643 CandidateSet.push_back(OverloadCandidate());
3644 OverloadCandidate &Candidate = CandidateSet.back();
3645 Candidate.FoundDecl = FoundDecl;
3646 Candidate.Function = MethodTmpl->getTemplatedDecl();
3647 Candidate.Viable = false;
3648 Candidate.FailureKind = ovl_fail_bad_deduction;
3649 Candidate.IsSurrogate = false;
3650 Candidate.IgnoreObjectArgument = false;
3651 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3652 Info);
3653 return;
3654 }
Mike Stump1eb44332009-09-09 15:08:12 +00003655
Douglas Gregor6b906862009-08-21 00:16:32 +00003656 // Add the function template specialization produced by template argument
3657 // deduction as a candidate.
3658 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00003659 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00003660 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00003661 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003662 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003663 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00003664}
3665
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003666/// \brief Add a C++ function template specialization as a candidate
3667/// in the candidate set, using template argument deduction to produce
3668/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003669void
Douglas Gregore53060f2009-06-25 22:08:12 +00003670Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003671 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00003672 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00003673 Expr **Args, unsigned NumArgs,
3674 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003675 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003676 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3677 return;
3678
Douglas Gregore53060f2009-06-25 22:08:12 +00003679 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003680 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00003681 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003682 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00003683 // candidate functions in the usual way.113) A given name can refer to one
3684 // or more function templates and also to a set of overloaded non-template
3685 // functions. In such a case, the candidate functions generated from each
3686 // function template are combined with the set of non-template candidate
3687 // functions.
John McCall5769d612010-02-08 23:07:23 +00003688 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00003689 FunctionDecl *Specialization = 0;
3690 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003691 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003692 Args, NumArgs, Specialization, Info)) {
John McCall578b69b2009-12-16 08:11:27 +00003693 CandidateSet.push_back(OverloadCandidate());
3694 OverloadCandidate &Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003695 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00003696 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3697 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003698 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00003699 Candidate.IsSurrogate = false;
3700 Candidate.IgnoreObjectArgument = false;
Douglas Gregorff5adac2010-05-08 20:18:54 +00003701 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3702 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00003703 return;
3704 }
Mike Stump1eb44332009-09-09 15:08:12 +00003705
Douglas Gregore53060f2009-06-25 22:08:12 +00003706 // Add the function template specialization produced by template argument
3707 // deduction as a candidate.
3708 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003709 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003710 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00003711}
Mike Stump1eb44332009-09-09 15:08:12 +00003712
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003713/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00003714/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003715/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00003716/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003717/// (which may or may not be the same type as the type that the
3718/// conversion function produces).
3719void
3720Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003721 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003722 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003723 Expr *From, QualType ToType,
3724 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003725 assert(!Conversion->getDescribedFunctionTemplate() &&
3726 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003727 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00003728 if (!CandidateSet.isNewCandidate(Conversion))
3729 return;
3730
Douglas Gregor7edfb692009-11-23 12:27:39 +00003731 // Overload resolution is always an unevaluated context.
3732 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3733
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003734 // Add this candidate
3735 CandidateSet.push_back(OverloadCandidate());
3736 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003737 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003738 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003739 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003740 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003741 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003742 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003743 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003744 Candidate.Viable = true;
3745 Candidate.Conversions.resize(1);
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003746
Douglas Gregorbca39322010-08-19 15:37:02 +00003747 // C++ [over.match.funcs]p4:
3748 // For conversion functions, the function is considered to be a member of
3749 // the class of the implicit implied object argument for the purpose of
3750 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003751 //
3752 // Determine the implicit conversion sequence for the implicit
3753 // object parameter.
3754 QualType ImplicitParamType = From->getType();
3755 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
3756 ImplicitParamType = FromPtrType->getPointeeType();
3757 CXXRecordDecl *ConversionContext
3758 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
3759
3760 Candidate.Conversions[0]
3761 = TryObjectArgumentInitialization(From->getType(), Conversion,
3762 ConversionContext);
3763
John McCall1d318332010-01-12 00:44:57 +00003764 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003765 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003766 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003767 return;
3768 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003769
3770 // Make sure that the actual object argument initialization will work, when
3771 // it comes down to it. This takes into account the actual acting context.
3772 if (ConversionContext->getCanonicalDecl()
3773 != ActingContext->getCanonicalDecl()) {
3774 ImplicitConversionSequence ObjectConvertICS
3775 = TryObjectArgumentInitialization(From->getType(), Conversion,
3776 ActingContext);
3777 if (ObjectConvertICS.isBad()) {
3778 Candidate.Viable = false;
3779 Candidate.FailureKind = ovl_fail_bad_conversion;
3780 Candidate.Conversions[0] = ObjectConvertICS;
3781 return;
3782 }
3783 }
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003784
3785 // We won't go through a user-define type conversion function to convert a
3786 // derived to base as such conversions are given Conversion Rank. They only
3787 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3788 QualType FromCanon
3789 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3790 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3791 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3792 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003793 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003794 return;
3795 }
3796
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003797 // To determine what the conversion from the result of calling the
3798 // conversion function to the type we're eventually trying to
3799 // convert to (ToType), we need to synthesize a call to the
3800 // conversion function and attempt copy initialization from it. This
3801 // makes sure that we get the right semantics with respect to
3802 // lvalues/rvalues and the type. Fortunately, we can allocate this
3803 // call on the stack and we don't need its arguments to be
3804 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00003805 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003806 From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00003807 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
3808 Context.getPointerType(Conversion->getType()),
Eli Friedman73c39ab2009-10-20 08:27:19 +00003809 CastExpr::CK_FunctionToPointerDecay,
John McCallf871d0c2010-08-07 06:22:56 +00003810 &ConversionRef, ImplicitCastExpr::RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00003811
3812 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00003813 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3814 // allocator).
Mike Stump1eb44332009-09-09 15:08:12 +00003815 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregor63982352010-07-13 18:40:04 +00003816 Conversion->getConversionType().getNonLValueExprType(Context),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003817 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00003818 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00003819 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00003820 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003821 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00003822
John McCall1d318332010-01-12 00:44:57 +00003823 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003824 case ImplicitConversionSequence::StandardConversion:
3825 Candidate.FinalConversion = ICS.Standard;
Douglas Gregorc520c842010-04-12 23:42:09 +00003826
3827 // C++ [over.ics.user]p3:
3828 // If the user-defined conversion is specified by a specialization of a
3829 // conversion function template, the second standard conversion sequence
3830 // shall have exact match rank.
3831 if (Conversion->getPrimaryTemplate() &&
3832 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3833 Candidate.Viable = false;
3834 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3835 }
3836
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003837 break;
3838
3839 case ImplicitConversionSequence::BadConversion:
3840 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003841 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003842 break;
3843
3844 default:
Mike Stump1eb44332009-09-09 15:08:12 +00003845 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003846 "Can only end up with a standard conversion sequence or failure");
3847 }
3848}
3849
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003850/// \brief Adds a conversion function template specialization
3851/// candidate to the overload set, using template argument deduction
3852/// to deduce the template arguments of the conversion function
3853/// template from the type that we are converting to (C++
3854/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00003855void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003856Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003857 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003858 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003859 Expr *From, QualType ToType,
3860 OverloadCandidateSet &CandidateSet) {
3861 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3862 "Only conversion function templates permitted here");
3863
Douglas Gregor3f396022009-09-28 04:47:19 +00003864 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3865 return;
3866
John McCall5769d612010-02-08 23:07:23 +00003867 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003868 CXXConversionDecl *Specialization = 0;
3869 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00003870 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003871 Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003872 CandidateSet.push_back(OverloadCandidate());
3873 OverloadCandidate &Candidate = CandidateSet.back();
3874 Candidate.FoundDecl = FoundDecl;
3875 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3876 Candidate.Viable = false;
3877 Candidate.FailureKind = ovl_fail_bad_deduction;
3878 Candidate.IsSurrogate = false;
3879 Candidate.IgnoreObjectArgument = false;
3880 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3881 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003882 return;
3883 }
Mike Stump1eb44332009-09-09 15:08:12 +00003884
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003885 // Add the conversion function template specialization produced by
3886 // template argument deduction as a candidate.
3887 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003888 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00003889 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003890}
3891
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003892/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3893/// converts the given @c Object to a function pointer via the
3894/// conversion function @c Conversion, and then attempts to call it
3895/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3896/// the type of function that we'll eventually be calling.
3897void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003898 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003899 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00003900 const FunctionProtoType *Proto,
John McCall701c89e2009-12-03 04:06:58 +00003901 QualType ObjectType,
3902 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003903 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003904 if (!CandidateSet.isNewCandidate(Conversion))
3905 return;
3906
Douglas Gregor7edfb692009-11-23 12:27:39 +00003907 // Overload resolution is always an unevaluated context.
3908 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3909
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003910 CandidateSet.push_back(OverloadCandidate());
3911 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003912 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003913 Candidate.Function = 0;
3914 Candidate.Surrogate = Conversion;
3915 Candidate.Viable = true;
3916 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003917 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003918 Candidate.Conversions.resize(NumArgs + 1);
3919
3920 // Determine the implicit conversion sequence for the implicit
3921 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00003922 ImplicitConversionSequence ObjectInit
John McCall701c89e2009-12-03 04:06:58 +00003923 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00003924 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003925 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003926 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00003927 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003928 return;
3929 }
3930
3931 // The first conversion is actually a user-defined conversion whose
3932 // first conversion is ObjectInit's standard conversion (which is
3933 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00003934 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003935 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00003936 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003937 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00003938 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003939 = Candidate.Conversions[0].UserDefined.Before;
3940 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3941
Mike Stump1eb44332009-09-09 15:08:12 +00003942 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003943 unsigned NumArgsInProto = Proto->getNumArgs();
3944
3945 // (C++ 13.3.2p2): A candidate function having fewer than m
3946 // parameters is viable only if it has an ellipsis in its parameter
3947 // list (8.3.5).
3948 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3949 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003950 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003951 return;
3952 }
3953
3954 // Function types don't have any default arguments, so just check if
3955 // we have enough arguments.
3956 if (NumArgs < NumArgsInProto) {
3957 // Not enough arguments.
3958 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003959 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003960 return;
3961 }
3962
3963 // Determine the implicit conversion sequences for each of the
3964 // arguments.
3965 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3966 if (ArgIdx < NumArgsInProto) {
3967 // (C++ 13.3.2p3): for F to be a viable function, there shall
3968 // exist for each argument an implicit conversion sequence
3969 // (13.3.3.1) that converts that argument to the corresponding
3970 // parameter of F.
3971 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003972 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003973 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00003974 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003975 /*InOverloadResolution=*/false);
John McCall1d318332010-01-12 00:44:57 +00003976 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003977 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003978 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003979 break;
3980 }
3981 } else {
3982 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3983 // argument for which there is no corresponding parameter is
3984 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003985 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003986 }
3987 }
3988}
3989
Douglas Gregor063daf62009-03-13 18:40:31 +00003990/// \brief Add overload candidates for overloaded operators that are
3991/// member functions.
3992///
3993/// Add the overloaded operator candidates that are member functions
3994/// for the operator Op that was used in an operator expression such
3995/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3996/// CandidateSet will store the added overload candidates. (C++
3997/// [over.match.oper]).
3998void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3999 SourceLocation OpLoc,
4000 Expr **Args, unsigned NumArgs,
4001 OverloadCandidateSet& CandidateSet,
4002 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00004003 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4004
4005 // C++ [over.match.oper]p3:
4006 // For a unary operator @ with an operand of a type whose
4007 // cv-unqualified version is T1, and for a binary operator @ with
4008 // a left operand of a type whose cv-unqualified version is T1 and
4009 // a right operand of a type whose cv-unqualified version is T2,
4010 // three sets of candidate functions, designated member
4011 // candidates, non-member candidates and built-in candidates, are
4012 // constructed as follows:
4013 QualType T1 = Args[0]->getType();
4014 QualType T2;
4015 if (NumArgs > 1)
4016 T2 = Args[1]->getType();
4017
4018 // -- If T1 is a class type, the set of member candidates is the
4019 // result of the qualified lookup of T1::operator@
4020 // (13.3.1.1.1); otherwise, the set of member candidates is
4021 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00004022 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004023 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004024 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004025 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004026
John McCalla24dc2e2009-11-17 02:14:36 +00004027 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4028 LookupQualifiedName(Operators, T1Rec->getDecl());
4029 Operators.suppressDiagnostics();
4030
Mike Stump1eb44332009-09-09 15:08:12 +00004031 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004032 OperEnd = Operators.end();
4033 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00004034 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00004035 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall701c89e2009-12-03 04:06:58 +00004036 Args + 1, NumArgs - 1, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00004037 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00004038 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004039}
4040
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004041/// AddBuiltinCandidate - Add a candidate for a built-in
4042/// operator. ResultTy and ParamTys are the result and parameter types
4043/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004044/// arguments being passed to the candidate. IsAssignmentOperator
4045/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004046/// operator. NumContextualBoolArguments is the number of arguments
4047/// (at the beginning of the argument list) that will be contextually
4048/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00004049void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004050 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004051 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004052 bool IsAssignmentOperator,
4053 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00004054 // Overload resolution is always an unevaluated context.
4055 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
4056
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004057 // Add this candidate
4058 CandidateSet.push_back(OverloadCandidate());
4059 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004060 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004061 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00004062 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004063 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004064 Candidate.BuiltinTypes.ResultTy = ResultTy;
4065 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4066 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4067
4068 // Determine the implicit conversion sequences for each of the
4069 // arguments.
4070 Candidate.Viable = true;
4071 Candidate.Conversions.resize(NumArgs);
4072 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004073 // C++ [over.match.oper]p4:
4074 // For the built-in assignment operators, conversions of the
4075 // left operand are restricted as follows:
4076 // -- no temporaries are introduced to hold the left operand, and
4077 // -- no user-defined conversions are applied to the left
4078 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00004079 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004080 //
4081 // We block these conversions by turning off user-defined
4082 // conversions, since that is the only way that initialization of
4083 // a reference to a non-class type can occur from something that
4084 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004085 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00004086 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004087 "Contextual conversion to bool requires bool type");
4088 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
4089 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00004090 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004091 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00004092 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00004093 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004094 }
John McCall1d318332010-01-12 00:44:57 +00004095 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004096 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004097 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00004098 break;
4099 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004100 }
4101}
4102
4103/// BuiltinCandidateTypeSet - A set of types that will be used for the
4104/// candidate operator functions for built-in operators (C++
4105/// [over.built]). The types are separated into pointer types and
4106/// enumeration types.
4107class BuiltinCandidateTypeSet {
4108 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004109 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004110
4111 /// PointerTypes - The set of pointer types that will be used in the
4112 /// built-in candidates.
4113 TypeSet PointerTypes;
4114
Sebastian Redl78eb8742009-04-19 21:53:20 +00004115 /// MemberPointerTypes - The set of member pointer types that will be
4116 /// used in the built-in candidates.
4117 TypeSet MemberPointerTypes;
4118
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004119 /// EnumerationTypes - The set of enumeration types that will be
4120 /// used in the built-in candidates.
4121 TypeSet EnumerationTypes;
4122
Douglas Gregor26bcf672010-05-19 03:21:00 +00004123 /// \brief The set of vector types that will be used in the built-in
4124 /// candidates.
4125 TypeSet VectorTypes;
4126
Douglas Gregor5842ba92009-08-24 15:23:48 +00004127 /// Sema - The semantic analysis instance where we are building the
4128 /// candidate type set.
4129 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00004130
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004131 /// Context - The AST context in which we will build the type sets.
4132 ASTContext &Context;
4133
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004134 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4135 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00004136 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004137
4138public:
4139 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004140 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004141
Mike Stump1eb44332009-09-09 15:08:12 +00004142 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor5842ba92009-08-24 15:23:48 +00004143 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004144
Douglas Gregor573d9c32009-10-21 23:19:44 +00004145 void AddTypesConvertedFrom(QualType Ty,
4146 SourceLocation Loc,
4147 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004148 bool AllowExplicitConversions,
4149 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004150
4151 /// pointer_begin - First pointer type found;
4152 iterator pointer_begin() { return PointerTypes.begin(); }
4153
Sebastian Redl78eb8742009-04-19 21:53:20 +00004154 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004155 iterator pointer_end() { return PointerTypes.end(); }
4156
Sebastian Redl78eb8742009-04-19 21:53:20 +00004157 /// member_pointer_begin - First member pointer type found;
4158 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4159
4160 /// member_pointer_end - Past the last member pointer type found;
4161 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4162
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004163 /// enumeration_begin - First enumeration type found;
4164 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4165
Sebastian Redl78eb8742009-04-19 21:53:20 +00004166 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004167 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004168
4169 iterator vector_begin() { return VectorTypes.begin(); }
4170 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004171};
4172
Sebastian Redl78eb8742009-04-19 21:53:20 +00004173/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004174/// the set of pointer types along with any more-qualified variants of
4175/// that type. For example, if @p Ty is "int const *", this routine
4176/// will add "int const *", "int const volatile *", "int const
4177/// restrict *", and "int const volatile restrict *" to the set of
4178/// pointer types. Returns true if the add of @p Ty itself succeeded,
4179/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00004180///
4181/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004182bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00004183BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4184 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00004185
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004186 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004187 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004188 return false;
4189
John McCall0953e762009-09-24 19:53:00 +00004190 const PointerType *PointerTy = Ty->getAs<PointerType>();
4191 assert(PointerTy && "type was not a pointer type!");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004192
John McCall0953e762009-09-24 19:53:00 +00004193 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00004194 // Don't add qualified variants of arrays. For one, they're not allowed
4195 // (the qualifier would sink to the element type), and for another, the
4196 // only overload situation where it matters is subscript or pointer +- int,
4197 // and those shouldn't have qualifier variants anyway.
4198 if (PointeeTy->isArrayType())
4199 return true;
John McCall0953e762009-09-24 19:53:00 +00004200 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00004201 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00004202 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004203 bool hasVolatile = VisibleQuals.hasVolatile();
4204 bool hasRestrict = VisibleQuals.hasRestrict();
4205
John McCall0953e762009-09-24 19:53:00 +00004206 // Iterate through all strict supersets of BaseCVR.
4207 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4208 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004209 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4210 // in the types.
4211 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4212 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00004213 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4214 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004215 }
4216
4217 return true;
4218}
4219
Sebastian Redl78eb8742009-04-19 21:53:20 +00004220/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4221/// to the set of pointer types along with any more-qualified variants of
4222/// that type. For example, if @p Ty is "int const *", this routine
4223/// will add "int const *", "int const volatile *", "int const
4224/// restrict *", and "int const volatile restrict *" to the set of
4225/// pointer types. Returns true if the add of @p Ty itself succeeded,
4226/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00004227///
4228/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004229bool
4230BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4231 QualType Ty) {
4232 // Insert this type.
4233 if (!MemberPointerTypes.insert(Ty))
4234 return false;
4235
John McCall0953e762009-09-24 19:53:00 +00004236 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4237 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00004238
John McCall0953e762009-09-24 19:53:00 +00004239 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00004240 // Don't add qualified variants of arrays. For one, they're not allowed
4241 // (the qualifier would sink to the element type), and for another, the
4242 // only overload situation where it matters is subscript or pointer +- int,
4243 // and those shouldn't have qualifier variants anyway.
4244 if (PointeeTy->isArrayType())
4245 return true;
John McCall0953e762009-09-24 19:53:00 +00004246 const Type *ClassTy = PointerTy->getClass();
4247
4248 // Iterate through all strict supersets of the pointee type's CVR
4249 // qualifiers.
4250 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4251 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4252 if ((CVR | BaseCVR) != CVR) continue;
4253
4254 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4255 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00004256 }
4257
4258 return true;
4259}
4260
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004261/// AddTypesConvertedFrom - Add each of the types to which the type @p
4262/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00004263/// primarily interested in pointer types and enumeration types. We also
4264/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004265/// AllowUserConversions is true if we should look at the conversion
4266/// functions of a class type, and AllowExplicitConversions if we
4267/// should also include the explicit conversion functions of a class
4268/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00004269void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004270BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004271 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004272 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004273 bool AllowExplicitConversions,
4274 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004275 // Only deal with canonical types.
4276 Ty = Context.getCanonicalType(Ty);
4277
4278 // Look through reference types; they aren't part of the type of an
4279 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00004280 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004281 Ty = RefTy->getPointeeType();
4282
4283 // We don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004284 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004285
Sebastian Redla65b5512009-11-05 16:36:20 +00004286 // If we're dealing with an array type, decay to the pointer.
4287 if (Ty->isArrayType())
4288 Ty = SemaRef.Context.getArrayDecayedType(Ty);
4289
Ted Kremenek6217b802009-07-29 21:53:49 +00004290 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004291 QualType PointeeTy = PointerTy->getPointeeType();
4292
4293 // Insert our type, and its more-qualified variants, into the set
4294 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004295 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004296 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00004297 } else if (Ty->isMemberPointerType()) {
4298 // Member pointers are far easier, since the pointee can't be converted.
4299 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4300 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004301 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00004302 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004303 } else if (Ty->isVectorType()) {
4304 VectorTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004305 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004306 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00004307 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00004308 // No conversion functions in incomplete types.
4309 return;
4310 }
Mike Stump1eb44332009-09-09 15:08:12 +00004311
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004312 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00004313 const UnresolvedSetImpl *Conversions
Fariborz Jahanianca4fb042009-10-07 17:26:09 +00004314 = ClassDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00004315 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004316 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00004317 NamedDecl *D = I.getDecl();
4318 if (isa<UsingShadowDecl>(D))
4319 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004320
Mike Stump1eb44332009-09-09 15:08:12 +00004321 // Skip conversion function templates; they don't tell us anything
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004322 // about which builtin types we can convert to.
John McCall32daa422010-03-31 01:36:47 +00004323 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004324 continue;
4325
John McCall32daa422010-03-31 01:36:47 +00004326 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004327 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00004328 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004329 VisibleQuals);
4330 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004331 }
4332 }
4333 }
4334}
4335
Douglas Gregor19b7b152009-08-24 13:43:27 +00004336/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4337/// the volatile- and non-volatile-qualified assignment operators for the
4338/// given type to the candidate set.
4339static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4340 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00004341 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004342 unsigned NumArgs,
4343 OverloadCandidateSet &CandidateSet) {
4344 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00004345
Douglas Gregor19b7b152009-08-24 13:43:27 +00004346 // T& operator=(T&, T)
4347 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4348 ParamTypes[1] = T;
4349 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4350 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004351
Douglas Gregor19b7b152009-08-24 13:43:27 +00004352 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4353 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00004354 ParamTypes[0]
4355 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00004356 ParamTypes[1] = T;
4357 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00004358 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00004359 }
4360}
Mike Stump1eb44332009-09-09 15:08:12 +00004361
Sebastian Redl9994a342009-10-25 17:03:50 +00004362/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4363/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004364static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4365 Qualifiers VRQuals;
4366 const RecordType *TyRec;
4367 if (const MemberPointerType *RHSMPType =
4368 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004369 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004370 else
4371 TyRec = ArgExpr->getType()->getAs<RecordType>();
4372 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004373 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004374 VRQuals.addVolatile();
4375 VRQuals.addRestrict();
4376 return VRQuals;
4377 }
4378
4379 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00004380 if (!ClassDecl->hasDefinition())
4381 return VRQuals;
4382
John McCalleec51cf2010-01-20 00:46:10 +00004383 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00004384 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004385
John McCalleec51cf2010-01-20 00:46:10 +00004386 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004387 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00004388 NamedDecl *D = I.getDecl();
4389 if (isa<UsingShadowDecl>(D))
4390 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4391 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004392 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4393 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4394 CanTy = ResTypeRef->getPointeeType();
4395 // Need to go down the pointer/mempointer chain and add qualifiers
4396 // as see them.
4397 bool done = false;
4398 while (!done) {
4399 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4400 CanTy = ResTypePtr->getPointeeType();
4401 else if (const MemberPointerType *ResTypeMPtr =
4402 CanTy->getAs<MemberPointerType>())
4403 CanTy = ResTypeMPtr->getPointeeType();
4404 else
4405 done = true;
4406 if (CanTy.isVolatileQualified())
4407 VRQuals.addVolatile();
4408 if (CanTy.isRestrictQualified())
4409 VRQuals.addRestrict();
4410 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4411 return VRQuals;
4412 }
4413 }
4414 }
4415 return VRQuals;
4416}
4417
Douglas Gregor74253732008-11-19 15:42:04 +00004418/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4419/// operator overloads to the candidate set (C++ [over.built]), based
4420/// on the operator @p Op and the arguments given. For example, if the
4421/// operator is a binary '+', this routine might add "int
4422/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004423void
Mike Stump1eb44332009-09-09 15:08:12 +00004424Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004425 SourceLocation OpLoc,
Douglas Gregor74253732008-11-19 15:42:04 +00004426 Expr **Args, unsigned NumArgs,
4427 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004428 // The set of "promoted arithmetic types", which are the arithmetic
4429 // types are that preserved by promotion (C++ [over.built]p2). Note
4430 // that the first few of these types are the promoted integral
4431 // types; these types need to be first.
4432 // FIXME: What about complex?
4433 const unsigned FirstIntegralType = 0;
4434 const unsigned LastIntegralType = 13;
Mike Stump1eb44332009-09-09 15:08:12 +00004435 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004436 LastPromotedIntegralType = 13;
4437 const unsigned FirstPromotedArithmeticType = 7,
4438 LastPromotedArithmeticType = 16;
4439 const unsigned NumArithmeticTypes = 16;
4440 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump1eb44332009-09-09 15:08:12 +00004441 Context.BoolTy, Context.CharTy, Context.WCharTy,
4442// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004443 Context.SignedCharTy, Context.ShortTy,
4444 Context.UnsignedCharTy, Context.UnsignedShortTy,
4445 Context.IntTy, Context.LongTy, Context.LongLongTy,
4446 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
4447 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
4448 };
Douglas Gregor652371a2009-10-21 22:01:30 +00004449 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
4450 "Invalid first promoted integral type");
4451 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4452 == Context.UnsignedLongLongTy &&
4453 "Invalid last promoted integral type");
4454 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
4455 "Invalid first promoted arithmetic type");
4456 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4457 == Context.LongDoubleTy &&
4458 "Invalid last promoted arithmetic type");
4459
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004460 // Find all of the types that the arguments can convert to, but only
4461 // if the operator we're looking at has built-in operator candidates
4462 // that make use of these types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004463 Qualifiers VisibleTypeConversionsQuals;
4464 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004465 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4466 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4467
Douglas Gregor5842ba92009-08-24 15:23:48 +00004468 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004469 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4470 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4471 OpLoc,
4472 true,
4473 (Op == OO_Exclaim ||
4474 Op == OO_AmpAmp ||
4475 Op == OO_PipePipe),
4476 VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004477
4478 bool isComparison = false;
4479 switch (Op) {
4480 case OO_None:
4481 case NUM_OVERLOADED_OPERATORS:
4482 assert(false && "Expected an overloaded operator");
4483 break;
4484
Douglas Gregor74253732008-11-19 15:42:04 +00004485 case OO_Star: // '*' is either unary or binary
Mike Stump1eb44332009-09-09 15:08:12 +00004486 if (NumArgs == 1)
Douglas Gregor74253732008-11-19 15:42:04 +00004487 goto UnaryStar;
4488 else
4489 goto BinaryStar;
4490 break;
4491
4492 case OO_Plus: // '+' is either unary or binary
4493 if (NumArgs == 1)
4494 goto UnaryPlus;
4495 else
4496 goto BinaryPlus;
4497 break;
4498
4499 case OO_Minus: // '-' is either unary or binary
4500 if (NumArgs == 1)
4501 goto UnaryMinus;
4502 else
4503 goto BinaryMinus;
4504 break;
4505
4506 case OO_Amp: // '&' is either unary or binary
4507 if (NumArgs == 1)
4508 goto UnaryAmp;
4509 else
4510 goto BinaryAmp;
4511
4512 case OO_PlusPlus:
4513 case OO_MinusMinus:
4514 // C++ [over.built]p3:
4515 //
4516 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4517 // is either volatile or empty, there exist candidate operator
4518 // functions of the form
4519 //
4520 // VQ T& operator++(VQ T&);
4521 // T operator++(VQ T&, int);
4522 //
4523 // C++ [over.built]p4:
4524 //
4525 // For every pair (T, VQ), where T is an arithmetic type other
4526 // than bool, and VQ is either volatile or empty, there exist
4527 // candidate operator functions of the form
4528 //
4529 // VQ T& operator--(VQ T&);
4530 // T operator--(VQ T&, int);
Mike Stump1eb44332009-09-09 15:08:12 +00004531 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor74253732008-11-19 15:42:04 +00004532 Arith < NumArithmeticTypes; ++Arith) {
4533 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump1eb44332009-09-09 15:08:12 +00004534 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004535 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00004536
4537 // Non-volatile version.
4538 if (NumArgs == 1)
4539 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4540 else
4541 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004542 // heuristic to reduce number of builtin candidates in the set.
4543 // Add volatile version only if there are conversions to a volatile type.
4544 if (VisibleTypeConversionsQuals.hasVolatile()) {
4545 // Volatile version
4546 ParamTypes[0]
4547 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4548 if (NumArgs == 1)
4549 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4550 else
4551 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4552 }
Douglas Gregor74253732008-11-19 15:42:04 +00004553 }
4554
4555 // C++ [over.built]p5:
4556 //
4557 // For every pair (T, VQ), where T is a cv-qualified or
4558 // cv-unqualified object type, and VQ is either volatile or
4559 // empty, there exist candidate operator functions of the form
4560 //
4561 // T*VQ& operator++(T*VQ&);
4562 // T*VQ& operator--(T*VQ&);
4563 // T* operator++(T*VQ&, int);
4564 // T* operator--(T*VQ&, int);
4565 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4566 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4567 // Skip pointer types that aren't pointers to object types.
Eli Friedman13578692010-08-05 02:49:48 +00004568 if (!(*Ptr)->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00004569 continue;
4570
Mike Stump1eb44332009-09-09 15:08:12 +00004571 QualType ParamTypes[2] = {
4572 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00004573 };
Mike Stump1eb44332009-09-09 15:08:12 +00004574
Douglas Gregor74253732008-11-19 15:42:04 +00004575 // Without volatile
4576 if (NumArgs == 1)
4577 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4578 else
4579 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4580
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004581 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4582 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00004583 // With volatile
John McCall0953e762009-09-24 19:53:00 +00004584 ParamTypes[0]
4585 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor74253732008-11-19 15:42:04 +00004586 if (NumArgs == 1)
4587 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4588 else
4589 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4590 }
4591 }
4592 break;
4593
4594 UnaryStar:
4595 // C++ [over.built]p6:
4596 // For every cv-qualified or cv-unqualified object type T, there
4597 // exist candidate operator functions of the form
4598 //
4599 // T& operator*(T*);
4600 //
4601 // C++ [over.built]p7:
4602 // For every function type T, there exist candidate operator
4603 // functions of the form
4604 // T& operator*(T*);
4605 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4606 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4607 QualType ParamTy = *Ptr;
Ted Kremenek6217b802009-07-29 21:53:49 +00004608 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004609 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00004610 &ParamTy, Args, 1, CandidateSet);
4611 }
4612 break;
4613
4614 UnaryPlus:
4615 // C++ [over.built]p8:
4616 // For every type T, there exist candidate operator functions of
4617 // the form
4618 //
4619 // T* operator+(T*);
4620 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4621 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4622 QualType ParamTy = *Ptr;
4623 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4624 }
Mike Stump1eb44332009-09-09 15:08:12 +00004625
Douglas Gregor74253732008-11-19 15:42:04 +00004626 // Fall through
4627
4628 UnaryMinus:
4629 // C++ [over.built]p9:
4630 // For every promoted arithmetic type T, there exist candidate
4631 // operator functions of the form
4632 //
4633 // T operator+(T);
4634 // T operator-(T);
Mike Stump1eb44332009-09-09 15:08:12 +00004635 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor74253732008-11-19 15:42:04 +00004636 Arith < LastPromotedArithmeticType; ++Arith) {
4637 QualType ArithTy = ArithmeticTypes[Arith];
4638 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4639 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004640
4641 // Extension: We also add these operators for vector types.
4642 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4643 VecEnd = CandidateTypes.vector_end();
4644 Vec != VecEnd; ++Vec) {
4645 QualType VecTy = *Vec;
4646 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4647 }
Douglas Gregor74253732008-11-19 15:42:04 +00004648 break;
4649
4650 case OO_Tilde:
4651 // C++ [over.built]p10:
4652 // For every promoted integral type T, there exist candidate
4653 // operator functions of the form
4654 //
4655 // T operator~(T);
Mike Stump1eb44332009-09-09 15:08:12 +00004656 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor74253732008-11-19 15:42:04 +00004657 Int < LastPromotedIntegralType; ++Int) {
4658 QualType IntTy = ArithmeticTypes[Int];
4659 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4660 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004661
4662 // Extension: We also add this operator for vector types.
4663 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4664 VecEnd = CandidateTypes.vector_end();
4665 Vec != VecEnd; ++Vec) {
4666 QualType VecTy = *Vec;
4667 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4668 }
Douglas Gregor74253732008-11-19 15:42:04 +00004669 break;
4670
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004671 case OO_New:
4672 case OO_Delete:
4673 case OO_Array_New:
4674 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004675 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00004676 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004677 break;
4678
4679 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00004680 UnaryAmp:
4681 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004682 // C++ [over.match.oper]p3:
4683 // -- For the operator ',', the unary operator '&', or the
4684 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004685 break;
4686
Douglas Gregor19b7b152009-08-24 13:43:27 +00004687 case OO_EqualEqual:
4688 case OO_ExclaimEqual:
4689 // C++ [over.match.oper]p16:
Mike Stump1eb44332009-09-09 15:08:12 +00004690 // For every pointer to member type T, there exist candidate operator
4691 // functions of the form
Douglas Gregor19b7b152009-08-24 13:43:27 +00004692 //
4693 // bool operator==(T,T);
4694 // bool operator!=(T,T);
Mike Stump1eb44332009-09-09 15:08:12 +00004695 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor19b7b152009-08-24 13:43:27 +00004696 MemPtr = CandidateTypes.member_pointer_begin(),
4697 MemPtrEnd = CandidateTypes.member_pointer_end();
4698 MemPtr != MemPtrEnd;
4699 ++MemPtr) {
4700 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4701 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4702 }
Mike Stump1eb44332009-09-09 15:08:12 +00004703
Douglas Gregor19b7b152009-08-24 13:43:27 +00004704 // Fall through
Mike Stump1eb44332009-09-09 15:08:12 +00004705
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004706 case OO_Less:
4707 case OO_Greater:
4708 case OO_LessEqual:
4709 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004710 // C++ [over.built]p15:
4711 //
4712 // For every pointer or enumeration type T, there exist
4713 // candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004714 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004715 // bool operator<(T, T);
4716 // bool operator>(T, T);
4717 // bool operator<=(T, T);
4718 // bool operator>=(T, T);
4719 // bool operator==(T, T);
4720 // bool operator!=(T, T);
4721 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4722 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4723 QualType ParamTypes[2] = { *Ptr, *Ptr };
4724 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4725 }
Mike Stump1eb44332009-09-09 15:08:12 +00004726 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004727 = CandidateTypes.enumeration_begin();
4728 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4729 QualType ParamTypes[2] = { *Enum, *Enum };
4730 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4731 }
4732
4733 // Fall through.
4734 isComparison = true;
4735
Douglas Gregor74253732008-11-19 15:42:04 +00004736 BinaryPlus:
4737 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004738 if (!isComparison) {
4739 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4740
4741 // C++ [over.built]p13:
4742 //
4743 // For every cv-qualified or cv-unqualified object type T
4744 // there exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004745 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004746 // T* operator+(T*, ptrdiff_t);
4747 // T& operator[](T*, ptrdiff_t); [BELOW]
4748 // T* operator-(T*, ptrdiff_t);
4749 // T* operator+(ptrdiff_t, T*);
4750 // T& operator[](ptrdiff_t, T*); [BELOW]
4751 //
4752 // C++ [over.built]p14:
4753 //
4754 // For every T, where T is a pointer to object type, there
4755 // exist candidate operator functions of the form
4756 //
4757 // ptrdiff_t operator-(T, T);
Mike Stump1eb44332009-09-09 15:08:12 +00004758 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004759 = CandidateTypes.pointer_begin();
4760 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4761 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4762
4763 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4764 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4765
4766 if (Op == OO_Plus) {
4767 // T* operator+(ptrdiff_t, T*);
4768 ParamTypes[0] = ParamTypes[1];
4769 ParamTypes[1] = *Ptr;
4770 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4771 } else {
4772 // ptrdiff_t operator-(T, T);
4773 ParamTypes[1] = *Ptr;
4774 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4775 Args, 2, CandidateSet);
4776 }
4777 }
4778 }
4779 // Fall through
4780
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004781 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00004782 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004783 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004784 // C++ [over.built]p12:
4785 //
4786 // For every pair of promoted arithmetic types L and R, there
4787 // exist candidate operator functions of the form
4788 //
4789 // LR operator*(L, R);
4790 // LR operator/(L, R);
4791 // LR operator+(L, R);
4792 // LR operator-(L, R);
4793 // bool operator<(L, R);
4794 // bool operator>(L, R);
4795 // bool operator<=(L, R);
4796 // bool operator>=(L, R);
4797 // bool operator==(L, R);
4798 // bool operator!=(L, R);
4799 //
4800 // where LR is the result of the usual arithmetic conversions
4801 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004802 //
4803 // C++ [over.built]p24:
4804 //
4805 // For every pair of promoted arithmetic types L and R, there exist
4806 // candidate operator functions of the form
4807 //
4808 // LR operator?(bool, L, R);
4809 //
4810 // where LR is the result of the usual arithmetic conversions
4811 // between types L and R.
4812 // Our candidates ignore the first parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00004813 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004814 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004815 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004816 Right < LastPromotedArithmeticType; ++Right) {
4817 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00004818 QualType Result
4819 = isComparison
4820 ? Context.BoolTy
4821 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004822 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4823 }
4824 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004825
4826 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
4827 // conditional operator for vector types.
4828 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4829 Vec1End = CandidateTypes.vector_end();
4830 Vec1 != Vec1End; ++Vec1)
4831 for (BuiltinCandidateTypeSet::iterator
4832 Vec2 = CandidateTypes.vector_begin(),
4833 Vec2End = CandidateTypes.vector_end();
4834 Vec2 != Vec2End; ++Vec2) {
4835 QualType LandR[2] = { *Vec1, *Vec2 };
4836 QualType Result;
4837 if (isComparison)
4838 Result = Context.BoolTy;
4839 else {
4840 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
4841 Result = *Vec1;
4842 else
4843 Result = *Vec2;
4844 }
4845
4846 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4847 }
4848
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004849 break;
4850
4851 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00004852 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004853 case OO_Caret:
4854 case OO_Pipe:
4855 case OO_LessLess:
4856 case OO_GreaterGreater:
4857 // C++ [over.built]p17:
4858 //
4859 // For every pair of promoted integral types L and R, there
4860 // exist candidate operator functions of the form
4861 //
4862 // LR operator%(L, R);
4863 // LR operator&(L, R);
4864 // LR operator^(L, R);
4865 // LR operator|(L, R);
4866 // L operator<<(L, R);
4867 // L operator>>(L, R);
4868 //
4869 // where LR is the result of the usual arithmetic conversions
4870 // between types L and R.
Mike Stump1eb44332009-09-09 15:08:12 +00004871 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004872 Left < LastPromotedIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004873 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004874 Right < LastPromotedIntegralType; ++Right) {
4875 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4876 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4877 ? LandR[0]
Eli Friedmana95d7572009-08-19 07:44:53 +00004878 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004879 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4880 }
4881 }
4882 break;
4883
4884 case OO_Equal:
4885 // C++ [over.built]p20:
4886 //
4887 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00004888 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004889 // empty, there exist candidate operator functions of the form
4890 //
4891 // VQ T& operator=(VQ T&, T);
Douglas Gregor19b7b152009-08-24 13:43:27 +00004892 for (BuiltinCandidateTypeSet::iterator
4893 Enum = CandidateTypes.enumeration_begin(),
4894 EnumEnd = CandidateTypes.enumeration_end();
4895 Enum != EnumEnd; ++Enum)
Mike Stump1eb44332009-09-09 15:08:12 +00004896 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004897 CandidateSet);
4898 for (BuiltinCandidateTypeSet::iterator
4899 MemPtr = CandidateTypes.member_pointer_begin(),
4900 MemPtrEnd = CandidateTypes.member_pointer_end();
4901 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump1eb44332009-09-09 15:08:12 +00004902 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004903 CandidateSet);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004904
4905 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004906
4907 case OO_PlusEqual:
4908 case OO_MinusEqual:
4909 // C++ [over.built]p19:
4910 //
4911 // For every pair (T, VQ), where T is any type and VQ is either
4912 // volatile or empty, there exist candidate operator functions
4913 // of the form
4914 //
4915 // T*VQ& operator=(T*VQ&, T*);
4916 //
4917 // C++ [over.built]p21:
4918 //
4919 // For every pair (T, VQ), where T is a cv-qualified or
4920 // cv-unqualified object type and VQ is either volatile or
4921 // empty, there exist candidate operator functions of the form
4922 //
4923 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4924 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4925 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4926 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4927 QualType ParamTypes[2];
4928 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4929
4930 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004931 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004932 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4933 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004934
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004935 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4936 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00004937 // volatile version
John McCall0953e762009-09-24 19:53:00 +00004938 ParamTypes[0]
4939 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004940 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4941 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00004942 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004943 }
4944 // Fall through.
4945
4946 case OO_StarEqual:
4947 case OO_SlashEqual:
4948 // C++ [over.built]p18:
4949 //
4950 // For every triple (L, VQ, R), where L is an arithmetic type,
4951 // VQ is either volatile or empty, and R is a promoted
4952 // arithmetic type, there exist candidate operator functions of
4953 // the form
4954 //
4955 // VQ L& operator=(VQ L&, R);
4956 // VQ L& operator*=(VQ L&, R);
4957 // VQ L& operator/=(VQ L&, R);
4958 // VQ L& operator+=(VQ L&, R);
4959 // VQ L& operator-=(VQ L&, R);
4960 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004961 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004962 Right < LastPromotedArithmeticType; ++Right) {
4963 QualType ParamTypes[2];
4964 ParamTypes[1] = ArithmeticTypes[Right];
4965
4966 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004967 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004968 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4969 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004970
4971 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004972 if (VisibleTypeConversionsQuals.hasVolatile()) {
4973 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4974 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4975 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4976 /*IsAssigmentOperator=*/Op == OO_Equal);
4977 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004978 }
4979 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004980
4981 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
4982 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4983 Vec1End = CandidateTypes.vector_end();
4984 Vec1 != Vec1End; ++Vec1)
4985 for (BuiltinCandidateTypeSet::iterator
4986 Vec2 = CandidateTypes.vector_begin(),
4987 Vec2End = CandidateTypes.vector_end();
4988 Vec2 != Vec2End; ++Vec2) {
4989 QualType ParamTypes[2];
4990 ParamTypes[1] = *Vec2;
4991 // Add this built-in operator as a candidate (VQ is empty).
4992 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
4993 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4994 /*IsAssigmentOperator=*/Op == OO_Equal);
4995
4996 // Add this built-in operator as a candidate (VQ is 'volatile').
4997 if (VisibleTypeConversionsQuals.hasVolatile()) {
4998 ParamTypes[0] = Context.getVolatileType(*Vec1);
4999 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5000 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5001 /*IsAssigmentOperator=*/Op == OO_Equal);
5002 }
5003 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005004 break;
5005
5006 case OO_PercentEqual:
5007 case OO_LessLessEqual:
5008 case OO_GreaterGreaterEqual:
5009 case OO_AmpEqual:
5010 case OO_CaretEqual:
5011 case OO_PipeEqual:
5012 // C++ [over.built]p22:
5013 //
5014 // For every triple (L, VQ, R), where L is an integral type, VQ
5015 // is either volatile or empty, and R is a promoted integral
5016 // type, there exist candidate operator functions of the form
5017 //
5018 // VQ L& operator%=(VQ L&, R);
5019 // VQ L& operator<<=(VQ L&, R);
5020 // VQ L& operator>>=(VQ L&, R);
5021 // VQ L& operator&=(VQ L&, R);
5022 // VQ L& operator^=(VQ L&, R);
5023 // VQ L& operator|=(VQ L&, R);
5024 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00005025 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005026 Right < LastPromotedIntegralType; ++Right) {
5027 QualType ParamTypes[2];
5028 ParamTypes[1] = ArithmeticTypes[Right];
5029
5030 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005031 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005032 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian035c46f2009-10-20 00:04:40 +00005033 if (VisibleTypeConversionsQuals.hasVolatile()) {
5034 // Add this built-in operator as a candidate (VQ is 'volatile').
5035 ParamTypes[0] = ArithmeticTypes[Left];
5036 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
5037 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5038 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5039 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005040 }
5041 }
5042 break;
5043
Douglas Gregor74253732008-11-19 15:42:04 +00005044 case OO_Exclaim: {
5045 // C++ [over.operator]p23:
5046 //
5047 // There also exist candidate operator functions of the form
5048 //
Mike Stump1eb44332009-09-09 15:08:12 +00005049 // bool operator!(bool);
Douglas Gregor74253732008-11-19 15:42:04 +00005050 // bool operator&&(bool, bool); [BELOW]
5051 // bool operator||(bool, bool); [BELOW]
5052 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005053 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5054 /*IsAssignmentOperator=*/false,
5055 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00005056 break;
5057 }
5058
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005059 case OO_AmpAmp:
5060 case OO_PipePipe: {
5061 // C++ [over.operator]p23:
5062 //
5063 // There also exist candidate operator functions of the form
5064 //
Douglas Gregor74253732008-11-19 15:42:04 +00005065 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005066 // bool operator&&(bool, bool);
5067 // bool operator||(bool, bool);
5068 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005069 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5070 /*IsAssignmentOperator=*/false,
5071 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005072 break;
5073 }
5074
5075 case OO_Subscript:
5076 // C++ [over.built]p13:
5077 //
5078 // For every cv-qualified or cv-unqualified object type T there
5079 // exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00005080 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005081 // T* operator+(T*, ptrdiff_t); [ABOVE]
5082 // T& operator[](T*, ptrdiff_t);
5083 // T* operator-(T*, ptrdiff_t); [ABOVE]
5084 // T* operator+(ptrdiff_t, T*); [ABOVE]
5085 // T& operator[](ptrdiff_t, T*);
5086 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
5087 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5088 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenek6217b802009-07-29 21:53:49 +00005089 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005090 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005091
5092 // T& operator[](T*, ptrdiff_t)
5093 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5094
5095 // T& operator[](ptrdiff_t, T*);
5096 ParamTypes[0] = ParamTypes[1];
5097 ParamTypes[1] = *Ptr;
5098 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregor26bcf672010-05-19 03:21:00 +00005099 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005100 break;
5101
5102 case OO_ArrowStar:
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005103 // C++ [over.built]p11:
5104 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5105 // C1 is the same type as C2 or is a derived class of C2, T is an object
5106 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5107 // there exist candidate operator functions of the form
5108 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5109 // where CV12 is the union of CV1 and CV2.
5110 {
5111 for (BuiltinCandidateTypeSet::iterator Ptr =
5112 CandidateTypes.pointer_begin();
5113 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5114 QualType C1Ty = (*Ptr);
5115 QualType C1;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00005116 QualifierCollector Q1;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005117 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00005118 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005119 if (!isa<RecordType>(C1))
5120 continue;
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005121 // heuristic to reduce number of builtin candidates in the set.
5122 // Add volatile/restrict version only if there are conversions to a
5123 // volatile/restrict type.
5124 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5125 continue;
5126 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5127 continue;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005128 }
5129 for (BuiltinCandidateTypeSet::iterator
5130 MemPtr = CandidateTypes.member_pointer_begin(),
5131 MemPtrEnd = CandidateTypes.member_pointer_end();
5132 MemPtr != MemPtrEnd; ++MemPtr) {
5133 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5134 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian43036972009-10-07 16:56:50 +00005135 C2 = C2.getUnqualifiedType();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005136 if (C1 != C2 && !IsDerivedFrom(C1, C2))
5137 break;
5138 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5139 // build CV12 T&
5140 QualType T = mptr->getPointeeType();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005141 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5142 T.isVolatileQualified())
5143 continue;
5144 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5145 T.isRestrictQualified())
5146 continue;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00005147 T = Q1.apply(T);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005148 QualType ResultTy = Context.getLValueReferenceType(T);
5149 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5150 }
5151 }
5152 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005153 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005154
5155 case OO_Conditional:
5156 // Note that we don't consider the first argument, since it has been
5157 // contextually converted to bool long ago. The candidates below are
5158 // therefore added as binary.
5159 //
5160 // C++ [over.built]p24:
5161 // For every type T, where T is a pointer or pointer-to-member type,
5162 // there exist candidate operator functions of the form
5163 //
5164 // T operator?(bool, T, T);
5165 //
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005166 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
5167 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
5168 QualType ParamTypes[2] = { *Ptr, *Ptr };
5169 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5170 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00005171 for (BuiltinCandidateTypeSet::iterator Ptr =
5172 CandidateTypes.member_pointer_begin(),
5173 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
5174 QualType ParamTypes[2] = { *Ptr, *Ptr };
5175 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5176 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005177 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005178 }
5179}
5180
Douglas Gregorfa047642009-02-04 00:32:51 +00005181/// \brief Add function candidates found via argument-dependent lookup
5182/// to the set of overloading candidates.
5183///
5184/// This routine performs argument-dependent name lookup based on the
5185/// given function name (which may also be an operator name) and adds
5186/// all of the overload candidates found by ADL to the overload
5187/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00005188void
Douglas Gregorfa047642009-02-04 00:32:51 +00005189Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00005190 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00005191 Expr **Args, unsigned NumArgs,
John McCalld5532b62009-11-23 01:53:49 +00005192 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005193 OverloadCandidateSet& CandidateSet,
5194 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00005195 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00005196
John McCalla113e722010-01-26 06:04:06 +00005197 // FIXME: This approach for uniquing ADL results (and removing
5198 // redundant candidates from the set) relies on pointer-equality,
5199 // which means we need to key off the canonical decl. However,
5200 // always going back to the canonical decl might not get us the
5201 // right set of default arguments. What default arguments are
5202 // we supposed to consider on ADL candidates, anyway?
5203
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005204 // FIXME: Pass in the explicit template arguments?
John McCall7edb5fd2010-01-26 07:16:45 +00005205 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00005206
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005207 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005208 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5209 CandEnd = CandidateSet.end();
5210 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00005211 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00005212 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00005213 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00005214 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00005215 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005216
5217 // For each of the ADL candidates we found, add it to the overload
5218 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00005219 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00005220 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00005221 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00005222 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005223 continue;
5224
John McCall9aa472c2010-03-19 07:35:19 +00005225 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00005226 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005227 } else
John McCall6e266892010-01-26 03:27:55 +00005228 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00005229 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00005230 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00005231 }
Douglas Gregorfa047642009-02-04 00:32:51 +00005232}
5233
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005234/// isBetterOverloadCandidate - Determines whether the first overload
5235/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00005236bool
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005237Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCall5769d612010-02-08 23:07:23 +00005238 const OverloadCandidate& Cand2,
5239 SourceLocation Loc) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005240 // Define viable functions to be better candidates than non-viable
5241 // functions.
5242 if (!Cand2.Viable)
5243 return Cand1.Viable;
5244 else if (!Cand1.Viable)
5245 return false;
5246
Douglas Gregor88a35142008-12-22 05:46:06 +00005247 // C++ [over.match.best]p1:
5248 //
5249 // -- if F is a static member function, ICS1(F) is defined such
5250 // that ICS1(F) is neither better nor worse than ICS1(G) for
5251 // any function G, and, symmetrically, ICS1(G) is neither
5252 // better nor worse than ICS1(F).
5253 unsigned StartArg = 0;
5254 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5255 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005256
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005257 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00005258 // A viable function F1 is defined to be a better function than another
5259 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005260 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005261 unsigned NumArgs = Cand1.Conversions.size();
5262 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5263 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005264 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005265 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
5266 Cand2.Conversions[ArgIdx])) {
5267 case ImplicitConversionSequence::Better:
5268 // Cand1 has a better conversion sequence.
5269 HasBetterConversion = true;
5270 break;
5271
5272 case ImplicitConversionSequence::Worse:
5273 // Cand1 can't be better than Cand2.
5274 return false;
5275
5276 case ImplicitConversionSequence::Indistinguishable:
5277 // Do nothing.
5278 break;
5279 }
5280 }
5281
Mike Stump1eb44332009-09-09 15:08:12 +00005282 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005283 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005284 if (HasBetterConversion)
5285 return true;
5286
Mike Stump1eb44332009-09-09 15:08:12 +00005287 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005288 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00005289 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005290 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5291 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005292
5293 // -- F1 and F2 are function template specializations, and the function
5294 // template for F1 is more specialized than the template for F2
5295 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005296 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00005297 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5298 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005299 if (FunctionTemplateDecl *BetterTemplate
5300 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5301 Cand2.Function->getPrimaryTemplate(),
John McCall5769d612010-02-08 23:07:23 +00005302 Loc,
Douglas Gregor5d7d3752009-09-14 23:02:14 +00005303 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5304 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005305 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005306
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005307 // -- the context is an initialization by user-defined conversion
5308 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5309 // from the return type of F1 to the destination type (i.e.,
5310 // the type of the entity being initialized) is a better
5311 // conversion sequence than the standard conversion sequence
5312 // from the return type of F2 to the destination type.
Mike Stump1eb44332009-09-09 15:08:12 +00005313 if (Cand1.Function && Cand2.Function &&
5314 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005315 isa<CXXConversionDecl>(Cand2.Function)) {
5316 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
5317 Cand2.FinalConversion)) {
5318 case ImplicitConversionSequence::Better:
5319 // Cand1 has a better conversion sequence.
5320 return true;
5321
5322 case ImplicitConversionSequence::Worse:
5323 // Cand1 can't be better than Cand2.
5324 return false;
5325
5326 case ImplicitConversionSequence::Indistinguishable:
5327 // Do nothing
5328 break;
5329 }
5330 }
5331
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005332 return false;
5333}
5334
Mike Stump1eb44332009-09-09 15:08:12 +00005335/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00005336/// within an overload candidate set.
5337///
5338/// \param CandidateSet the set of candidate functions.
5339///
5340/// \param Loc the location of the function name (or operator symbol) for
5341/// which overload resolution occurs.
5342///
Mike Stump1eb44332009-09-09 15:08:12 +00005343/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00005344/// function, Best points to the candidate function found.
5345///
5346/// \returns The result of overload resolution.
Douglas Gregor20093b42009-12-09 23:02:17 +00005347OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
5348 SourceLocation Loc,
5349 OverloadCandidateSet::iterator& Best) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005350 // Find the best viable function.
5351 Best = CandidateSet.end();
5352 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5353 Cand != CandidateSet.end(); ++Cand) {
5354 if (Cand->Viable) {
John McCall5769d612010-02-08 23:07:23 +00005355 if (Best == CandidateSet.end() ||
5356 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005357 Best = Cand;
5358 }
5359 }
5360
5361 // If we didn't find any viable functions, abort.
5362 if (Best == CandidateSet.end())
5363 return OR_No_Viable_Function;
5364
5365 // Make sure that this function is better than every other viable
5366 // function. If not, we have an ambiguity.
5367 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5368 Cand != CandidateSet.end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00005369 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005370 Cand != Best &&
John McCall5769d612010-02-08 23:07:23 +00005371 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005372 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005373 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005374 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005375 }
Mike Stump1eb44332009-09-09 15:08:12 +00005376
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005377 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005378 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00005379 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005380 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005381 return OR_Deleted;
5382
Douglas Gregore0762c92009-06-19 23:52:42 +00005383 // C++ [basic.def.odr]p2:
5384 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00005385 // when referred to from a potentially-evaluated expression. [Note: this
5386 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00005387 // (clause 13), user-defined conversions (12.3.2), allocation function for
5388 // placement new (5.3.4), as well as non-default initialization (8.5).
5389 if (Best->Function)
5390 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005391 return OR_Success;
5392}
5393
John McCall3c80f572010-01-12 02:15:36 +00005394namespace {
5395
5396enum OverloadCandidateKind {
5397 oc_function,
5398 oc_method,
5399 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00005400 oc_function_template,
5401 oc_method_template,
5402 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00005403 oc_implicit_default_constructor,
5404 oc_implicit_copy_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00005405 oc_implicit_copy_assignment
John McCall3c80f572010-01-12 02:15:36 +00005406};
5407
John McCall220ccbf2010-01-13 00:25:19 +00005408OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5409 FunctionDecl *Fn,
5410 std::string &Description) {
5411 bool isTemplate = false;
5412
5413 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5414 isTemplate = true;
5415 Description = S.getTemplateArgumentBindingsText(
5416 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5417 }
John McCallb1622a12010-01-06 09:43:14 +00005418
5419 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00005420 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00005421 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00005422
John McCall3c80f572010-01-12 02:15:36 +00005423 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5424 : oc_implicit_default_constructor;
John McCallb1622a12010-01-06 09:43:14 +00005425 }
5426
5427 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5428 // This actually gets spelled 'candidate function' for now, but
5429 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00005430 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00005431 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00005432
5433 assert(Meth->isCopyAssignment()
5434 && "implicit method is not copy assignment operator?");
John McCall3c80f572010-01-12 02:15:36 +00005435 return oc_implicit_copy_assignment;
5436 }
5437
John McCall220ccbf2010-01-13 00:25:19 +00005438 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00005439}
5440
5441} // end anonymous namespace
5442
5443// Notes the location of an overload candidate.
5444void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCall220ccbf2010-01-13 00:25:19 +00005445 std::string FnDesc;
5446 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5447 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5448 << (unsigned) K << FnDesc;
John McCallb1622a12010-01-06 09:43:14 +00005449}
5450
John McCall1d318332010-01-12 00:44:57 +00005451/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5452/// "lead" diagnostic; it will be given two arguments, the source and
5453/// target types of the conversion.
5454void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
5455 SourceLocation CaretLoc,
5456 const PartialDiagnostic &PDiag) {
5457 Diag(CaretLoc, PDiag)
5458 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
5459 for (AmbiguousConversionSequence::const_iterator
5460 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
5461 NoteOverloadCandidate(*I);
5462 }
John McCall81201622010-01-08 04:41:39 +00005463}
5464
John McCall1d318332010-01-12 00:44:57 +00005465namespace {
5466
John McCalladbb8f82010-01-13 09:16:55 +00005467void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5468 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5469 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00005470 assert(Cand->Function && "for now, candidate must be a function");
5471 FunctionDecl *Fn = Cand->Function;
5472
5473 // There's a conversion slot for the object argument if this is a
5474 // non-constructor method. Note that 'I' corresponds the
5475 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00005476 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00005477 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00005478 if (I == 0)
5479 isObjectArgument = true;
5480 else
5481 I--;
John McCall220ccbf2010-01-13 00:25:19 +00005482 }
5483
John McCall220ccbf2010-01-13 00:25:19 +00005484 std::string FnDesc;
5485 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5486
John McCalladbb8f82010-01-13 09:16:55 +00005487 Expr *FromExpr = Conv.Bad.FromExpr;
5488 QualType FromTy = Conv.Bad.getFromType();
5489 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00005490
John McCall5920dbb2010-02-02 02:42:52 +00005491 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00005492 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00005493 Expr *E = FromExpr->IgnoreParens();
5494 if (isa<UnaryOperator>(E))
5495 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00005496 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00005497
5498 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5499 << (unsigned) FnKind << FnDesc
5500 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5501 << ToTy << Name << I+1;
5502 return;
5503 }
5504
John McCall258b2032010-01-23 08:10:49 +00005505 // Do some hand-waving analysis to see if the non-viability is due
5506 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00005507 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5508 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5509 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5510 CToTy = RT->getPointeeType();
5511 else {
5512 // TODO: detect and diagnose the full richness of const mismatches.
5513 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5514 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5515 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5516 }
5517
5518 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5519 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5520 // It is dumb that we have to do this here.
5521 while (isa<ArrayType>(CFromTy))
5522 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5523 while (isa<ArrayType>(CToTy))
5524 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5525
5526 Qualifiers FromQs = CFromTy.getQualifiers();
5527 Qualifiers ToQs = CToTy.getQualifiers();
5528
5529 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5530 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5531 << (unsigned) FnKind << FnDesc
5532 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5533 << FromTy
5534 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5535 << (unsigned) isObjectArgument << I+1;
5536 return;
5537 }
5538
5539 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5540 assert(CVR && "unexpected qualifiers mismatch");
5541
5542 if (isObjectArgument) {
5543 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5544 << (unsigned) FnKind << FnDesc
5545 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5546 << FromTy << (CVR - 1);
5547 } else {
5548 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5549 << (unsigned) FnKind << FnDesc
5550 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5551 << FromTy << (CVR - 1) << I+1;
5552 }
5553 return;
5554 }
5555
John McCall258b2032010-01-23 08:10:49 +00005556 // Diagnose references or pointers to incomplete types differently,
5557 // since it's far from impossible that the incompleteness triggered
5558 // the failure.
5559 QualType TempFromTy = FromTy.getNonReferenceType();
5560 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5561 TempFromTy = PTy->getPointeeType();
5562 if (TempFromTy->isIncompleteType()) {
5563 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5564 << (unsigned) FnKind << FnDesc
5565 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5566 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5567 return;
5568 }
5569
Douglas Gregor85789812010-06-30 23:01:39 +00005570 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005571 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00005572 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
5573 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
5574 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5575 FromPtrTy->getPointeeType()) &&
5576 !FromPtrTy->getPointeeType()->isIncompleteType() &&
5577 !ToPtrTy->getPointeeType()->isIncompleteType() &&
5578 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
5579 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005580 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00005581 }
5582 } else if (const ObjCObjectPointerType *FromPtrTy
5583 = FromTy->getAs<ObjCObjectPointerType>()) {
5584 if (const ObjCObjectPointerType *ToPtrTy
5585 = ToTy->getAs<ObjCObjectPointerType>())
5586 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
5587 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
5588 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5589 FromPtrTy->getPointeeType()) &&
5590 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005591 BaseToDerivedConversion = 2;
5592 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
5593 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
5594 !FromTy->isIncompleteType() &&
5595 !ToRefTy->getPointeeType()->isIncompleteType() &&
5596 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
5597 BaseToDerivedConversion = 3;
5598 }
5599
5600 if (BaseToDerivedConversion) {
Douglas Gregor85789812010-06-30 23:01:39 +00005601 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005602 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00005603 << (unsigned) FnKind << FnDesc
5604 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005605 << (BaseToDerivedConversion - 1)
Douglas Gregor85789812010-06-30 23:01:39 +00005606 << FromTy << ToTy << I+1;
5607 return;
5608 }
5609
John McCall651f3ee2010-01-14 03:28:57 +00005610 // TODO: specialize more based on the kind of mismatch
John McCall220ccbf2010-01-13 00:25:19 +00005611 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5612 << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00005613 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalle81e15e2010-01-14 00:56:20 +00005614 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCalladbb8f82010-01-13 09:16:55 +00005615}
5616
5617void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5618 unsigned NumFormalArgs) {
5619 // TODO: treat calls to a missing default constructor as a special case
5620
5621 FunctionDecl *Fn = Cand->Function;
5622 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5623
5624 unsigned MinParams = Fn->getMinRequiredArguments();
5625
5626 // at least / at most / exactly
Douglas Gregora18592e2010-05-08 18:13:28 +00005627 // FIXME: variadic templates "at most" should account for parameter packs
John McCalladbb8f82010-01-13 09:16:55 +00005628 unsigned mode, modeCount;
5629 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00005630 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5631 (Cand->FailureKind == ovl_fail_bad_deduction &&
5632 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCalladbb8f82010-01-13 09:16:55 +00005633 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5634 mode = 0; // "at least"
5635 else
5636 mode = 2; // "exactly"
5637 modeCount = MinParams;
5638 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00005639 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5640 (Cand->FailureKind == ovl_fail_bad_deduction &&
5641 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00005642 if (MinParams != FnTy->getNumArgs())
5643 mode = 1; // "at most"
5644 else
5645 mode = 2; // "exactly"
5646 modeCount = FnTy->getNumArgs();
5647 }
5648
5649 std::string Description;
5650 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5651
5652 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregora18592e2010-05-08 18:13:28 +00005653 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5654 << modeCount << NumFormalArgs;
John McCall220ccbf2010-01-13 00:25:19 +00005655}
5656
John McCall342fec42010-02-01 18:53:26 +00005657/// Diagnose a failed template-argument deduction.
5658void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5659 Expr **Args, unsigned NumArgs) {
5660 FunctionDecl *Fn = Cand->Function; // pattern
5661
Douglas Gregora9333192010-05-08 17:41:32 +00005662 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00005663 NamedDecl *ParamD;
5664 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5665 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5666 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00005667 switch (Cand->DeductionFailure.Result) {
5668 case Sema::TDK_Success:
5669 llvm_unreachable("TDK_success while diagnosing bad deduction");
5670
5671 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00005672 assert(ParamD && "no parameter found for incomplete deduction result");
5673 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5674 << ParamD->getDeclName();
5675 return;
5676 }
5677
John McCall57e97782010-08-05 09:05:08 +00005678 case Sema::TDK_Underqualified: {
5679 assert(ParamD && "no parameter found for bad qualifiers deduction result");
5680 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
5681
5682 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
5683
5684 // Param will have been canonicalized, but it should just be a
5685 // qualified version of ParamD, so move the qualifiers to that.
5686 QualifierCollector Qs(S.Context);
5687 Qs.strip(Param);
5688 QualType NonCanonParam = Qs.apply(TParam->getTypeForDecl());
5689 assert(S.Context.hasSameType(Param, NonCanonParam));
5690
5691 // Arg has also been canonicalized, but there's nothing we can do
5692 // about that. It also doesn't matter as much, because it won't
5693 // have any template parameters in it (because deduction isn't
5694 // done on dependent types).
5695 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
5696
5697 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
5698 << ParamD->getDeclName() << Arg << NonCanonParam;
5699 return;
5700 }
5701
5702 case Sema::TDK_Inconsistent: {
Douglas Gregorf1a84452010-05-08 19:15:54 +00005703 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00005704 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00005705 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00005706 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00005707 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00005708 which = 1;
5709 else {
Douglas Gregora9333192010-05-08 17:41:32 +00005710 which = 2;
5711 }
5712
5713 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5714 << which << ParamD->getDeclName()
5715 << *Cand->DeductionFailure.getFirstArg()
5716 << *Cand->DeductionFailure.getSecondArg();
5717 return;
5718 }
Douglas Gregora18592e2010-05-08 18:13:28 +00005719
Douglas Gregorf1a84452010-05-08 19:15:54 +00005720 case Sema::TDK_InvalidExplicitArguments:
5721 assert(ParamD && "no parameter found for invalid explicit arguments");
5722 if (ParamD->getDeclName())
5723 S.Diag(Fn->getLocation(),
5724 diag::note_ovl_candidate_explicit_arg_mismatch_named)
5725 << ParamD->getDeclName();
5726 else {
5727 int index = 0;
5728 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5729 index = TTP->getIndex();
5730 else if (NonTypeTemplateParmDecl *NTTP
5731 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5732 index = NTTP->getIndex();
5733 else
5734 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
5735 S.Diag(Fn->getLocation(),
5736 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
5737 << (index + 1);
5738 }
5739 return;
5740
Douglas Gregora18592e2010-05-08 18:13:28 +00005741 case Sema::TDK_TooManyArguments:
5742 case Sema::TDK_TooFewArguments:
5743 DiagnoseArityMismatch(S, Cand, NumArgs);
5744 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00005745
5746 case Sema::TDK_InstantiationDepth:
5747 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
5748 return;
5749
5750 case Sema::TDK_SubstitutionFailure: {
5751 std::string ArgString;
5752 if (TemplateArgumentList *Args
5753 = Cand->DeductionFailure.getTemplateArgumentList())
5754 ArgString = S.getTemplateArgumentBindingsText(
5755 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
5756 *Args);
5757 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
5758 << ArgString;
5759 return;
5760 }
Douglas Gregora9333192010-05-08 17:41:32 +00005761
John McCall342fec42010-02-01 18:53:26 +00005762 // TODO: diagnose these individually, then kill off
5763 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00005764 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00005765 case Sema::TDK_FailedOverloadResolution:
5766 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
5767 return;
5768 }
5769}
5770
5771/// Generates a 'note' diagnostic for an overload candidate. We've
5772/// already generated a primary error at the call site.
5773///
5774/// It really does need to be a single diagnostic with its caret
5775/// pointed at the candidate declaration. Yes, this creates some
5776/// major challenges of technical writing. Yes, this makes pointing
5777/// out problems with specific arguments quite awkward. It's still
5778/// better than generating twenty screens of text for every failed
5779/// overload.
5780///
5781/// It would be great to be able to express per-candidate problems
5782/// more richly for those diagnostic clients that cared, but we'd
5783/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00005784void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
5785 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00005786 FunctionDecl *Fn = Cand->Function;
5787
John McCall81201622010-01-08 04:41:39 +00005788 // Note deleted candidates, but only if they're viable.
John McCall3c80f572010-01-12 02:15:36 +00005789 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCall220ccbf2010-01-13 00:25:19 +00005790 std::string FnDesc;
5791 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00005792
5793 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00005794 << FnKind << FnDesc << Fn->isDeleted();
John McCalla1d7d622010-01-08 00:58:21 +00005795 return;
John McCall81201622010-01-08 04:41:39 +00005796 }
5797
John McCall220ccbf2010-01-13 00:25:19 +00005798 // We don't really have anything else to say about viable candidates.
5799 if (Cand->Viable) {
5800 S.NoteOverloadCandidate(Fn);
5801 return;
5802 }
John McCall1d318332010-01-12 00:44:57 +00005803
John McCalladbb8f82010-01-13 09:16:55 +00005804 switch (Cand->FailureKind) {
5805 case ovl_fail_too_many_arguments:
5806 case ovl_fail_too_few_arguments:
5807 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00005808
John McCalladbb8f82010-01-13 09:16:55 +00005809 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00005810 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5811
John McCall717e8912010-01-23 05:17:32 +00005812 case ovl_fail_trivial_conversion:
5813 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00005814 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00005815 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00005816
John McCallb1bdc622010-02-25 01:37:24 +00005817 case ovl_fail_bad_conversion: {
5818 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5819 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00005820 if (Cand->Conversions[I].isBad())
5821 return DiagnoseBadConversion(S, Cand, I);
5822
5823 // FIXME: this currently happens when we're called from SemaInit
5824 // when user-conversion overload fails. Figure out how to handle
5825 // those conditions and diagnose them well.
5826 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00005827 }
John McCallb1bdc622010-02-25 01:37:24 +00005828 }
John McCalla1d7d622010-01-08 00:58:21 +00005829}
5830
5831void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5832 // Desugar the type of the surrogate down to a function type,
5833 // retaining as many typedefs as possible while still showing
5834 // the function type (and, therefore, its parameter types).
5835 QualType FnType = Cand->Surrogate->getConversionType();
5836 bool isLValueReference = false;
5837 bool isRValueReference = false;
5838 bool isPointer = false;
5839 if (const LValueReferenceType *FnTypeRef =
5840 FnType->getAs<LValueReferenceType>()) {
5841 FnType = FnTypeRef->getPointeeType();
5842 isLValueReference = true;
5843 } else if (const RValueReferenceType *FnTypeRef =
5844 FnType->getAs<RValueReferenceType>()) {
5845 FnType = FnTypeRef->getPointeeType();
5846 isRValueReference = true;
5847 }
5848 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5849 FnType = FnTypePtr->getPointeeType();
5850 isPointer = true;
5851 }
5852 // Desugar down to a function type.
5853 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5854 // Reconstruct the pointer/reference as appropriate.
5855 if (isPointer) FnType = S.Context.getPointerType(FnType);
5856 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5857 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5858
5859 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5860 << FnType;
5861}
5862
5863void NoteBuiltinOperatorCandidate(Sema &S,
5864 const char *Opc,
5865 SourceLocation OpLoc,
5866 OverloadCandidate *Cand) {
5867 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5868 std::string TypeStr("operator");
5869 TypeStr += Opc;
5870 TypeStr += "(";
5871 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5872 if (Cand->Conversions.size() == 1) {
5873 TypeStr += ")";
5874 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5875 } else {
5876 TypeStr += ", ";
5877 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5878 TypeStr += ")";
5879 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5880 }
5881}
5882
5883void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5884 OverloadCandidate *Cand) {
5885 unsigned NoOperands = Cand->Conversions.size();
5886 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5887 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00005888 if (ICS.isBad()) break; // all meaningless after first invalid
5889 if (!ICS.isAmbiguous()) continue;
5890
5891 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005892 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00005893 }
5894}
5895
John McCall1b77e732010-01-15 23:32:50 +00005896SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5897 if (Cand->Function)
5898 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00005899 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00005900 return Cand->Surrogate->getLocation();
5901 return SourceLocation();
5902}
5903
John McCallbf65c0b2010-01-12 00:48:53 +00005904struct CompareOverloadCandidatesForDisplay {
5905 Sema &S;
5906 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00005907
5908 bool operator()(const OverloadCandidate *L,
5909 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00005910 // Fast-path this check.
5911 if (L == R) return false;
5912
John McCall81201622010-01-08 04:41:39 +00005913 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00005914 if (L->Viable) {
5915 if (!R->Viable) return true;
5916
5917 // TODO: introduce a tri-valued comparison for overload
5918 // candidates. Would be more worthwhile if we had a sort
5919 // that could exploit it.
John McCall5769d612010-02-08 23:07:23 +00005920 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5921 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00005922 } else if (R->Viable)
5923 return false;
John McCall81201622010-01-08 04:41:39 +00005924
John McCall1b77e732010-01-15 23:32:50 +00005925 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00005926
John McCall1b77e732010-01-15 23:32:50 +00005927 // Criteria by which we can sort non-viable candidates:
5928 if (!L->Viable) {
5929 // 1. Arity mismatches come after other candidates.
5930 if (L->FailureKind == ovl_fail_too_many_arguments ||
5931 L->FailureKind == ovl_fail_too_few_arguments)
5932 return false;
5933 if (R->FailureKind == ovl_fail_too_many_arguments ||
5934 R->FailureKind == ovl_fail_too_few_arguments)
5935 return true;
John McCall81201622010-01-08 04:41:39 +00005936
John McCall717e8912010-01-23 05:17:32 +00005937 // 2. Bad conversions come first and are ordered by the number
5938 // of bad conversions and quality of good conversions.
5939 if (L->FailureKind == ovl_fail_bad_conversion) {
5940 if (R->FailureKind != ovl_fail_bad_conversion)
5941 return true;
5942
5943 // If there's any ordering between the defined conversions...
5944 // FIXME: this might not be transitive.
5945 assert(L->Conversions.size() == R->Conversions.size());
5946
5947 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00005948 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5949 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall717e8912010-01-23 05:17:32 +00005950 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5951 R->Conversions[I])) {
5952 case ImplicitConversionSequence::Better:
5953 leftBetter++;
5954 break;
5955
5956 case ImplicitConversionSequence::Worse:
5957 leftBetter--;
5958 break;
5959
5960 case ImplicitConversionSequence::Indistinguishable:
5961 break;
5962 }
5963 }
5964 if (leftBetter > 0) return true;
5965 if (leftBetter < 0) return false;
5966
5967 } else if (R->FailureKind == ovl_fail_bad_conversion)
5968 return false;
5969
John McCall1b77e732010-01-15 23:32:50 +00005970 // TODO: others?
5971 }
5972
5973 // Sort everything else by location.
5974 SourceLocation LLoc = GetLocationForCandidate(L);
5975 SourceLocation RLoc = GetLocationForCandidate(R);
5976
5977 // Put candidates without locations (e.g. builtins) at the end.
5978 if (LLoc.isInvalid()) return false;
5979 if (RLoc.isInvalid()) return true;
5980
5981 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00005982 }
5983};
5984
John McCall717e8912010-01-23 05:17:32 +00005985/// CompleteNonViableCandidate - Normally, overload resolution only
5986/// computes up to the first
5987void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5988 Expr **Args, unsigned NumArgs) {
5989 assert(!Cand->Viable);
5990
5991 // Don't do anything on failures other than bad conversion.
5992 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5993
5994 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00005995 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCall717e8912010-01-23 05:17:32 +00005996 unsigned ConvCount = Cand->Conversions.size();
5997 while (true) {
5998 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5999 ConvIdx++;
6000 if (Cand->Conversions[ConvIdx - 1].isBad())
6001 break;
6002 }
6003
6004 if (ConvIdx == ConvCount)
6005 return;
6006
John McCallb1bdc622010-02-25 01:37:24 +00006007 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6008 "remaining conversion is initialized?");
6009
Douglas Gregor23ef6c02010-04-16 17:45:54 +00006010 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00006011 // operation somehow.
6012 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00006013
6014 const FunctionProtoType* Proto;
6015 unsigned ArgIdx = ConvIdx;
6016
6017 if (Cand->IsSurrogate) {
6018 QualType ConvType
6019 = Cand->Surrogate->getConversionType().getNonReferenceType();
6020 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6021 ConvType = ConvPtrType->getPointeeType();
6022 Proto = ConvType->getAs<FunctionProtoType>();
6023 ArgIdx--;
6024 } else if (Cand->Function) {
6025 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6026 if (isa<CXXMethodDecl>(Cand->Function) &&
6027 !isa<CXXConstructorDecl>(Cand->Function))
6028 ArgIdx--;
6029 } else {
6030 // Builtin binary operator with a bad first conversion.
6031 assert(ConvCount <= 3);
6032 for (; ConvIdx != ConvCount; ++ConvIdx)
6033 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006034 = TryCopyInitialization(S, Args[ConvIdx],
6035 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6036 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00006037 /*InOverloadResolution*/ true);
John McCall717e8912010-01-23 05:17:32 +00006038 return;
6039 }
6040
6041 // Fill in the rest of the conversions.
6042 unsigned NumArgsInProto = Proto->getNumArgs();
6043 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6044 if (ArgIdx < NumArgsInProto)
6045 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006046 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6047 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00006048 /*InOverloadResolution=*/true);
John McCall717e8912010-01-23 05:17:32 +00006049 else
6050 Cand->Conversions[ConvIdx].setEllipsis();
6051 }
6052}
6053
John McCalla1d7d622010-01-08 00:58:21 +00006054} // end anonymous namespace
6055
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006056/// PrintOverloadCandidates - When overload resolution fails, prints
6057/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00006058/// set.
Mike Stump1eb44332009-09-09 15:08:12 +00006059void
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006060Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall81201622010-01-08 04:41:39 +00006061 OverloadCandidateDisplayKind OCD,
John McCallcbce6062010-01-12 07:18:19 +00006062 Expr **Args, unsigned NumArgs,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00006063 const char *Opc,
Fariborz Jahanian16a5eac2009-10-09 00:13:15 +00006064 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00006065 // Sort the candidates by viability and position. Sorting directly would
6066 // be prohibitive, so we make a set of pointers and sort those.
6067 llvm::SmallVector<OverloadCandidate*, 32> Cands;
6068 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
6069 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6070 LastCand = CandidateSet.end();
John McCall717e8912010-01-23 05:17:32 +00006071 Cand != LastCand; ++Cand) {
6072 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00006073 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00006074 else if (OCD == OCD_AllCandidates) {
6075 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006076 if (Cand->Function || Cand->IsSurrogate)
6077 Cands.push_back(Cand);
6078 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6079 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00006080 }
6081 }
6082
John McCallbf65c0b2010-01-12 00:48:53 +00006083 std::sort(Cands.begin(), Cands.end(),
6084 CompareOverloadCandidatesForDisplay(*this));
John McCall81201622010-01-08 04:41:39 +00006085
John McCall1d318332010-01-12 00:44:57 +00006086 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00006087
John McCall81201622010-01-08 04:41:39 +00006088 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006089 const Diagnostic::OverloadsShown ShowOverloads = Diags.getShowOverloads();
6090 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00006091 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6092 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00006093
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006094 // Set an arbitrary limit on the number of candidate functions we'll spam
6095 // the user with. FIXME: This limit should depend on details of the
6096 // candidate list.
6097 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6098 break;
6099 }
6100 ++CandsShown;
6101
John McCalla1d7d622010-01-08 00:58:21 +00006102 if (Cand->Function)
John McCall220ccbf2010-01-13 00:25:19 +00006103 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00006104 else if (Cand->IsSurrogate)
6105 NoteSurrogateCandidate(*this, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006106 else {
6107 assert(Cand->Viable &&
6108 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00006109 // Generally we only see ambiguities including viable builtin
6110 // operators if overload resolution got screwed up by an
6111 // ambiguous user-defined conversion.
6112 //
6113 // FIXME: It's quite possible for different conversions to see
6114 // different ambiguities, though.
6115 if (!ReportedAmbiguousConversions) {
6116 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
6117 ReportedAmbiguousConversions = true;
6118 }
John McCalla1d7d622010-01-08 00:58:21 +00006119
John McCall1d318332010-01-12 00:44:57 +00006120 // If this is a viable builtin, print it.
John McCalla1d7d622010-01-08 00:58:21 +00006121 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006122 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006123 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006124
6125 if (I != E)
Jeffrey Yasskin258de302010-06-11 06:58:43 +00006126 Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006127}
6128
John McCall9aa472c2010-03-19 07:35:19 +00006129static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCallc373d482010-01-27 01:50:18 +00006130 if (isa<UnresolvedLookupExpr>(E))
John McCall9aa472c2010-03-19 07:35:19 +00006131 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00006132
John McCall9aa472c2010-03-19 07:35:19 +00006133 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00006134}
6135
Douglas Gregor904eed32008-11-10 20:40:00 +00006136/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6137/// an overloaded function (C++ [over.over]), where @p From is an
6138/// expression with overloaded function type and @p ToType is the type
6139/// we're trying to resolve to. For example:
6140///
6141/// @code
6142/// int f(double);
6143/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00006144///
Douglas Gregor904eed32008-11-10 20:40:00 +00006145/// int (*pfd)(double) = f; // selects f(double)
6146/// @endcode
6147///
6148/// This routine returns the resulting FunctionDecl if it could be
6149/// resolved, and NULL otherwise. When @p Complain is true, this
6150/// routine will emit diagnostics if there is an error.
6151FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00006152Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall6bb80172010-03-30 21:47:33 +00006153 bool Complain,
6154 DeclAccessPair &FoundResult) {
Douglas Gregor904eed32008-11-10 20:40:00 +00006155 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00006156 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00006157 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00006158 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00006159 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00006160 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00006161 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00006162 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00006163 FunctionType = MemTypePtr->getPointeeType();
6164 IsMember = true;
6165 }
Douglas Gregor904eed32008-11-10 20:40:00 +00006166
Douglas Gregor904eed32008-11-10 20:40:00 +00006167 // C++ [over.over]p1:
6168 // [...] [Note: any redundant set of parentheses surrounding the
6169 // overloaded function name is ignored (5.1). ]
Douglas Gregor904eed32008-11-10 20:40:00 +00006170 // C++ [over.over]p1:
6171 // [...] The overloaded function name can be preceded by the &
6172 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00006173 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
6174 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6175 if (OvlExpr->hasExplicitTemplateArgs()) {
6176 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6177 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregor904eed32008-11-10 20:40:00 +00006178 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006179
6180 // We expect a pointer or reference to function, or a function pointer.
6181 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6182 if (!FunctionType->isFunctionType()) {
6183 if (Complain)
6184 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6185 << OvlExpr->getName() << ToType;
6186
6187 return 0;
6188 }
6189
6190 assert(From->getType() == Context.OverloadTy);
Douglas Gregor904eed32008-11-10 20:40:00 +00006191
Douglas Gregor904eed32008-11-10 20:40:00 +00006192 // Look through all of the overloaded functions, searching for one
6193 // whose type matches exactly.
John McCall9aa472c2010-03-19 07:35:19 +00006194 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb7a09262010-04-01 18:32:35 +00006195 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
6196
Douglas Gregor00aeb522009-07-08 23:33:52 +00006197 bool FoundNonTemplateFunction = false;
John McCall7bb12da2010-02-02 06:20:04 +00006198 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6199 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00006200 // Look through any using declarations to find the underlying function.
6201 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6202
Douglas Gregor904eed32008-11-10 20:40:00 +00006203 // C++ [over.over]p3:
6204 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00006205 // targets of type "pointer-to-function" or "reference-to-function."
6206 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00006207 // type "pointer-to-member-function."
6208 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00006209
Mike Stump1eb44332009-09-09 15:08:12 +00006210 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthbd647292009-12-29 06:17:27 +00006211 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006212 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00006213 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00006214 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00006215 // static when converting to member pointer.
6216 if (Method->isStatic() == IsMember)
6217 continue;
6218 } else if (IsMember)
6219 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00006220
Douglas Gregor00aeb522009-07-08 23:33:52 +00006221 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00006222 // If the name is a function template, template argument deduction is
6223 // done (14.8.2.2), and if the argument deduction succeeds, the
6224 // resulting template argument list is used to generate a single
6225 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00006226 // overloaded functions considered.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00006227 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor83314aa2009-07-08 20:55:45 +00006228 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00006229 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor83314aa2009-07-08 20:55:45 +00006230 if (TemplateDeductionResult Result
John McCall7bb12da2010-02-02 06:20:04 +00006231 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00006232 FunctionType, Specialization, Info)) {
6233 // FIXME: make a note of the failed deduction for diagnostics.
6234 (void)Result;
6235 } else {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00006236 // FIXME: If the match isn't exact, shouldn't we just drop this as
6237 // a candidate? Find a testcase before changing the code.
Mike Stump1eb44332009-09-09 15:08:12 +00006238 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00006239 == Context.getCanonicalType(Specialization->getType()));
John McCall9aa472c2010-03-19 07:35:19 +00006240 Matches.push_back(std::make_pair(I.getPair(),
6241 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor83314aa2009-07-08 20:55:45 +00006242 }
John McCallba135432009-11-21 08:51:07 +00006243
6244 continue;
Douglas Gregor83314aa2009-07-08 20:55:45 +00006245 }
Mike Stump1eb44332009-09-09 15:08:12 +00006246
Chandler Carruthbd647292009-12-29 06:17:27 +00006247 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00006248 // Skip non-static functions when converting to pointer, and static
6249 // when converting to member pointer.
6250 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00006251 continue;
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006252
6253 // If we have explicit template arguments, skip non-templates.
John McCall7bb12da2010-02-02 06:20:04 +00006254 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006255 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00006256 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00006257 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00006258
Chandler Carruthbd647292009-12-29 06:17:27 +00006259 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00006260 QualType ResultTy;
6261 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6262 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6263 ResultTy)) {
John McCall9aa472c2010-03-19 07:35:19 +00006264 Matches.push_back(std::make_pair(I.getPair(),
6265 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00006266 FoundNonTemplateFunction = true;
6267 }
Mike Stump1eb44332009-09-09 15:08:12 +00006268 }
Douglas Gregor904eed32008-11-10 20:40:00 +00006269 }
6270
Douglas Gregor00aeb522009-07-08 23:33:52 +00006271 // If there were 0 or 1 matches, we're done.
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006272 if (Matches.empty()) {
6273 if (Complain) {
6274 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6275 << OvlExpr->getName() << FunctionType;
6276 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6277 E = OvlExpr->decls_end();
6278 I != E; ++I)
6279 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6280 NoteOverloadCandidate(F);
6281 }
6282
Douglas Gregor00aeb522009-07-08 23:33:52 +00006283 return 0;
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006284 } else if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00006285 FunctionDecl *Result = Matches[0].second;
John McCall6bb80172010-03-30 21:47:33 +00006286 FoundResult = Matches[0].first;
Sebastian Redl07ab2022009-10-17 21:12:09 +00006287 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCallc373d482010-01-27 01:50:18 +00006288 if (Complain)
John McCall6bb80172010-03-30 21:47:33 +00006289 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redl07ab2022009-10-17 21:12:09 +00006290 return Result;
6291 }
Douglas Gregor00aeb522009-07-08 23:33:52 +00006292
6293 // C++ [over.over]p4:
6294 // If more than one function is selected, [...]
Douglas Gregor312a2022009-09-26 03:56:17 +00006295 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006296 // [...] and any given function template specialization F1 is
6297 // eliminated if the set contains a second function template
6298 // specialization whose function template is more specialized
6299 // than the function template of F1 according to the partial
6300 // ordering rules of 14.5.5.2.
6301
6302 // The algorithm specified above is quadratic. We instead use a
6303 // two-pass algorithm (similar to the one used to identify the
6304 // best viable function in an overload set) that identifies the
6305 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00006306
6307 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6308 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6309 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCallc373d482010-01-27 01:50:18 +00006310
6311 UnresolvedSetIterator Result =
John McCall9aa472c2010-03-19 07:35:19 +00006312 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redl07ab2022009-10-17 21:12:09 +00006313 TPOC_Other, From->getLocStart(),
6314 PDiag(),
6315 PDiag(diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00006316 << Matches[0].second->getDeclName(),
John McCall220ccbf2010-01-13 00:25:19 +00006317 PDiag(diag::note_ovl_candidate)
6318 << (unsigned) oc_function_template);
John McCall9aa472c2010-03-19 07:35:19 +00006319 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCallc373d482010-01-27 01:50:18 +00006320 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall6bb80172010-03-30 21:47:33 +00006321 FoundResult = Matches[Result - MatchesCopy.begin()].first;
John McCallb697e082010-05-06 18:15:07 +00006322 if (Complain) {
John McCall6bb80172010-03-30 21:47:33 +00006323 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCallb697e082010-05-06 18:15:07 +00006324 DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc());
6325 }
John McCallc373d482010-01-27 01:50:18 +00006326 return cast<FunctionDecl>(*Result);
Douglas Gregor00aeb522009-07-08 23:33:52 +00006327 }
Mike Stump1eb44332009-09-09 15:08:12 +00006328
Douglas Gregor312a2022009-09-26 03:56:17 +00006329 // [...] any function template specializations in the set are
6330 // eliminated if the set also contains a non-template function, [...]
John McCallc373d482010-01-27 01:50:18 +00006331 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCall9aa472c2010-03-19 07:35:19 +00006332 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCallc373d482010-01-27 01:50:18 +00006333 ++I;
6334 else {
John McCall9aa472c2010-03-19 07:35:19 +00006335 Matches[I] = Matches[--N];
6336 Matches.set_size(N);
John McCallc373d482010-01-27 01:50:18 +00006337 }
6338 }
Douglas Gregor312a2022009-09-26 03:56:17 +00006339
Mike Stump1eb44332009-09-09 15:08:12 +00006340 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00006341 // selected function.
John McCallc373d482010-01-27 01:50:18 +00006342 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00006343 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall6bb80172010-03-30 21:47:33 +00006344 FoundResult = Matches[0].first;
John McCallb697e082010-05-06 18:15:07 +00006345 if (Complain) {
John McCall9aa472c2010-03-19 07:35:19 +00006346 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
John McCallb697e082010-05-06 18:15:07 +00006347 DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc());
6348 }
John McCall9aa472c2010-03-19 07:35:19 +00006349 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redl07ab2022009-10-17 21:12:09 +00006350 }
Mike Stump1eb44332009-09-09 15:08:12 +00006351
Douglas Gregor00aeb522009-07-08 23:33:52 +00006352 // FIXME: We should probably return the same thing that BestViableFunction
6353 // returns (even if we issue the diagnostics here).
6354 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00006355 << Matches[0].second->getDeclName();
6356 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6357 NoteOverloadCandidate(Matches[I].second);
Douglas Gregor904eed32008-11-10 20:40:00 +00006358 return 0;
6359}
6360
Douglas Gregor4b52e252009-12-21 23:17:24 +00006361/// \brief Given an expression that refers to an overloaded function, try to
6362/// resolve that overloaded function expression down to a single function.
6363///
6364/// This routine can only resolve template-ids that refer to a single function
6365/// template, where that template-id refers to a single template whose template
6366/// arguments are either provided by the template-id or have defaults,
6367/// as described in C++0x [temp.arg.explicit]p3.
6368FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6369 // C++ [over.over]p1:
6370 // [...] [Note: any redundant set of parentheses surrounding the
6371 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00006372 // C++ [over.over]p1:
6373 // [...] The overloaded function name can be preceded by the &
6374 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00006375
6376 if (From->getType() != Context.OverloadTy)
6377 return 0;
6378
6379 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor4b52e252009-12-21 23:17:24 +00006380
6381 // If we didn't actually find any template-ids, we're done.
John McCall7bb12da2010-02-02 06:20:04 +00006382 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00006383 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00006384
6385 TemplateArgumentListInfo ExplicitTemplateArgs;
6386 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor4b52e252009-12-21 23:17:24 +00006387
6388 // Look through all of the overloaded functions, searching for one
6389 // whose type matches exactly.
6390 FunctionDecl *Matched = 0;
John McCall7bb12da2010-02-02 06:20:04 +00006391 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6392 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00006393 // C++0x [temp.arg.explicit]p3:
6394 // [...] In contexts where deduction is done and fails, or in contexts
6395 // where deduction is not done, if a template argument list is
6396 // specified and it, along with any default template arguments,
6397 // identifies a single function template specialization, then the
6398 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00006399 FunctionTemplateDecl *FunctionTemplate
6400 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor4b52e252009-12-21 23:17:24 +00006401
6402 // C++ [over.over]p2:
6403 // If the name is a function template, template argument deduction is
6404 // done (14.8.2.2), and if the argument deduction succeeds, the
6405 // resulting template argument list is used to generate a single
6406 // function template specialization, which is added to the set of
6407 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00006408 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00006409 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00006410 if (TemplateDeductionResult Result
6411 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6412 Specialization, Info)) {
6413 // FIXME: make a note of the failed deduction for diagnostics.
6414 (void)Result;
6415 continue;
6416 }
6417
6418 // Multiple matches; we can't resolve to a single declaration.
6419 if (Matched)
6420 return 0;
6421
6422 Matched = Specialization;
6423 }
6424
6425 return Matched;
6426}
6427
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006428/// \brief Add a single candidate to the overload set.
6429static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00006430 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00006431 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006432 Expr **Args, unsigned NumArgs,
6433 OverloadCandidateSet &CandidateSet,
6434 bool PartialOverloading) {
John McCall9aa472c2010-03-19 07:35:19 +00006435 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00006436 if (isa<UsingShadowDecl>(Callee))
6437 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6438
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006439 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00006440 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCall9aa472c2010-03-19 07:35:19 +00006441 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00006442 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006443 return;
John McCallba135432009-11-21 08:51:07 +00006444 }
6445
6446 if (FunctionTemplateDecl *FuncTemplate
6447 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00006448 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6449 ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00006450 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00006451 return;
6452 }
6453
6454 assert(false && "unhandled case in overloaded call candidate");
6455
6456 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006457}
6458
6459/// \brief Add the overload candidates named by callee and/or found by argument
6460/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00006461void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006462 Expr **Args, unsigned NumArgs,
6463 OverloadCandidateSet &CandidateSet,
6464 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00006465
6466#ifndef NDEBUG
6467 // Verify that ArgumentDependentLookup is consistent with the rules
6468 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006469 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006470 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6471 // and let Y be the lookup set produced by argument dependent
6472 // lookup (defined as follows). If X contains
6473 //
6474 // -- a declaration of a class member, or
6475 //
6476 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00006477 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006478 //
6479 // -- a declaration that is neither a function or a function
6480 // template
6481 //
6482 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00006483
John McCall3b4294e2009-12-16 12:17:52 +00006484 if (ULE->requiresADL()) {
6485 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6486 E = ULE->decls_end(); I != E; ++I) {
6487 assert(!(*I)->getDeclContext()->isRecord());
6488 assert(isa<UsingShadowDecl>(*I) ||
6489 !(*I)->getDeclContext()->isFunctionOrMethod());
6490 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00006491 }
6492 }
6493#endif
6494
John McCall3b4294e2009-12-16 12:17:52 +00006495 // It would be nice to avoid this copy.
6496 TemplateArgumentListInfo TABuffer;
6497 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6498 if (ULE->hasExplicitTemplateArgs()) {
6499 ULE->copyTemplateArgumentsInto(TABuffer);
6500 ExplicitTemplateArgs = &TABuffer;
6501 }
6502
6503 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6504 E = ULE->decls_end(); I != E; ++I)
John McCall9aa472c2010-03-19 07:35:19 +00006505 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00006506 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006507 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00006508
John McCall3b4294e2009-12-16 12:17:52 +00006509 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00006510 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6511 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006512 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006513 CandidateSet,
6514 PartialOverloading);
6515}
John McCall578b69b2009-12-16 08:11:27 +00006516
6517/// Attempts to recover from a call where no functions were found.
6518///
6519/// Returns true if new candidates were found.
John McCall3b4294e2009-12-16 12:17:52 +00006520static Sema::OwningExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006521BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00006522 UnresolvedLookupExpr *ULE,
6523 SourceLocation LParenLoc,
6524 Expr **Args, unsigned NumArgs,
6525 SourceLocation *CommaLocs,
6526 SourceLocation RParenLoc) {
John McCall578b69b2009-12-16 08:11:27 +00006527
6528 CXXScopeSpec SS;
6529 if (ULE->getQualifier()) {
6530 SS.setScopeRep(ULE->getQualifier());
6531 SS.setRange(ULE->getQualifierRange());
6532 }
6533
John McCall3b4294e2009-12-16 12:17:52 +00006534 TemplateArgumentListInfo TABuffer;
6535 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6536 if (ULE->hasExplicitTemplateArgs()) {
6537 ULE->copyTemplateArgumentsInto(TABuffer);
6538 ExplicitTemplateArgs = &TABuffer;
6539 }
6540
John McCall578b69b2009-12-16 08:11:27 +00006541 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6542 Sema::LookupOrdinaryName);
Douglas Gregor91f7ac72010-05-18 16:14:23 +00006543 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
Douglas Gregorff331c12010-07-25 18:17:45 +00006544 return SemaRef.ExprError();
John McCall578b69b2009-12-16 08:11:27 +00006545
John McCall3b4294e2009-12-16 12:17:52 +00006546 assert(!R.empty() && "lookup results empty despite recovery");
6547
6548 // Build an implicit member call if appropriate. Just drop the
6549 // casts and such from the call, we don't really care.
6550 Sema::OwningExprResult NewFn = SemaRef.ExprError();
6551 if ((*R.begin())->isCXXClassMember())
6552 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6553 else if (ExplicitTemplateArgs)
6554 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6555 else
6556 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6557
6558 if (NewFn.isInvalid())
Douglas Gregorff331c12010-07-25 18:17:45 +00006559 return SemaRef.ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00006560
6561 // This shouldn't cause an infinite loop because we're giving it
6562 // an expression with non-empty lookup results, which should never
6563 // end up here.
6564 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
6565 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
6566 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00006567}
Douglas Gregord7a95972010-06-08 17:35:15 +00006568
Douglas Gregorf6b89692008-11-26 05:54:23 +00006569/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00006570/// (which eventually refers to the declaration Func) and the call
6571/// arguments Args/NumArgs, attempt to resolve the function call down
6572/// to a specific function. If overload resolution succeeds, returns
6573/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00006574/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00006575/// arguments and Fn, and returns NULL.
John McCall3b4294e2009-12-16 12:17:52 +00006576Sema::OwningExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006577Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00006578 SourceLocation LParenLoc,
6579 Expr **Args, unsigned NumArgs,
6580 SourceLocation *CommaLocs,
6581 SourceLocation RParenLoc) {
6582#ifndef NDEBUG
6583 if (ULE->requiresADL()) {
6584 // To do ADL, we must have found an unqualified name.
6585 assert(!ULE->getQualifier() && "qualified name with ADL");
6586
6587 // We don't perform ADL for implicit declarations of builtins.
6588 // Verify that this was correctly set up.
6589 FunctionDecl *F;
6590 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6591 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6592 F->getBuiltinID() && F->isImplicit())
6593 assert(0 && "performing ADL for builtin");
6594
6595 // We don't perform ADL in C.
6596 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6597 }
6598#endif
6599
John McCall5769d612010-02-08 23:07:23 +00006600 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00006601
John McCall3b4294e2009-12-16 12:17:52 +00006602 // Add the functions denoted by the callee to the set of candidate
6603 // functions, including those from argument-dependent lookup.
6604 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00006605
6606 // If we found nothing, try to recover.
6607 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6608 // bailout out if it fails.
John McCall3b4294e2009-12-16 12:17:52 +00006609 if (CandidateSet.empty())
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006610 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00006611 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00006612
Douglas Gregorf6b89692008-11-26 05:54:23 +00006613 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006614 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00006615 case OR_Success: {
6616 FunctionDecl *FDecl = Best->Function;
John McCall9aa472c2010-03-19 07:35:19 +00006617 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00006618 DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00006619 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall3b4294e2009-12-16 12:17:52 +00006620 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6621 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00006622
6623 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00006624 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00006625 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00006626 << ULE->getName() << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006627 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00006628 break;
6629
6630 case OR_Ambiguous:
6631 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00006632 << ULE->getName() << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006633 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00006634 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006635
6636 case OR_Deleted:
6637 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6638 << Best->Function->isDeleted()
John McCall3b4294e2009-12-16 12:17:52 +00006639 << ULE->getName()
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006640 << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006641 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006642 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00006643 }
6644
Douglas Gregorff331c12010-07-25 18:17:45 +00006645 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00006646 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00006647}
6648
John McCall6e266892010-01-26 03:27:55 +00006649static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00006650 return Functions.size() > 1 ||
6651 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6652}
6653
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006654/// \brief Create a unary operation that may resolve to an overloaded
6655/// operator.
6656///
6657/// \param OpLoc The location of the operator itself (e.g., '*').
6658///
6659/// \param OpcIn The UnaryOperator::Opcode that describes this
6660/// operator.
6661///
6662/// \param Functions The set of non-member functions that will be
6663/// considered by overload resolution. The caller needs to build this
6664/// set based on the context using, e.g.,
6665/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6666/// set should not contain any member functions; those will be added
6667/// by CreateOverloadedUnaryOp().
6668///
6669/// \param input The input argument.
John McCall6e266892010-01-26 03:27:55 +00006670Sema::OwningExprResult
6671Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6672 const UnresolvedSetImpl &Fns,
6673 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006674 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
6675 Expr *Input = (Expr *)input.get();
6676
6677 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6678 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6679 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00006680 // TODO: provide better source location info.
6681 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006682
6683 Expr *Args[2] = { Input, 0 };
6684 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00006685
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006686 // For post-increment and post-decrement, add the implicit '0' as
6687 // the second argument, so that we know this is a post-increment or
6688 // post-decrement.
6689 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
6690 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump1eb44332009-09-09 15:08:12 +00006691 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006692 SourceLocation());
6693 NumArgs = 2;
6694 }
6695
6696 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00006697 if (Fns.empty())
6698 return Owned(new (Context) UnaryOperator(input.takeAs<Expr>(),
6699 Opc,
6700 Context.DependentTy,
6701 OpLoc));
6702
John McCallc373d482010-01-27 01:50:18 +00006703 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00006704 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00006705 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00006706 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00006707 /*ADL*/ true, IsOverloaded(Fns),
6708 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006709 input.release();
6710 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6711 &Args[0], NumArgs,
6712 Context.DependentTy,
6713 OpLoc));
6714 }
6715
6716 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00006717 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006718
6719 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00006720 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006721
6722 // Add operator candidates that are member functions.
6723 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6724
John McCall6e266892010-01-26 03:27:55 +00006725 // Add candidates from ADL.
6726 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregordc81c882010-02-05 05:15:43 +00006727 Args, NumArgs,
John McCall6e266892010-01-26 03:27:55 +00006728 /*ExplicitTemplateArgs*/ 0,
6729 CandidateSet);
6730
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006731 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00006732 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006733
6734 // Perform overload resolution.
6735 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006736 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006737 case OR_Success: {
6738 // We found a built-in operator or an overloaded operator.
6739 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00006740
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006741 if (FnDecl) {
6742 // We matched an overloaded operator. Build a call to that
6743 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00006744
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006745 // Convert the arguments.
6746 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00006747 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00006748
John McCall6bb80172010-03-30 21:47:33 +00006749 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6750 Best->FoundDecl, Method))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006751 return ExprError();
6752 } else {
6753 // Convert the arguments.
Douglas Gregore1a5c172009-12-23 17:40:29 +00006754 OwningExprResult InputInit
6755 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregorbaecfed2009-12-23 00:02:00 +00006756 FnDecl->getParamDecl(0)),
Douglas Gregore1a5c172009-12-23 17:40:29 +00006757 SourceLocation(),
6758 move(input));
6759 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006760 return ExprError();
Douglas Gregorbaecfed2009-12-23 00:02:00 +00006761
Douglas Gregore1a5c172009-12-23 17:40:29 +00006762 input = move(InputInit);
Douglas Gregorbaecfed2009-12-23 00:02:00 +00006763 Input = (Expr *)input.get();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006764 }
6765
John McCallb697e082010-05-06 18:15:07 +00006766 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6767
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006768 // Determine the result type
Douglas Gregor5291c3c2010-07-13 08:18:22 +00006769 QualType ResultTy = FnDecl->getCallResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006770
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006771 // Build the actual expression node.
6772 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6773 SourceLocation());
6774 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00006775
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006776 input.release();
Eli Friedman4c3b8962009-11-18 03:58:17 +00006777 Args[0] = Input;
Anders Carlsson26a2a072009-10-13 21:19:37 +00006778 ExprOwningPtr<CallExpr> TheCall(this,
6779 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman4c3b8962009-11-18 03:58:17 +00006780 Args, NumArgs, ResultTy, OpLoc));
John McCallb697e082010-05-06 18:15:07 +00006781
Anders Carlsson26a2a072009-10-13 21:19:37 +00006782 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6783 FnDecl))
6784 return ExprError();
6785
6786 return MaybeBindToTemporary(TheCall.release());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006787 } else {
6788 // We matched a built-in operator. Convert the arguments, then
6789 // break out so that we will build the appropriate built-in
6790 // operator node.
6791 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00006792 Best->Conversions[0], AA_Passing))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006793 return ExprError();
6794
6795 break;
6796 }
6797 }
6798
6799 case OR_No_Viable_Function:
6800 // No viable function; fall through to handling this as a
6801 // built-in operator, which will produce an error message for us.
6802 break;
6803
6804 case OR_Ambiguous:
6805 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6806 << UnaryOperator::getOpcodeStr(Opc)
6807 << Input->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006808 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00006809 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006810 return ExprError();
6811
6812 case OR_Deleted:
6813 Diag(OpLoc, diag::err_ovl_deleted_oper)
6814 << Best->Function->isDeleted()
6815 << UnaryOperator::getOpcodeStr(Opc)
6816 << Input->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006817 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006818 return ExprError();
6819 }
6820
6821 // Either we found no viable overloaded operator or we matched a
6822 // built-in operator. In either case, fall through to trying to
6823 // build a built-in operation.
6824 input.release();
6825 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
6826}
6827
Douglas Gregor063daf62009-03-13 18:40:31 +00006828/// \brief Create a binary operation that may resolve to an overloaded
6829/// operator.
6830///
6831/// \param OpLoc The location of the operator itself (e.g., '+').
6832///
6833/// \param OpcIn The BinaryOperator::Opcode that describes this
6834/// operator.
6835///
6836/// \param Functions The set of non-member functions that will be
6837/// considered by overload resolution. The caller needs to build this
6838/// set based on the context using, e.g.,
6839/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6840/// set should not contain any member functions; those will be added
6841/// by CreateOverloadedBinOp().
6842///
6843/// \param LHS Left-hand argument.
6844/// \param RHS Right-hand argument.
Mike Stump1eb44332009-09-09 15:08:12 +00006845Sema::OwningExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00006846Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006847 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00006848 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00006849 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00006850 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006851 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00006852
6853 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6854 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6855 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6856
6857 // If either side is type-dependent, create an appropriate dependent
6858 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006859 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00006860 if (Fns.empty()) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006861 // If there are no functions to store, just build a dependent
6862 // BinaryOperator or CompoundAssignment.
6863 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
6864 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6865 Context.DependentTy, OpLoc));
6866
6867 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6868 Context.DependentTy,
6869 Context.DependentTy,
6870 Context.DependentTy,
6871 OpLoc));
6872 }
John McCall6e266892010-01-26 03:27:55 +00006873
6874 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00006875 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00006876 // TODO: provide better source location info in DNLoc component.
6877 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +00006878 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00006879 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00006880 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00006881 /*ADL*/ true, IsOverloaded(Fns),
6882 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00006883 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00006884 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00006885 Context.DependentTy,
6886 OpLoc));
6887 }
6888
6889 // If this is the .* operator, which is not overloadable, just
6890 // create a built-in binary operator.
6891 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006892 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00006893
Sebastian Redl275c2b42009-11-18 23:10:33 +00006894 // If this is the assignment operator, we only perform overload resolution
6895 // if the left-hand side is a class or enumeration type. This is actually
6896 // a hack. The standard requires that we do overload resolution between the
6897 // various built-in candidates, but as DR507 points out, this can lead to
6898 // problems. So we do it this way, which pretty much follows what GCC does.
6899 // Note that we go the traditional code path for compound assignment forms.
6900 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006901 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00006902
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006903 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00006904 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00006905
6906 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00006907 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00006908
6909 // Add operator candidates that are member functions.
6910 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6911
John McCall6e266892010-01-26 03:27:55 +00006912 // Add candidates from ADL.
6913 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6914 Args, 2,
6915 /*ExplicitTemplateArgs*/ 0,
6916 CandidateSet);
6917
Douglas Gregor063daf62009-03-13 18:40:31 +00006918 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00006919 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00006920
6921 // Perform overload resolution.
6922 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006923 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00006924 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00006925 // We found a built-in operator or an overloaded operator.
6926 FunctionDecl *FnDecl = Best->Function;
6927
6928 if (FnDecl) {
6929 // We matched an overloaded operator. Build a call to that
6930 // operator.
6931
6932 // Convert the arguments.
6933 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00006934 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +00006935 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00006936
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006937 OwningExprResult Arg1
6938 = PerformCopyInitialization(
6939 InitializedEntity::InitializeParameter(
6940 FnDecl->getParamDecl(0)),
6941 SourceLocation(),
6942 Owned(Args[1]));
6943 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00006944 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006945
Douglas Gregor5fccd362010-03-03 23:55:11 +00006946 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00006947 Best->FoundDecl, Method))
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006948 return ExprError();
6949
6950 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00006951 } else {
6952 // Convert the arguments.
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006953 OwningExprResult Arg0
6954 = PerformCopyInitialization(
6955 InitializedEntity::InitializeParameter(
6956 FnDecl->getParamDecl(0)),
6957 SourceLocation(),
6958 Owned(Args[0]));
6959 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00006960 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006961
6962 OwningExprResult Arg1
6963 = PerformCopyInitialization(
6964 InitializedEntity::InitializeParameter(
6965 FnDecl->getParamDecl(1)),
6966 SourceLocation(),
6967 Owned(Args[1]));
6968 if (Arg1.isInvalid())
6969 return ExprError();
6970 Args[0] = LHS = Arg0.takeAs<Expr>();
6971 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00006972 }
6973
John McCallb697e082010-05-06 18:15:07 +00006974 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6975
Douglas Gregor063daf62009-03-13 18:40:31 +00006976 // Determine the result type
6977 QualType ResultTy
Douglas Gregor5291c3c2010-07-13 08:18:22 +00006978 = FnDecl->getType()->getAs<FunctionType>()
6979 ->getCallResultType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +00006980
6981 // Build the actual expression node.
6982 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00006983 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00006984 UsualUnaryConversions(FnExpr);
6985
Anders Carlsson15ea3782009-10-13 22:43:21 +00006986 ExprOwningPtr<CXXOperatorCallExpr>
6987 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6988 Args, 2, ResultTy,
6989 OpLoc));
6990
6991 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6992 FnDecl))
6993 return ExprError();
6994
6995 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor063daf62009-03-13 18:40:31 +00006996 } else {
6997 // We matched a built-in operator. Convert the arguments, then
6998 // break out so that we will build the appropriate built-in
6999 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007000 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00007001 Best->Conversions[0], AA_Passing) ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007002 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00007003 Best->Conversions[1], AA_Passing))
Douglas Gregor063daf62009-03-13 18:40:31 +00007004 return ExprError();
7005
7006 break;
7007 }
7008 }
7009
Douglas Gregor33074752009-09-30 21:46:01 +00007010 case OR_No_Viable_Function: {
7011 // C++ [over.match.oper]p9:
7012 // If the operator is the operator , [...] and there are no
7013 // viable functions, then the operator is assumed to be the
7014 // built-in operator and interpreted according to clause 5.
7015 if (Opc == BinaryOperator::Comma)
7016 break;
7017
Sebastian Redl8593c782009-05-21 11:50:50 +00007018 // For class as left operand for assignment or compound assigment operator
7019 // do not fall through to handling in built-in, but report that no overloaded
7020 // assignment operator found
Douglas Gregor33074752009-09-30 21:46:01 +00007021 OwningExprResult Result = ExprError();
7022 if (Args[0]->getType()->isRecordType() &&
7023 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00007024 Diag(OpLoc, diag::err_ovl_no_viable_oper)
7025 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007026 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00007027 } else {
7028 // No viable function; try to create a built-in operation, which will
7029 // produce an error. Then, show the non-viable candidates.
7030 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00007031 }
Douglas Gregor33074752009-09-30 21:46:01 +00007032 assert(Result.isInvalid() &&
7033 "C++ binary operator overloading is missing candidates!");
7034 if (Result.isInvalid())
John McCallcbce6062010-01-12 07:18:19 +00007035 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00007036 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00007037 return move(Result);
7038 }
Douglas Gregor063daf62009-03-13 18:40:31 +00007039
7040 case OR_Ambiguous:
7041 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
7042 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007043 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007044 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00007045 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00007046 return ExprError();
7047
7048 case OR_Deleted:
7049 Diag(OpLoc, diag::err_ovl_deleted_oper)
7050 << Best->Function->isDeleted()
7051 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007052 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007053 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor063daf62009-03-13 18:40:31 +00007054 return ExprError();
John McCall1d318332010-01-12 00:44:57 +00007055 }
Douglas Gregor063daf62009-03-13 18:40:31 +00007056
Douglas Gregor33074752009-09-30 21:46:01 +00007057 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007058 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00007059}
7060
Sebastian Redlf322ed62009-10-29 20:17:01 +00007061Action::OwningExprResult
7062Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7063 SourceLocation RLoc,
7064 ExprArg Base, ExprArg Idx) {
7065 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
7066 static_cast<Expr*>(Idx.get()) };
7067 DeclarationName OpName =
7068 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7069
7070 // If either side is type-dependent, create an appropriate dependent
7071 // expression.
7072 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7073
John McCallc373d482010-01-27 01:50:18 +00007074 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00007075 // CHECKME: no 'operator' keyword?
7076 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7077 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +00007078 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00007079 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00007080 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00007081 /*ADL*/ true, /*Overloaded*/ false,
7082 UnresolvedSetIterator(),
7083 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +00007084 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00007085
7086 Base.release();
7087 Idx.release();
7088 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7089 Args, 2,
7090 Context.DependentTy,
7091 RLoc));
7092 }
7093
7094 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00007095 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007096
7097 // Subscript can only be overloaded as a member function.
7098
7099 // Add operator candidates that are member functions.
7100 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7101
7102 // Add builtin operator candidates.
7103 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7104
7105 // Perform overload resolution.
7106 OverloadCandidateSet::iterator Best;
7107 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
7108 case OR_Success: {
7109 // We found a built-in operator or an overloaded operator.
7110 FunctionDecl *FnDecl = Best->Function;
7111
7112 if (FnDecl) {
7113 // We matched an overloaded operator. Build a call to that
7114 // operator.
7115
John McCall9aa472c2010-03-19 07:35:19 +00007116 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007117 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +00007118
Sebastian Redlf322ed62009-10-29 20:17:01 +00007119 // Convert the arguments.
7120 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007121 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007122 Best->FoundDecl, Method))
Sebastian Redlf322ed62009-10-29 20:17:01 +00007123 return ExprError();
7124
Anders Carlsson38f88ab2010-01-29 18:37:50 +00007125 // Convert the arguments.
7126 OwningExprResult InputInit
7127 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7128 FnDecl->getParamDecl(0)),
7129 SourceLocation(),
7130 Owned(Args[1]));
7131 if (InputInit.isInvalid())
7132 return ExprError();
7133
7134 Args[1] = InputInit.takeAs<Expr>();
7135
Sebastian Redlf322ed62009-10-29 20:17:01 +00007136 // Determine the result type
7137 QualType ResultTy
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007138 = FnDecl->getType()->getAs<FunctionType>()
7139 ->getCallResultType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007140
7141 // Build the actual expression node.
7142 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7143 LLoc);
7144 UsualUnaryConversions(FnExpr);
7145
7146 Base.release();
7147 Idx.release();
7148 ExprOwningPtr<CXXOperatorCallExpr>
7149 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7150 FnExpr, Args, 2,
7151 ResultTy, RLoc));
7152
7153 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
7154 FnDecl))
7155 return ExprError();
7156
7157 return MaybeBindToTemporary(TheCall.release());
7158 } else {
7159 // We matched a built-in operator. Convert the arguments, then
7160 // break out so that we will build the appropriate built-in
7161 // operator node.
7162 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00007163 Best->Conversions[0], AA_Passing) ||
Sebastian Redlf322ed62009-10-29 20:17:01 +00007164 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00007165 Best->Conversions[1], AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00007166 return ExprError();
7167
7168 break;
7169 }
7170 }
7171
7172 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00007173 if (CandidateSet.empty())
7174 Diag(LLoc, diag::err_ovl_no_oper)
7175 << Args[0]->getType() << /*subscript*/ 0
7176 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7177 else
7178 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7179 << Args[0]->getType()
7180 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007181 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall1eb3e102010-01-07 02:04:15 +00007182 "[]", LLoc);
7183 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00007184 }
7185
7186 case OR_Ambiguous:
7187 Diag(LLoc, diag::err_ovl_ambiguous_oper)
7188 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007189 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redlf322ed62009-10-29 20:17:01 +00007190 "[]", LLoc);
7191 return ExprError();
7192
7193 case OR_Deleted:
7194 Diag(LLoc, diag::err_ovl_deleted_oper)
7195 << Best->Function->isDeleted() << "[]"
7196 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007197 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall81201622010-01-08 04:41:39 +00007198 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007199 return ExprError();
7200 }
7201
7202 // We matched a built-in operator; build it.
7203 Base.release();
7204 Idx.release();
7205 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
7206 Owned(Args[1]), RLoc);
7207}
7208
Douglas Gregor88a35142008-12-22 05:46:06 +00007209/// BuildCallToMemberFunction - Build a call to a member
7210/// function. MemExpr is the expression that refers to the member
7211/// function (and includes the object parameter), Args/NumArgs are the
7212/// arguments to the function call (not including the object
7213/// parameter). The caller needs to validate that the member
7214/// expression refers to a member function or an overloaded member
7215/// function.
John McCallaa81e162009-12-01 22:10:20 +00007216Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00007217Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7218 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor88a35142008-12-22 05:46:06 +00007219 unsigned NumArgs, SourceLocation *CommaLocs,
7220 SourceLocation RParenLoc) {
7221 // Dig out the member expression. This holds both the object
7222 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00007223 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7224
John McCall129e2df2009-11-30 22:42:35 +00007225 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00007226 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +00007227 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007228 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +00007229 if (isa<MemberExpr>(NakedMemExpr)) {
7230 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00007231 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +00007232 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +00007233 Qualifier = MemExpr->getQualifier();
John McCall129e2df2009-11-30 22:42:35 +00007234 } else {
7235 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007236 Qualifier = UnresExpr->getQualifier();
7237
John McCall701c89e2009-12-03 04:06:58 +00007238 QualType ObjectType = UnresExpr->getBaseType();
John McCall129e2df2009-11-30 22:42:35 +00007239
Douglas Gregor88a35142008-12-22 05:46:06 +00007240 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +00007241 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00007242
John McCallaa81e162009-12-01 22:10:20 +00007243 // FIXME: avoid copy.
7244 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7245 if (UnresExpr->hasExplicitTemplateArgs()) {
7246 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7247 TemplateArgs = &TemplateArgsBuffer;
7248 }
7249
John McCall129e2df2009-11-30 22:42:35 +00007250 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7251 E = UnresExpr->decls_end(); I != E; ++I) {
7252
John McCall701c89e2009-12-03 04:06:58 +00007253 NamedDecl *Func = *I;
7254 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7255 if (isa<UsingShadowDecl>(Func))
7256 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7257
John McCall129e2df2009-11-30 22:42:35 +00007258 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00007259 // If explicit template arguments were provided, we can't call a
7260 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00007261 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00007262 continue;
7263
John McCall9aa472c2010-03-19 07:35:19 +00007264 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCall86820f52010-01-26 01:37:31 +00007265 Args, NumArgs,
John McCall701c89e2009-12-03 04:06:58 +00007266 CandidateSet, /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00007267 } else {
John McCall129e2df2009-11-30 22:42:35 +00007268 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +00007269 I.getPair(), ActingDC, TemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00007270 ObjectType, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00007271 CandidateSet,
7272 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00007273 }
Douglas Gregordec06662009-08-21 18:42:58 +00007274 }
Mike Stump1eb44332009-09-09 15:08:12 +00007275
John McCall129e2df2009-11-30 22:42:35 +00007276 DeclarationName DeclName = UnresExpr->getMemberName();
7277
Douglas Gregor88a35142008-12-22 05:46:06 +00007278 OverloadCandidateSet::iterator Best;
John McCall129e2df2009-11-30 22:42:35 +00007279 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00007280 case OR_Success:
7281 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00007282 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +00007283 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007284 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +00007285 break;
7286
7287 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00007288 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00007289 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00007290 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007291 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00007292 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007293 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007294
7295 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00007296 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00007297 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007298 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00007299 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007300 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007301
7302 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00007303 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007304 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00007305 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007306 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007307 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007308 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007309 }
7310
John McCall6bb80172010-03-30 21:47:33 +00007311 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +00007312
John McCallaa81e162009-12-01 22:10:20 +00007313 // If overload resolution picked a static member, build a
7314 // non-member call based on that function.
7315 if (Method->isStatic()) {
7316 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7317 Args, NumArgs, RParenLoc);
7318 }
7319
John McCall129e2df2009-11-30 22:42:35 +00007320 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00007321 }
7322
7323 assert(Method && "Member call to something that isn't a method?");
Mike Stump1eb44332009-09-09 15:08:12 +00007324 ExprOwningPtr<CXXMemberCallExpr>
John McCallaa81e162009-12-01 22:10:20 +00007325 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump1eb44332009-09-09 15:08:12 +00007326 NumArgs,
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007327 Method->getCallResultType(),
Douglas Gregor88a35142008-12-22 05:46:06 +00007328 RParenLoc));
7329
Anders Carlssoneed3e692009-10-10 00:06:20 +00007330 // Check for a valid return type.
7331 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
7332 TheCall.get(), Method))
John McCallaa81e162009-12-01 22:10:20 +00007333 return ExprError();
Anders Carlssoneed3e692009-10-10 00:06:20 +00007334
Douglas Gregor88a35142008-12-22 05:46:06 +00007335 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +00007336 // We only need to do this if there was actually an overload; otherwise
7337 // it was done at lookup.
John McCallaa81e162009-12-01 22:10:20 +00007338 Expr *ObjectArg = MemExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00007339 if (!Method->isStatic() &&
John McCall6bb80172010-03-30 21:47:33 +00007340 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7341 FoundDecl, Method))
John McCallaa81e162009-12-01 22:10:20 +00007342 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007343 MemExpr->setBase(ObjectArg);
7344
7345 // Convert the rest of the arguments
Douglas Gregor5f970ee2010-05-04 18:18:31 +00007346 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00007347 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00007348 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00007349 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007350
Anders Carlssond406bf02009-08-16 01:56:34 +00007351 if (CheckFunctionCall(Method, TheCall.get()))
John McCallaa81e162009-12-01 22:10:20 +00007352 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00007353
John McCallaa81e162009-12-01 22:10:20 +00007354 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor88a35142008-12-22 05:46:06 +00007355}
7356
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007357/// BuildCallToObjectOfClassType - Build a call to an object of class
7358/// type (C++ [over.call.object]), which can end up invoking an
7359/// overloaded function call operator (@c operator()) or performing a
7360/// user-defined conversion on the object argument.
Mike Stump1eb44332009-09-09 15:08:12 +00007361Sema::ExprResult
7362Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00007363 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007364 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00007365 SourceLocation *CommaLocs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007366 SourceLocation RParenLoc) {
7367 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00007368 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00007369
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007370 // C++ [over.call.object]p1:
7371 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00007372 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007373 // candidate functions includes at least the function call
7374 // operators of T. The function call operators of T are obtained by
7375 // ordinary lookup of the name operator() in the context of
7376 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +00007377 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00007378 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00007379
7380 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007381 PDiag(diag::err_incomplete_object_call)
Douglas Gregor593564b2009-11-15 07:48:03 +00007382 << Object->getSourceRange()))
7383 return true;
7384
John McCalla24dc2e2009-11-17 02:14:36 +00007385 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7386 LookupQualifiedName(R, Record->getDecl());
7387 R.suppressDiagnostics();
7388
Douglas Gregor593564b2009-11-15 07:48:03 +00007389 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00007390 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00007391 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCall86820f52010-01-26 01:37:31 +00007392 Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00007393 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00007394 }
Douglas Gregor4a27d702009-10-21 06:18:39 +00007395
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007396 // C++ [over.call.object]p2:
7397 // In addition, for each conversion function declared in T of the
7398 // form
7399 //
7400 // operator conversion-type-id () cv-qualifier;
7401 //
7402 // where cv-qualifier is the same cv-qualification as, or a
7403 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00007404 // denotes the type "pointer to function of (P1,...,Pn) returning
7405 // R", or the type "reference to pointer to function of
7406 // (P1,...,Pn) returning R", or the type "reference to function
7407 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007408 // is also considered as a candidate function. Similarly,
7409 // surrogate call functions are added to the set of candidate
7410 // functions for each conversion function declared in an
7411 // accessible base class provided the function is not hidden
7412 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +00007413 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00007414 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00007415 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00007416 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00007417 NamedDecl *D = *I;
7418 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7419 if (isa<UsingShadowDecl>(D))
7420 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7421
Douglas Gregor4a27d702009-10-21 06:18:39 +00007422 // Skip over templated conversion functions; they aren't
7423 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00007424 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00007425 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007426
John McCall701c89e2009-12-03 04:06:58 +00007427 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCallba135432009-11-21 08:51:07 +00007428
Douglas Gregor4a27d702009-10-21 06:18:39 +00007429 // Strip the reference type (if any) and then the pointer type (if
7430 // any) to get down to what might be a function type.
7431 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7432 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7433 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007434
Douglas Gregor4a27d702009-10-21 06:18:39 +00007435 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall9aa472c2010-03-19 07:35:19 +00007436 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall701c89e2009-12-03 04:06:58 +00007437 Object->getType(), Args, NumArgs,
7438 CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007439 }
Mike Stump1eb44332009-09-09 15:08:12 +00007440
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007441 // Perform overload resolution.
7442 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00007443 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007444 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007445 // Overload resolution succeeded; we'll build the appropriate call
7446 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007447 break;
7448
7449 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00007450 if (CandidateSet.empty())
7451 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7452 << Object->getType() << /*call*/ 1
7453 << Object->getSourceRange();
7454 else
7455 Diag(Object->getSourceRange().getBegin(),
7456 diag::err_ovl_no_viable_object_call)
7457 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007458 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007459 break;
7460
7461 case OR_Ambiguous:
7462 Diag(Object->getSourceRange().getBegin(),
7463 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00007464 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007465 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007466 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007467
7468 case OR_Deleted:
7469 Diag(Object->getSourceRange().getBegin(),
7470 diag::err_ovl_deleted_object_call)
7471 << Best->Function->isDeleted()
7472 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007473 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007474 break;
Mike Stump1eb44332009-09-09 15:08:12 +00007475 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007476
Douglas Gregorff331c12010-07-25 18:17:45 +00007477 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007478 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007479
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007480 if (Best->Function == 0) {
7481 // Since there is no function declaration, this is one of the
7482 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00007483 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007484 = cast<CXXConversionDecl>(
7485 Best->Conversions[0].UserDefined.ConversionFunction);
7486
John McCall9aa472c2010-03-19 07:35:19 +00007487 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007488 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00007489
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007490 // We selected one of the surrogate functions that converts the
7491 // object parameter to a function pointer. Perform the conversion
7492 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00007493
7494 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00007495 // and then call it.
John McCall6bb80172010-03-30 21:47:33 +00007496 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7497 Conv);
Fariborz Jahanianb7400232009-09-28 23:23:40 +00007498
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00007499 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00007500 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
Douglas Gregoraa0be172010-04-13 15:50:39 +00007501 CommaLocs, RParenLoc).result();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007502 }
7503
John McCall9aa472c2010-03-19 07:35:19 +00007504 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007505 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00007506
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007507 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7508 // that calls this method, using Object for the implicit object
7509 // parameter and passing along the remaining arguments.
7510 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall183700f2009-09-21 23:43:11 +00007511 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007512
7513 unsigned NumArgsInProto = Proto->getNumArgs();
7514 unsigned NumArgsToCheck = NumArgs;
7515
7516 // Build the full argument list for the method call (the
7517 // implicit object parameter is placed at the beginning of the
7518 // list).
7519 Expr **MethodArgs;
7520 if (NumArgs < NumArgsInProto) {
7521 NumArgsToCheck = NumArgsInProto;
7522 MethodArgs = new Expr*[NumArgsInProto + 1];
7523 } else {
7524 MethodArgs = new Expr*[NumArgs + 1];
7525 }
7526 MethodArgs[0] = Object;
7527 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7528 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00007529
7530 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00007531 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007532 UsualUnaryConversions(NewFn);
7533
7534 // Once we've built TheCall, all of the expressions are properly
7535 // owned.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007536 QualType ResultTy = Method->getCallResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00007537 ExprOwningPtr<CXXOperatorCallExpr>
7538 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor063daf62009-03-13 18:40:31 +00007539 MethodArgs, NumArgs + 1,
Ted Kremenek8189cde2009-02-07 01:47:29 +00007540 ResultTy, RParenLoc));
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007541 delete [] MethodArgs;
7542
Anders Carlsson07d68f12009-10-13 21:49:31 +00007543 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
7544 Method))
7545 return true;
7546
Douglas Gregor518fda12009-01-13 05:10:00 +00007547 // We may have default arguments. If so, we need to allocate more
7548 // slots in the call for them.
7549 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00007550 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00007551 else if (NumArgs > NumArgsInProto)
7552 NumArgsToCheck = NumArgsInProto;
7553
Chris Lattner312531a2009-04-12 08:11:20 +00007554 bool IsError = false;
7555
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007556 // Initialize the implicit object parameter.
Douglas Gregor5fccd362010-03-03 23:55:11 +00007557 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007558 Best->FoundDecl, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007559 TheCall->setArg(0, Object);
7560
Chris Lattner312531a2009-04-12 08:11:20 +00007561
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007562 // Check the argument types.
7563 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007564 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00007565 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007566 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00007567
Douglas Gregor518fda12009-01-13 05:10:00 +00007568 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +00007569
7570 OwningExprResult InputInit
7571 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7572 Method->getParamDecl(i)),
7573 SourceLocation(), Owned(Arg));
7574
7575 IsError |= InputInit.isInvalid();
7576 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00007577 } else {
Douglas Gregord47c47d2009-11-09 19:27:57 +00007578 OwningExprResult DefArg
7579 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7580 if (DefArg.isInvalid()) {
7581 IsError = true;
7582 break;
7583 }
7584
7585 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00007586 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007587
7588 TheCall->setArg(i + 1, Arg);
7589 }
7590
7591 // If this is a variadic call, handle args passed through "...".
7592 if (Proto->isVariadic()) {
7593 // Promote the arguments (C99 6.5.2.2p7).
7594 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7595 Expr *Arg = Args[i];
Chris Lattner40378332010-05-16 04:01:30 +00007596 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007597 TheCall->setArg(i + 1, Arg);
7598 }
7599 }
7600
Chris Lattner312531a2009-04-12 08:11:20 +00007601 if (IsError) return true;
7602
Anders Carlssond406bf02009-08-16 01:56:34 +00007603 if (CheckFunctionCall(Method, TheCall.get()))
7604 return true;
7605
Douglas Gregoraa0be172010-04-13 15:50:39 +00007606 return MaybeBindToTemporary(TheCall.release()).result();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007607}
7608
Douglas Gregor8ba10742008-11-20 16:27:02 +00007609/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00007610/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00007611/// @c Member is the name of the member we're trying to find.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007612Sema::OwningExprResult
7613Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
7614 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor8ba10742008-11-20 16:27:02 +00007615 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00007616
John McCall5769d612010-02-08 23:07:23 +00007617 SourceLocation Loc = Base->getExprLoc();
7618
Douglas Gregor8ba10742008-11-20 16:27:02 +00007619 // C++ [over.ref]p1:
7620 //
7621 // [...] An expression x->m is interpreted as (x.operator->())->m
7622 // for a class object x of type T if T::operator->() exists and if
7623 // the operator is selected as the best match function by the
7624 // overload resolution mechanism (13.3).
Douglas Gregor8ba10742008-11-20 16:27:02 +00007625 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +00007626 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +00007627 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007628
John McCall5769d612010-02-08 23:07:23 +00007629 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +00007630 PDiag(diag::err_typecheck_incomplete_tag)
7631 << Base->getSourceRange()))
7632 return ExprError();
7633
John McCalla24dc2e2009-11-17 02:14:36 +00007634 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7635 LookupQualifiedName(R, BaseRecord->getDecl());
7636 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00007637
7638 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00007639 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00007640 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00007641 /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00007642 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00007643
7644 // Perform overload resolution.
7645 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00007646 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00007647 case OR_Success:
7648 // Overload resolution succeeded; we'll build the call below.
7649 break;
7650
7651 case OR_No_Viable_Function:
7652 if (CandidateSet.empty())
7653 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007654 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007655 else
7656 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007657 << "operator->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007658 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007659 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007660
7661 case OR_Ambiguous:
7662 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlssone30572a2009-09-10 23:18:36 +00007663 << "->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007664 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007665 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007666
7667 case OR_Deleted:
7668 Diag(OpLoc, diag::err_ovl_deleted_oper)
7669 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00007670 << "->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007671 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007672 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007673 }
7674
John McCall9aa472c2010-03-19 07:35:19 +00007675 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007676 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +00007677
Douglas Gregor8ba10742008-11-20 16:27:02 +00007678 // Convert the object parameter.
7679 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00007680 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7681 Best->FoundDecl, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007682 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00007683
7684 // No concerns about early exits now.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007685 BaseIn.release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007686
7687 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00007688 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7689 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00007690 UsualUnaryConversions(FnExpr);
Anders Carlsson15ea3782009-10-13 22:43:21 +00007691
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007692 QualType ResultTy = Method->getCallResultType();
Anders Carlsson15ea3782009-10-13 22:43:21 +00007693 ExprOwningPtr<CXXOperatorCallExpr>
7694 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7695 &Base, 1, ResultTy, OpLoc));
7696
7697 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
7698 Method))
7699 return ExprError();
7700 return move(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00007701}
7702
Douglas Gregor904eed32008-11-10 20:40:00 +00007703/// FixOverloadedFunctionReference - E is an expression that refers to
7704/// a C++ overloaded function (possibly with some parentheses and
7705/// perhaps a '&' around it). We have resolved the overloaded function
7706/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00007707/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +00007708Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +00007709 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00007710 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00007711 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7712 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00007713 if (SubExpr == PE->getSubExpr())
7714 return PE->Retain();
7715
7716 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7717 }
7718
7719 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00007720 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7721 Found, Fn);
Douglas Gregor097bfb12009-10-23 22:18:25 +00007722 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00007723 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00007724 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +00007725 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +00007726 if (SubExpr == ICE->getSubExpr())
7727 return ICE->Retain();
7728
John McCallf871d0c2010-08-07 06:22:56 +00007729 return ImplicitCastExpr::Create(Context, ICE->getType(),
7730 ICE->getCastKind(),
7731 SubExpr, 0,
7732 ICE->getCategory());
Douglas Gregor699ee522009-11-20 19:42:02 +00007733 }
7734
7735 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007736 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00007737 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00007738 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7739 if (Method->isStatic()) {
7740 // Do nothing: static member functions aren't any different
7741 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00007742 } else {
John McCallf7a1a742009-11-24 19:00:30 +00007743 // Fix the sub expression, which really has to be an
7744 // UnresolvedLookupExpr holding an overloaded member function
7745 // or template.
John McCall6bb80172010-03-30 21:47:33 +00007746 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7747 Found, Fn);
John McCallba135432009-11-21 08:51:07 +00007748 if (SubExpr == UnOp->getSubExpr())
7749 return UnOp->Retain();
Douglas Gregor699ee522009-11-20 19:42:02 +00007750
John McCallba135432009-11-21 08:51:07 +00007751 assert(isa<DeclRefExpr>(SubExpr)
7752 && "fixed to something other than a decl ref");
7753 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7754 && "fixed to a member ref with no nested name qualifier");
7755
7756 // We have taken the address of a pointer to member
7757 // function. Perform the computation here so that we get the
7758 // appropriate pointer to member type.
7759 QualType ClassType
7760 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7761 QualType MemPtrType
7762 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7763
7764 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7765 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00007766 }
7767 }
John McCall6bb80172010-03-30 21:47:33 +00007768 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7769 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00007770 if (SubExpr == UnOp->getSubExpr())
7771 return UnOp->Retain();
Anders Carlsson96ad5332009-10-21 17:16:23 +00007772
Douglas Gregor699ee522009-11-20 19:42:02 +00007773 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7774 Context.getPointerType(SubExpr->getType()),
7775 UnOp->getOperatorLoc());
Douglas Gregor699ee522009-11-20 19:42:02 +00007776 }
John McCallba135432009-11-21 08:51:07 +00007777
7778 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00007779 // FIXME: avoid copy.
7780 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00007781 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00007782 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7783 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00007784 }
7785
John McCallba135432009-11-21 08:51:07 +00007786 return DeclRefExpr::Create(Context,
7787 ULE->getQualifier(),
7788 ULE->getQualifierRange(),
7789 Fn,
7790 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00007791 Fn->getType(),
7792 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00007793 }
7794
John McCall129e2df2009-11-30 22:42:35 +00007795 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00007796 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00007797 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7798 if (MemExpr->hasExplicitTemplateArgs()) {
7799 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7800 TemplateArgs = &TemplateArgsBuffer;
7801 }
John McCalld5532b62009-11-23 01:53:49 +00007802
John McCallaa81e162009-12-01 22:10:20 +00007803 Expr *Base;
7804
7805 // If we're filling in
7806 if (MemExpr->isImplicitAccess()) {
7807 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7808 return DeclRefExpr::Create(Context,
7809 MemExpr->getQualifier(),
7810 MemExpr->getQualifierRange(),
7811 Fn,
7812 MemExpr->getMemberLoc(),
7813 Fn->getType(),
7814 TemplateArgs);
Douglas Gregor828a1972010-01-07 23:12:05 +00007815 } else {
7816 SourceLocation Loc = MemExpr->getMemberLoc();
7817 if (MemExpr->getQualifier())
7818 Loc = MemExpr->getQualifierRange().getBegin();
7819 Base = new (Context) CXXThisExpr(Loc,
7820 MemExpr->getBaseType(),
7821 /*isImplicit=*/true);
7822 }
John McCallaa81e162009-12-01 22:10:20 +00007823 } else
7824 Base = MemExpr->getBase()->Retain();
7825
7826 return MemberExpr::Create(Context, Base,
Douglas Gregor699ee522009-11-20 19:42:02 +00007827 MemExpr->isArrow(),
7828 MemExpr->getQualifier(),
7829 MemExpr->getQualifierRange(),
7830 Fn,
John McCall6bb80172010-03-30 21:47:33 +00007831 Found,
Abramo Bagnara25777432010-08-11 22:01:17 +00007832 MemExpr->getMemberNameInfo(),
John McCallaa81e162009-12-01 22:10:20 +00007833 TemplateArgs,
Douglas Gregor699ee522009-11-20 19:42:02 +00007834 Fn->getType());
7835 }
7836
Douglas Gregor699ee522009-11-20 19:42:02 +00007837 assert(false && "Invalid reference to overloaded function");
7838 return E->Retain();
Douglas Gregor904eed32008-11-10 20:40:00 +00007839}
7840
Douglas Gregor20093b42009-12-09 23:02:17 +00007841Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCall161755a2010-04-06 21:38:20 +00007842 DeclAccessPair Found,
Douglas Gregor20093b42009-12-09 23:02:17 +00007843 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +00007844 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +00007845}
7846
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007847} // end namespace clang