blob: 037bc7b76b7e9917e8126d90cffce88199512265 [file] [log] [blame]
Douglas Gregor5251f1b2008-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
14#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000016#include "SemaInit.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000017#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000018#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000023#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000025#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-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 Stump11289f42009-09-09 15:08:12 +000033ImplicitConversionCategory
Douglas Gregor5251f1b2008-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 Gregor40cb9ad2009-12-09 00:47:37 +000041 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000042 ICC_Qualification_Adjustment,
43 ICC_Promotion,
44 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000045 ICC_Promotion,
46 ICC_Conversion,
47 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000048 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000053 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000054 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +000055 ICC_Conversion,
56 ICC_Conversion,
Douglas Gregor5251f1b2008-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 Gregor40cb9ad2009-12-09 00:47:37 +000072 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000073 ICR_Promotion,
74 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000075 ICR_Promotion,
76 ICR_Conversion,
77 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000078 ICR_Conversion,
79 ICR_Conversion,
80 ICR_Conversion,
81 ICR_Conversion,
82 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000083 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000084 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +000085 ICR_Conversion,
86 ICR_Conversion,
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +000087 ICR_Complex_Real_Conversion
Douglas Gregor5251f1b2008-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 Lopescfca1f02009-12-23 17:49:57 +000095 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000096 "No conversion",
97 "Lvalue-to-rvalue",
98 "Array-to-pointer",
99 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000100 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000101 "Qualification",
102 "Integral promotion",
103 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000104 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000105 "Integral conversion",
106 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000107 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000108 "Floating-integral conversion",
109 "Pointer conversion",
110 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000111 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000112 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000113 "Derived-to-base conversion",
114 "Vector conversion",
115 "Vector splat",
116 "Complex-real conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000117 };
118 return Name[Kind];
119}
120
Douglas Gregor26bee0b2008-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 Gregore489a7d2010-02-28 18:30:25 +0000127 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000128 ReferenceBinding = false;
129 DirectBinding = false;
Sebastian Redlf69a94a2009-03-29 22:46:24 +0000130 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000131 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000132}
133
Douglas Gregor5251f1b2008-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 Stump11289f42009-09-09 15:08:12 +0000150/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000151/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000152bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-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 Gregor3edc4d52010-01-27 03:51:04 +0000157 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000158 (getFromType()->isPointerType() ||
159 getFromType()->isObjCObjectPointerType() ||
160 getFromType()->isBlockPointerType() ||
Douglas Gregor5251f1b2008-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 Gregor5c407d92008-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 Stump11289f42009-09-09 15:08:12 +0000171bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000172StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000173isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000174 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000175 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-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 Gregor1aa450a2009-12-13 21:37:05 +0000183 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000184 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000185 return ToPtrType->getPointeeType()->isVoidType();
186
187 return false;
188}
189
Douglas Gregor5251f1b2008-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 Dunbar42e3df02010-01-22 02:04:41 +0000193 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000194 bool PrintedSomething = false;
195 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000196 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000197 PrintedSomething = true;
198 }
199
200 if (Second != ICK_Identity) {
201 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000202 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000203 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000204 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000205
206 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000207 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000208 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000209 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000210 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000211 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000212 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000213 PrintedSomething = true;
214 }
215
216 if (Third != ICK_Identity) {
217 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000218 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000219 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000220 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000221 PrintedSomething = true;
222 }
223
224 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000225 OS << "No conversions required";
Douglas Gregor5251f1b2008-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 Dunbar42e3df02010-01-22 02:04:41 +0000232 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000233 if (Before.First || Before.Second || Before.Third) {
234 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000235 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000236 }
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000237 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000238 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000239 OS << " -> ";
Douglas Gregor5251f1b2008-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 Dunbar42e3df02010-01-22 02:04:41 +0000247 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000248 switch (ConversionKind) {
249 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000250 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000251 Standard.DebugPrint();
252 break;
253 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000254 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000255 UserDefined.DebugPrint();
256 break;
257 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000258 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000259 break;
John McCall0d1da222010-01-12 00:44:57 +0000260 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000261 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000262 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000263 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000264 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000265 break;
266 }
267
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000268 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000269}
270
John McCall0d1da222010-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 Gregor3626a5c2010-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 Gregor90cf2c92010-05-08 20:18:54 +0000299static MakeDeductionFailureInfo(ASTContext &Context,
300 Sema::TemplateDeductionResult TDK,
Douglas Gregord09efd42010-05-08 20:07:26 +0000301 Sema::TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-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 Gregor461761d2010-05-08 18:20:53 +0000308 case Sema::TDK_TooManyArguments:
309 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000310 break;
311
312 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000313 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000314 Result.Data = Info.Param.getOpaqueValue();
315 break;
316
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000317 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000318 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-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 Gregor3626a5c2010-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 Gregord09efd42010-05-08 20:07:26 +0000329 Result.Data = Info.take();
330 break;
331
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000332 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000333 case Sema::TDK_FailedOverloadResolution:
334 break;
335 }
336
337 return Result;
338}
John McCall0d1da222010-01-12 00:44:57 +0000339
Douglas Gregor3626a5c2010-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 Gregor461761d2010-05-08 18:20:53 +0000345 case Sema::TDK_TooManyArguments:
346 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000347 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000348 break;
349
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000350 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000351 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000352 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000353 Data = 0;
354 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000355
356 case Sema::TDK_SubstitutionFailure:
357 // FIXME: Destroy the template arugment list?
358 Data = 0;
359 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000360
Douglas Gregor461761d2010-05-08 18:20:53 +0000361 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000362 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-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 Gregor461761d2010-05-08 18:20:53 +0000373 case Sema::TDK_TooManyArguments:
374 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000375 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000376 return TemplateParameter();
377
378 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000379 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000380 return TemplateParameter::getFromOpaqueValue(Data);
381
382 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000383 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000384 return static_cast<DFIParamWithArguments*>(Data)->Param;
385
386 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000387 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000388 case Sema::TDK_FailedOverloadResolution:
389 break;
390 }
391
392 return TemplateParameter();
393}
Douglas Gregord09efd42010-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 McCall42d7d192010-08-05 09:05:08 +0000405 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-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 Gregor3626a5c2010-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 Gregor461761d2010-05-08 18:20:53 +0000425 case Sema::TDK_TooManyArguments:
426 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000427 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000428 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000429 return 0;
430
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000431 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000432 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000433 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
434
Douglas Gregor461761d2010-05-08 18:20:53 +0000435 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000436 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-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 Gregor461761d2010-05-08 18:20:53 +0000450 case Sema::TDK_TooManyArguments:
451 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000452 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000453 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000454 return 0;
455
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000456 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000457 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000458 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
459
Douglas Gregor461761d2010-05-08 18:20:53 +0000460 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000461 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000462 case Sema::TDK_FailedOverloadResolution:
463 break;
464 }
465
466 return 0;
467}
468
469void OverloadCandidateSet::clear() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000470 inherited::clear();
471 Functions.clear();
472}
473
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000474// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-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 McCalldaa3d6b2009-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 Gregor5251f1b2008-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 Stump11289f42009-09-09 15:08:12 +0000490// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000491//
John McCall3d988d92009-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 Gregor5251f1b2008-10-21 16:13:35 +0000496//
John McCall3d988d92009-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 Gregor5251f1b2008-10-21 16:13:35 +0000501// signature), IsOverload returns false and MatchedDecl will be set to
502// point to the FunctionDecl for #2.
John McCalle9cccd82010-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 McCalldaa3d6b2009-12-09 03:35:25 +0000508Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000509Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
510 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000511 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000512 I != E; ++I) {
John McCalle9cccd82010-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 McCall3d988d92009-12-02 08:47:38 +0000534 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-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 McCalldaa3d6b2009-12-09 03:35:25 +0000541 Match = *I;
542 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000543 }
John McCall3d988d92009-12-02 08:47:38 +0000544 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-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 McCalldaa3d6b2009-12-09 03:35:25 +0000551 Match = *I;
552 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000553 }
John McCall84d87672009-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 McCall1f82f242009-11-18 22:49:29 +0000563 // (C++ 13p1):
564 // Only function declarations can be overloaded; object and type
565 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000566 Match = *I;
567 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000568 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000569 }
John McCall1f82f242009-11-18 22:49:29 +0000570
John McCalldaa3d6b2009-12-09 03:35:25 +0000571 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000572}
573
John McCalle9cccd82010-06-16 08:42:20 +0000574bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
575 bool UseUsingDeclRules) {
John McCall1f82f242009-11-18 22:49:29 +0000576 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
577 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
578
579 // C++ [temp.fct]p2:
580 // A function template can be overloaded with other function templates
581 // and with normal (non-template) functions.
582 if ((OldTemplate == 0) != (NewTemplate == 0))
583 return true;
584
585 // Is the function New an overload of the function Old?
586 QualType OldQType = Context.getCanonicalType(Old->getType());
587 QualType NewQType = Context.getCanonicalType(New->getType());
588
589 // Compare the signatures (C++ 1.3.10) of the two functions to
590 // determine whether they are overloads. If we find any mismatch
591 // in the signature, they are overloads.
592
593 // If either of these functions is a K&R-style function (no
594 // prototype), then we consider them to have matching signatures.
595 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
596 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
597 return false;
598
599 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
600 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
601
602 // The signature of a function includes the types of its
603 // parameters (C++ 1.3.10), which includes the presence or absence
604 // of the ellipsis; see C++ DR 357).
605 if (OldQType != NewQType &&
606 (OldType->getNumArgs() != NewType->getNumArgs() ||
607 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000608 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000609 return true;
610
611 // C++ [temp.over.link]p4:
612 // The signature of a function template consists of its function
613 // signature, its return type and its template parameter list. The names
614 // of the template parameters are significant only for establishing the
615 // relationship between the template parameters and the rest of the
616 // signature.
617 //
618 // We check the return type and template parameter lists for function
619 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000620 //
621 // However, we don't consider either of these when deciding whether
622 // a member introduced by a shadow declaration is hidden.
623 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000624 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
625 OldTemplate->getTemplateParameters(),
626 false, TPL_TemplateMatch) ||
627 OldType->getResultType() != NewType->getResultType()))
628 return true;
629
630 // If the function is a class member, its signature includes the
631 // cv-qualifiers (if any) on the function itself.
632 //
633 // As part of this, also check whether one of the member functions
634 // is static, in which case they are not overloads (C++
635 // 13.1p2). While not part of the definition of the signature,
636 // this check is important to determine whether these functions
637 // can be overloaded.
638 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
639 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
640 if (OldMethod && NewMethod &&
641 !OldMethod->isStatic() && !NewMethod->isStatic() &&
642 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
643 return true;
644
645 // The signatures match; this is not an overload.
646 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000647}
648
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000649/// TryImplicitConversion - Attempt to perform an implicit conversion
650/// from the given expression (Expr) to the given type (ToType). This
651/// function returns an implicit conversion sequence that can be used
652/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000653///
654/// void f(float f);
655/// void g(int i) { f(i); }
656///
657/// this routine would produce an implicit conversion sequence to
658/// describe the initialization of f from i, which will be a standard
659/// conversion sequence containing an lvalue-to-rvalue conversion (C++
660/// 4.1) followed by a floating-integral conversion (C++ 4.9).
661//
662/// Note that this routine only determines how the conversion can be
663/// performed; it does not actually perform the conversion. As such,
664/// it will not produce any diagnostics if no conversion is available,
665/// but will instead return an implicit conversion sequence of kind
666/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000667///
668/// If @p SuppressUserConversions, then user-defined conversions are
669/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000670/// If @p AllowExplicit, then explicit user-defined conversions are
671/// permitted.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000672ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000673Sema::TryImplicitConversion(Expr* From, QualType ToType,
674 bool SuppressUserConversions,
Douglas Gregore81335c2010-04-16 18:00:29 +0000675 bool AllowExplicit,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000676 bool InOverloadResolution) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000677 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +0000678 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000679 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000680 return ICS;
681 }
682
683 if (!getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000684 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000685 return ICS;
686 }
687
Douglas Gregor5ab11652010-04-17 22:01:05 +0000688 if (SuppressUserConversions) {
689 // C++ [over.ics.user]p4:
690 // A conversion of an expression of class type to the same class
691 // type is given Exact Match rank, and a conversion of an
692 // expression of class type to a base class of that type is
693 // given Conversion rank, in spite of the fact that a copy/move
694 // constructor (i.e., a user-defined conversion function) is
695 // called for those cases.
696 QualType FromType = From->getType();
697 if (!ToType->getAs<RecordType>() || !FromType->getAs<RecordType>() ||
698 !(Context.hasSameUnqualifiedType(FromType, ToType) ||
699 IsDerivedFrom(FromType, ToType))) {
700 // We're not in the case above, so there is no conversion that
701 // we can perform.
702 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
703 return ICS;
704 }
705
706 ICS.setStandard();
707 ICS.Standard.setAsIdentityConversion();
708 ICS.Standard.setFromType(FromType);
709 ICS.Standard.setAllToTypes(ToType);
710
711 // We don't actually check at this point whether there is a valid
712 // copy/move constructor, since overloading just assumes that it
713 // exists. When we actually perform initialization, we'll find the
714 // appropriate constructor to copy the returned object, if needed.
715 ICS.Standard.CopyConstructor = 0;
716
717 // Determine whether this is considered a derived-to-base conversion.
718 if (!Context.hasSameUnqualifiedType(FromType, ToType))
719 ICS.Standard.Second = ICK_Derived_To_Base;
720
721 return ICS;
722 }
723
724 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000725 OverloadCandidateSet Conversions(From->getExprLoc());
726 OverloadingResult UserDefResult
727 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000728 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000729
730 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000731 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000732 // C++ [over.ics.user]p4:
733 // A conversion of an expression of class type to the same class
734 // type is given Exact Match rank, and a conversion of an
735 // expression of class type to a base class of that type is
736 // given Conversion rank, in spite of the fact that a copy
737 // constructor (i.e., a user-defined conversion function) is
738 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000739 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000740 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000741 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000742 = Context.getCanonicalType(From->getType().getUnqualifiedType());
743 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000744 if (Constructor->isCopyConstructor() &&
Douglas Gregor4141d5b2009-12-22 00:21:20 +0000745 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000746 // Turn this into a "standard" conversion sequence, so that it
747 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000748 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000749 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000750 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000751 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000752 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000753 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000754 ICS.Standard.Second = ICK_Derived_To_Base;
755 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000756 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000757
758 // C++ [over.best.ics]p4:
759 // However, when considering the argument of a user-defined
760 // conversion function that is a candidate by 13.3.1.3 when
761 // invoked for the copying of the temporary in the second step
762 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
763 // 13.3.1.6 in all cases, only standard conversion sequences and
764 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000765 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000766 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000767 }
John McCalle8c8cd22010-01-13 22:30:33 +0000768 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000769 ICS.setAmbiguous();
770 ICS.Ambiguous.setFromType(From->getType());
771 ICS.Ambiguous.setToType(ToType);
772 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
773 Cand != Conversions.end(); ++Cand)
774 if (Cand->Viable)
775 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000776 } else {
John McCall65eb8792010-02-25 01:37:24 +0000777 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000778 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000779
780 return ICS;
781}
782
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000783/// PerformImplicitConversion - Perform an implicit conversion of the
784/// expression From to the type ToType. Returns true if there was an
785/// error, false otherwise. The expression From is replaced with the
786/// converted expression. Flavor is the kind of conversion we're
787/// performing, used in the error message. If @p AllowExplicit,
788/// explicit user-defined conversions are permitted.
789bool
790Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
791 AssignmentAction Action, bool AllowExplicit) {
792 ImplicitConversionSequence ICS;
793 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
794}
795
796bool
797Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
798 AssignmentAction Action, bool AllowExplicit,
799 ImplicitConversionSequence& ICS) {
800 ICS = TryImplicitConversion(From, ToType,
801 /*SuppressUserConversions=*/false,
802 AllowExplicit,
803 /*InOverloadResolution=*/false);
804 return PerformImplicitConversion(From, ToType, ICS, Action);
805}
806
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000807/// \brief Determine whether the conversion from FromType to ToType is a valid
808/// conversion that strips "noreturn" off the nested function type.
809static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
810 QualType ToType, QualType &ResultTy) {
811 if (Context.hasSameUnqualifiedType(FromType, ToType))
812 return false;
813
814 // Strip the noreturn off the type we're converting from; noreturn can
815 // safely be removed.
816 FromType = Context.getNoReturnType(FromType, false);
817 if (!Context.hasSameUnqualifiedType(FromType, ToType))
818 return false;
819
820 ResultTy = FromType;
821 return true;
822}
Douglas Gregor46188682010-05-18 22:42:18 +0000823
824/// \brief Determine whether the conversion from FromType to ToType is a valid
825/// vector conversion.
826///
827/// \param ICK Will be set to the vector conversion kind, if this is a vector
828/// conversion.
829static bool IsVectorConversion(ASTContext &Context, QualType FromType,
830 QualType ToType, ImplicitConversionKind &ICK) {
831 // We need at least one of these types to be a vector type to have a vector
832 // conversion.
833 if (!ToType->isVectorType() && !FromType->isVectorType())
834 return false;
835
836 // Identical types require no conversions.
837 if (Context.hasSameUnqualifiedType(FromType, ToType))
838 return false;
839
840 // There are no conversions between extended vector types, only identity.
841 if (ToType->isExtVectorType()) {
842 // There are no conversions between extended vector types other than the
843 // identity conversion.
844 if (FromType->isExtVectorType())
845 return false;
846
847 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +0000848 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +0000849 ICK = ICK_Vector_Splat;
850 return true;
851 }
852 }
853
854 // If lax vector conversions are permitted and the vector types are of the
855 // same size, we can perform the conversion.
856 if (Context.getLangOptions().LaxVectorConversions &&
857 FromType->isVectorType() && ToType->isVectorType() &&
858 Context.getTypeSize(FromType) == Context.getTypeSize(ToType)) {
859 ICK = ICK_Vector_Conversion;
860 return true;
861 }
862
863 return false;
864}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000865
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000866/// IsStandardConversion - Determines whether there is a standard
867/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
868/// expression From to the type ToType. Standard conversion sequences
869/// only consider non-class types; for conversions that involve class
870/// types, use TryImplicitConversion. If a conversion exists, SCS will
871/// contain the standard conversion sequence required to perform this
872/// conversion and this routine will return true. Otherwise, this
873/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000874bool
875Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000876 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000877 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000878 QualType FromType = From->getType();
879
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000880 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000881 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000882 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000883 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000884 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000885 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000886
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000887 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000888 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000889 if (FromType->isRecordType() || ToType->isRecordType()) {
890 if (getLangOptions().CPlusPlus)
891 return false;
892
Mike Stump11289f42009-09-09 15:08:12 +0000893 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000894 }
895
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000896 // The first conversion can be an lvalue-to-rvalue conversion,
897 // array-to-pointer conversion, or function-to-pointer conversion
898 // (C++ 4p1).
899
Douglas Gregor980fb162010-04-29 18:24:40 +0000900 if (FromType == Context.OverloadTy) {
901 DeclAccessPair AccessPair;
902 if (FunctionDecl *Fn
903 = ResolveAddressOfOverloadedFunction(From, ToType, false,
904 AccessPair)) {
905 // We were able to resolve the address of the overloaded function,
906 // so we can convert to the type of that function.
907 FromType = Fn->getType();
908 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
909 if (!Method->isStatic()) {
910 Type *ClassType
911 = Context.getTypeDeclType(Method->getParent()).getTypePtr();
912 FromType = Context.getMemberPointerType(FromType, ClassType);
913 }
914 }
915
916 // If the "from" expression takes the address of the overloaded
917 // function, update the type of the resulting expression accordingly.
918 if (FromType->getAs<FunctionType>())
919 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
920 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
921 FromType = Context.getPointerType(FromType);
922
923 // Check that we've computed the proper type after overload resolution.
924 assert(Context.hasSameType(FromType,
925 FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
926 } else {
927 return false;
928 }
929 }
Mike Stump11289f42009-09-09 15:08:12 +0000930 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000931 // An lvalue (3.10) of a non-function, non-array type T can be
932 // converted to an rvalue.
933 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000934 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000935 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000936 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000937 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000938
939 // If T is a non-class type, the type of the rvalue is the
940 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000941 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
942 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000943 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000944 } else if (FromType->isArrayType()) {
945 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000946 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000947
948 // An lvalue or rvalue of type "array of N T" or "array of unknown
949 // bound of T" can be converted to an rvalue of type "pointer to
950 // T" (C++ 4.2p1).
951 FromType = Context.getArrayDecayedType(FromType);
952
953 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
954 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +0000955 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000956
957 // For the purpose of ranking in overload resolution
958 // (13.3.3.1.1), this conversion is considered an
959 // array-to-pointer conversion followed by a qualification
960 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000961 SCS.Second = ICK_Identity;
962 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000963 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000964 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000965 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000966 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
967 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000968 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000969
970 // An lvalue of function type T can be converted to an rvalue of
971 // type "pointer to T." The result is a pointer to the
972 // function. (C++ 4.3p1).
973 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000974 } else {
975 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000976 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000977 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000978 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000979
980 // The second conversion can be an integral promotion, floating
981 // point promotion, integral conversion, floating point conversion,
982 // floating-integral conversion, pointer conversion,
983 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000984 // For overloading in C, this can also be a "compatible-type"
985 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000986 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +0000987 ImplicitConversionKind SecondICK = ICK_Identity;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000988 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000989 // The unqualified versions of the types are the same: there's no
990 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000991 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000992 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000993 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000994 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000995 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000996 } else if (IsFloatingPointPromotion(FromType, ToType)) {
997 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000998 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000999 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001000 } else if (IsComplexPromotion(FromType, ToType)) {
1001 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001002 SCS.Second = ICK_Complex_Promotion;
1003 FromType = ToType.getUnqualifiedType();
Douglas Gregorb90df602010-06-16 00:17:44 +00001004 } else if (FromType->isIntegralOrEnumerationType() &&
Douglas Gregor6972a622010-06-16 00:35:25 +00001005 ToType->isIntegralType(Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001006 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001007 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001008 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001009 } else if (FromType->isComplexType() && ToType->isComplexType()) {
1010 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001011 SCS.Second = ICK_Complex_Conversion;
1012 FromType = ToType.getUnqualifiedType();
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001013 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
1014 (ToType->isComplexType() && FromType->isArithmeticType())) {
1015 // Complex-real conversions (C99 6.3.1.7)
1016 SCS.Second = ICK_Complex_Real;
1017 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001018 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001019 // Floating point conversions (C++ 4.8).
1020 SCS.Second = ICK_Floating_Conversion;
1021 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001022 } else if ((FromType->isRealFloatingType() &&
Douglas Gregor6972a622010-06-16 00:35:25 +00001023 ToType->isIntegralType(Context) && !ToType->isBooleanType()) ||
Douglas Gregorb90df602010-06-16 00:17:44 +00001024 (FromType->isIntegralOrEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001025 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001026 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001027 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001028 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +00001029 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1030 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001031 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001032 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001033 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +00001034 } else if (IsMemberPointerConversion(From, FromType, ToType,
1035 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001036 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001037 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +00001038 } else if (ToType->isBooleanType() &&
1039 (FromType->isArithmeticType() ||
1040 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +00001041 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +00001042 FromType->isBlockPointerType() ||
1043 FromType->isMemberPointerType() ||
Douglas Gregora3208f92010-06-22 23:41:02 +00001044 FromType->isNullPtrType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001045 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001046 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001047 FromType = Context.BoolTy;
Douglas Gregor46188682010-05-18 22:42:18 +00001048 } else if (IsVectorConversion(Context, FromType, ToType, SecondICK)) {
1049 SCS.Second = SecondICK;
1050 FromType = ToType.getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001051 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +00001052 Context.typesAreCompatible(ToType, FromType)) {
1053 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001054 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001055 FromType = ToType.getUnqualifiedType();
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001056 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
1057 // Treat a conversion that strips "noreturn" as an identity conversion.
1058 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001059 } else {
1060 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001061 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001062 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001063 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001064
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001065 QualType CanonFrom;
1066 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001067 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +00001068 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001069 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001070 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001071 CanonFrom = Context.getCanonicalType(FromType);
1072 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001073 } else {
1074 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001075 SCS.Third = ICK_Identity;
1076
Mike Stump11289f42009-09-09 15:08:12 +00001077 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001078 // [...] Any difference in top-level cv-qualification is
1079 // subsumed by the initialization itself and does not constitute
1080 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001081 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +00001082 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001083 if (CanonFrom.getLocalUnqualifiedType()
1084 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001085 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1086 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001087 FromType = ToType;
1088 CanonFrom = CanonTo;
1089 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001090 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001091 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001092
1093 // If we have not converted the argument type to the parameter type,
1094 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001095 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001096 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001097
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001098 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001099}
1100
1101/// IsIntegralPromotion - Determines whether the conversion from the
1102/// expression From (whose potentially-adjusted type is FromType) to
1103/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1104/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001105bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001106 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001107 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001108 if (!To) {
1109 return false;
1110 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001111
1112 // An rvalue of type char, signed char, unsigned char, short int, or
1113 // unsigned short int can be converted to an rvalue of type int if
1114 // int can represent all the values of the source type; otherwise,
1115 // the source rvalue can be converted to an rvalue of type unsigned
1116 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001117 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1118 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001119 if (// We can promote any signed, promotable integer type to an int
1120 (FromType->isSignedIntegerType() ||
1121 // We can promote any unsigned integer type whose size is
1122 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001123 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001124 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001125 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001126 }
1127
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001128 return To->getKind() == BuiltinType::UInt;
1129 }
1130
1131 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
1132 // can be converted to an rvalue of the first of the following types
1133 // that can represent all the values of its underlying type: int,
1134 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +00001135
1136 // We pre-calculate the promotion type for enum types.
1137 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
1138 if (ToType->isIntegerType())
1139 return Context.hasSameUnqualifiedType(ToType,
1140 FromEnumType->getDecl()->getPromotionType());
1141
1142 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001143 // Determine whether the type we're converting from is signed or
1144 // unsigned.
1145 bool FromIsSigned;
1146 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +00001147
1148 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1149 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001150
1151 // The types we'll try to promote to, in the appropriate
1152 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001153 QualType PromoteTypes[6] = {
1154 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001155 Context.LongTy, Context.UnsignedLongTy ,
1156 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001157 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001158 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001159 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1160 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001161 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001162 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1163 // We found the type that we can promote to. If this is the
1164 // type we wanted, we have a promotion. Otherwise, no
1165 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001166 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001167 }
1168 }
1169 }
1170
1171 // An rvalue for an integral bit-field (9.6) can be converted to an
1172 // rvalue of type int if int can represent all the values of the
1173 // bit-field; otherwise, it can be converted to unsigned int if
1174 // unsigned int can represent all the values of the bit-field. If
1175 // the bit-field is larger yet, no integral promotion applies to
1176 // it. If the bit-field has an enumerated type, it is treated as any
1177 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001178 // FIXME: We should delay checking of bit-fields until we actually perform the
1179 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001180 using llvm::APSInt;
1181 if (From)
1182 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001183 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001184 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001185 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1186 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1187 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001188
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001189 // Are we promoting to an int from a bitfield that fits in an int?
1190 if (BitWidth < ToSize ||
1191 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1192 return To->getKind() == BuiltinType::Int;
1193 }
Mike Stump11289f42009-09-09 15:08:12 +00001194
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001195 // Are we promoting to an unsigned int from an unsigned bitfield
1196 // that fits into an unsigned int?
1197 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1198 return To->getKind() == BuiltinType::UInt;
1199 }
Mike Stump11289f42009-09-09 15:08:12 +00001200
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001201 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001202 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001203 }
Mike Stump11289f42009-09-09 15:08:12 +00001204
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001205 // An rvalue of type bool can be converted to an rvalue of type int,
1206 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001207 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001208 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001209 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001210
1211 return false;
1212}
1213
1214/// IsFloatingPointPromotion - Determines whether the conversion from
1215/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1216/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001217bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001218 /// An rvalue of type float can be converted to an rvalue of type
1219 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001220 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1221 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001222 if (FromBuiltin->getKind() == BuiltinType::Float &&
1223 ToBuiltin->getKind() == BuiltinType::Double)
1224 return true;
1225
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001226 // C99 6.3.1.5p1:
1227 // When a float is promoted to double or long double, or a
1228 // double is promoted to long double [...].
1229 if (!getLangOptions().CPlusPlus &&
1230 (FromBuiltin->getKind() == BuiltinType::Float ||
1231 FromBuiltin->getKind() == BuiltinType::Double) &&
1232 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1233 return true;
1234 }
1235
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001236 return false;
1237}
1238
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001239/// \brief Determine if a conversion is a complex promotion.
1240///
1241/// A complex promotion is defined as a complex -> complex conversion
1242/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001243/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001244bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001245 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001246 if (!FromComplex)
1247 return false;
1248
John McCall9dd450b2009-09-21 23:43:11 +00001249 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001250 if (!ToComplex)
1251 return false;
1252
1253 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001254 ToComplex->getElementType()) ||
1255 IsIntegralPromotion(0, FromComplex->getElementType(),
1256 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001257}
1258
Douglas Gregor237f96c2008-11-26 23:31:11 +00001259/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1260/// the pointer type FromPtr to a pointer to type ToPointee, with the
1261/// same type qualifiers as FromPtr has on its pointee type. ToType,
1262/// if non-empty, will be a pointer to ToType that may or may not have
1263/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001264static QualType
1265BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001266 QualType ToPointee, QualType ToType,
1267 ASTContext &Context) {
1268 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1269 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001270 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001271
1272 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001273 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001274 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001275 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001276 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001277
1278 // Build a pointer to ToPointee. It has the right qualifiers
1279 // already.
1280 return Context.getPointerType(ToPointee);
1281 }
1282
1283 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +00001284 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001285 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1286 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +00001287}
1288
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001289/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1290/// the FromType, which is an objective-c pointer, to ToType, which may or may
1291/// not have the right set of qualifiers.
1292static QualType
1293BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1294 QualType ToType,
1295 ASTContext &Context) {
1296 QualType CanonFromType = Context.getCanonicalType(FromType);
1297 QualType CanonToType = Context.getCanonicalType(ToType);
1298 Qualifiers Quals = CanonFromType.getQualifiers();
1299
1300 // Exact qualifier match -> return the pointer type we're converting to.
1301 if (CanonToType.getLocalQualifiers() == Quals)
1302 return ToType;
1303
1304 // Just build a canonical type that has the right qualifiers.
1305 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1306}
1307
Mike Stump11289f42009-09-09 15:08:12 +00001308static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001309 bool InOverloadResolution,
1310 ASTContext &Context) {
1311 // Handle value-dependent integral null pointer constants correctly.
1312 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1313 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001314 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001315 return !InOverloadResolution;
1316
Douglas Gregor56751b52009-09-25 04:25:58 +00001317 return Expr->isNullPointerConstant(Context,
1318 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1319 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001320}
Mike Stump11289f42009-09-09 15:08:12 +00001321
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001322/// IsPointerConversion - Determines whether the conversion of the
1323/// expression From, which has the (possibly adjusted) type FromType,
1324/// can be converted to the type ToType via a pointer conversion (C++
1325/// 4.10). If so, returns true and places the converted type (that
1326/// might differ from ToType in its cv-qualifiers at some level) into
1327/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001328///
Douglas Gregora29dc052008-11-27 01:19:21 +00001329/// This routine also supports conversions to and from block pointers
1330/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1331/// pointers to interfaces. FIXME: Once we've determined the
1332/// appropriate overloading rules for Objective-C, we may want to
1333/// split the Objective-C checks into a different routine; however,
1334/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001335/// conversions, so for now they live here. IncompatibleObjC will be
1336/// set if the conversion is an allowed Objective-C conversion that
1337/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001338bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001339 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001340 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001341 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001342 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001343 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1344 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001345
Mike Stump11289f42009-09-09 15:08:12 +00001346 // Conversion from a null pointer constant to any Objective-C pointer type.
1347 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001348 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001349 ConvertedType = ToType;
1350 return true;
1351 }
1352
Douglas Gregor231d1c62008-11-27 00:15:41 +00001353 // Blocks: Block pointers can be converted to void*.
1354 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001355 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001356 ConvertedType = ToType;
1357 return true;
1358 }
1359 // Blocks: A null pointer constant can be converted to a block
1360 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001361 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001362 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001363 ConvertedType = ToType;
1364 return true;
1365 }
1366
Sebastian Redl576fd422009-05-10 18:38:11 +00001367 // If the left-hand-side is nullptr_t, the right side can be a null
1368 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001369 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001370 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001371 ConvertedType = ToType;
1372 return true;
1373 }
1374
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001375 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001376 if (!ToTypePtr)
1377 return false;
1378
1379 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001380 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001381 ConvertedType = ToType;
1382 return true;
1383 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001384
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001385 // Beyond this point, both types need to be pointers
1386 // , including objective-c pointers.
1387 QualType ToPointeeType = ToTypePtr->getPointeeType();
1388 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1389 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1390 ToType, Context);
1391 return true;
1392
1393 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001394 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001395 if (!FromTypePtr)
1396 return false;
1397
1398 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001399
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001400 // An rvalue of type "pointer to cv T," where T is an object type,
1401 // can be converted to an rvalue of type "pointer to cv void" (C++
1402 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001403 if (FromPointeeType->isIncompleteOrObjectType() &&
1404 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001405 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001406 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001407 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001408 return true;
1409 }
1410
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001411 // When we're overloading in C, we allow a special kind of pointer
1412 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001413 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001414 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001415 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001416 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001417 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001418 return true;
1419 }
1420
Douglas Gregor5c407d92008-10-23 00:40:37 +00001421 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001422 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001423 // An rvalue of type "pointer to cv D," where D is a class type,
1424 // can be converted to an rvalue of type "pointer to cv B," where
1425 // B is a base class (clause 10) of D. If B is an inaccessible
1426 // (clause 11) or ambiguous (10.2) base class of D, a program that
1427 // necessitates this conversion is ill-formed. The result of the
1428 // conversion is a pointer to the base class sub-object of the
1429 // derived class object. The null pointer value is converted to
1430 // the null pointer value of the destination type.
1431 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001432 // Note that we do not check for ambiguity or inaccessibility
1433 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001434 if (getLangOptions().CPlusPlus &&
1435 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001436 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001437 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001438 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001439 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001440 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001441 ToType, Context);
1442 return true;
1443 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001444
Douglas Gregora119f102008-12-19 19:13:09 +00001445 return false;
1446}
1447
1448/// isObjCPointerConversion - Determines whether this is an
1449/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1450/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001451bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001452 QualType& ConvertedType,
1453 bool &IncompatibleObjC) {
1454 if (!getLangOptions().ObjC1)
1455 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001456
Steve Naroff7cae42b2009-07-10 23:34:53 +00001457 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001458 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001459 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001460 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001461
Steve Naroff7cae42b2009-07-10 23:34:53 +00001462 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001463 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001464 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001465 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001466 ConvertedType = ToType;
1467 return true;
1468 }
1469 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001470 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001471 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001472 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001473 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001474 ConvertedType = ToType;
1475 return true;
1476 }
1477 // Objective C++: We're able to convert from a pointer to an
1478 // interface to a pointer to a different interface.
1479 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001480 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1481 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1482 if (getLangOptions().CPlusPlus && LHS && RHS &&
1483 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1484 FromObjCPtr->getPointeeType()))
1485 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001486 ConvertedType = ToType;
1487 return true;
1488 }
1489
1490 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1491 // Okay: this is some kind of implicit downcast of Objective-C
1492 // interfaces, which is permitted. However, we're going to
1493 // complain about it.
1494 IncompatibleObjC = true;
1495 ConvertedType = FromType;
1496 return true;
1497 }
Mike Stump11289f42009-09-09 15:08:12 +00001498 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001499 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001500 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001501 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001502 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001503 else if (const BlockPointerType *ToBlockPtr =
1504 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001505 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001506 // to a block pointer type.
1507 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1508 ConvertedType = ToType;
1509 return true;
1510 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001511 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001512 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001513 else if (FromType->getAs<BlockPointerType>() &&
1514 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1515 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001516 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001517 ConvertedType = ToType;
1518 return true;
1519 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001520 else
Douglas Gregora119f102008-12-19 19:13:09 +00001521 return false;
1522
Douglas Gregor033f56d2008-12-23 00:53:59 +00001523 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001524 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001525 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001526 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001527 FromPointeeType = FromBlockPtr->getPointeeType();
1528 else
Douglas Gregora119f102008-12-19 19:13:09 +00001529 return false;
1530
Douglas Gregora119f102008-12-19 19:13:09 +00001531 // If we have pointers to pointers, recursively check whether this
1532 // is an Objective-C conversion.
1533 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1534 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1535 IncompatibleObjC)) {
1536 // We always complain about this conversion.
1537 IncompatibleObjC = true;
1538 ConvertedType = ToType;
1539 return true;
1540 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001541 // Allow conversion of pointee being objective-c pointer to another one;
1542 // as in I* to id.
1543 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1544 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1545 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1546 IncompatibleObjC)) {
1547 ConvertedType = ToType;
1548 return true;
1549 }
1550
Douglas Gregor033f56d2008-12-23 00:53:59 +00001551 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001552 // differences in the argument and result types are in Objective-C
1553 // pointer conversions. If so, we permit the conversion (but
1554 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001555 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001556 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001557 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001558 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001559 if (FromFunctionType && ToFunctionType) {
1560 // If the function types are exactly the same, this isn't an
1561 // Objective-C pointer conversion.
1562 if (Context.getCanonicalType(FromPointeeType)
1563 == Context.getCanonicalType(ToPointeeType))
1564 return false;
1565
1566 // Perform the quick checks that will tell us whether these
1567 // function types are obviously different.
1568 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1569 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1570 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1571 return false;
1572
1573 bool HasObjCConversion = false;
1574 if (Context.getCanonicalType(FromFunctionType->getResultType())
1575 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1576 // Okay, the types match exactly. Nothing to do.
1577 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1578 ToFunctionType->getResultType(),
1579 ConvertedType, IncompatibleObjC)) {
1580 // Okay, we have an Objective-C pointer conversion.
1581 HasObjCConversion = true;
1582 } else {
1583 // Function types are too different. Abort.
1584 return false;
1585 }
Mike Stump11289f42009-09-09 15:08:12 +00001586
Douglas Gregora119f102008-12-19 19:13:09 +00001587 // Check argument types.
1588 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1589 ArgIdx != NumArgs; ++ArgIdx) {
1590 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1591 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1592 if (Context.getCanonicalType(FromArgType)
1593 == Context.getCanonicalType(ToArgType)) {
1594 // Okay, the types match exactly. Nothing to do.
1595 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1596 ConvertedType, IncompatibleObjC)) {
1597 // Okay, we have an Objective-C pointer conversion.
1598 HasObjCConversion = true;
1599 } else {
1600 // Argument types are too different. Abort.
1601 return false;
1602 }
1603 }
1604
1605 if (HasObjCConversion) {
1606 // We had an Objective-C conversion. Allow this pointer
1607 // conversion, but complain about it.
1608 ConvertedType = ToType;
1609 IncompatibleObjC = true;
1610 return true;
1611 }
1612 }
1613
Sebastian Redl72b597d2009-01-25 19:43:20 +00001614 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001615}
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001616
1617/// FunctionArgTypesAreEqual - This routine checks two function proto types
1618/// for equlity of their argument types. Caller has already checked that
1619/// they have same number of arguments. This routine assumes that Objective-C
1620/// pointer types which only differ in their protocol qualifiers are equal.
1621bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1622 FunctionProtoType* NewType){
1623 if (!getLangOptions().ObjC1)
1624 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1625 NewType->arg_type_begin());
1626
1627 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1628 N = NewType->arg_type_begin(),
1629 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1630 QualType ToType = (*O);
1631 QualType FromType = (*N);
1632 if (ToType != FromType) {
1633 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1634 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001635 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1636 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1637 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1638 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001639 continue;
1640 }
John McCall8b07ec22010-05-15 11:32:37 +00001641 else if (const ObjCObjectPointerType *PTTo =
1642 ToType->getAs<ObjCObjectPointerType>()) {
1643 if (const ObjCObjectPointerType *PTFr =
1644 FromType->getAs<ObjCObjectPointerType>())
1645 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1646 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001647 }
1648 return false;
1649 }
1650 }
1651 return true;
1652}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001653
Douglas Gregor39c16d42008-10-24 04:54:22 +00001654/// CheckPointerConversion - Check the pointer conversion from the
1655/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001656/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001657/// conversions for which IsPointerConversion has already returned
1658/// true. It returns true and produces a diagnostic if there was an
1659/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001660bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001661 CastExpr::CastKind &Kind,
Anders Carlssona70cff62010-04-24 19:06:50 +00001662 CXXBaseSpecifierArray& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001663 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001664 QualType FromType = From->getType();
1665
Douglas Gregor4038cf42010-06-08 17:35:15 +00001666 if (CXXBoolLiteralExpr* LitBool
1667 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
1668 if (LitBool->getValue() == false)
1669 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1670 << ToType;
1671
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001672 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1673 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001674 QualType FromPointeeType = FromPtrType->getPointeeType(),
1675 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001676
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001677 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1678 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001679 // We must have a derived-to-base conversion. Check an
1680 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001681 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1682 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001683 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001684 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001685 return true;
1686
1687 // The conversion was successful.
1688 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001689 }
1690 }
Mike Stump11289f42009-09-09 15:08:12 +00001691 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001692 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001693 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001694 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001695 // Objective-C++ conversions are always okay.
1696 // FIXME: We should have a different class of conversions for the
1697 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001698 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001699 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001700
Steve Naroff7cae42b2009-07-10 23:34:53 +00001701 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001702 return false;
1703}
1704
Sebastian Redl72b597d2009-01-25 19:43:20 +00001705/// IsMemberPointerConversion - Determines whether the conversion of the
1706/// expression From, which has the (possibly adjusted) type FromType, can be
1707/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1708/// If so, returns true and places the converted type (that might differ from
1709/// ToType in its cv-qualifiers at some level) into ConvertedType.
1710bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001711 QualType ToType,
1712 bool InOverloadResolution,
1713 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001714 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001715 if (!ToTypePtr)
1716 return false;
1717
1718 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001719 if (From->isNullPointerConstant(Context,
1720 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1721 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001722 ConvertedType = ToType;
1723 return true;
1724 }
1725
1726 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001727 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001728 if (!FromTypePtr)
1729 return false;
1730
1731 // A pointer to member of B can be converted to a pointer to member of D,
1732 // where D is derived from B (C++ 4.11p2).
1733 QualType FromClass(FromTypePtr->getClass(), 0);
1734 QualType ToClass(ToTypePtr->getClass(), 0);
1735 // FIXME: What happens when these are dependent? Is this function even called?
1736
1737 if (IsDerivedFrom(ToClass, FromClass)) {
1738 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1739 ToClass.getTypePtr());
1740 return true;
1741 }
1742
1743 return false;
1744}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001745
Sebastian Redl72b597d2009-01-25 19:43:20 +00001746/// CheckMemberPointerConversion - Check the member pointer conversion from the
1747/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001748/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001749/// for which IsMemberPointerConversion has already returned true. It returns
1750/// true and produces a diagnostic if there was an error, or returns false
1751/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001752bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001753 CastExpr::CastKind &Kind,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001754 CXXBaseSpecifierArray &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001755 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001756 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001757 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001758 if (!FromPtrType) {
1759 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001760 assert(From->isNullPointerConstant(Context,
1761 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001762 "Expr must be null pointer constant!");
1763 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001764 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001765 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001766
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001767 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001768 assert(ToPtrType && "No member pointer cast has a target type "
1769 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001770
Sebastian Redled8f2002009-01-28 18:33:18 +00001771 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1772 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001773
Sebastian Redled8f2002009-01-28 18:33:18 +00001774 // FIXME: What about dependent types?
1775 assert(FromClass->isRecordType() && "Pointer into non-class.");
1776 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001777
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001778 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001779 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001780 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1781 assert(DerivationOkay &&
1782 "Should not have been called if derivation isn't OK.");
1783 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001784
Sebastian Redled8f2002009-01-28 18:33:18 +00001785 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1786 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001787 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1788 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1789 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1790 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001791 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001792
Douglas Gregor89ee6822009-02-28 01:32:25 +00001793 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001794 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1795 << FromClass << ToClass << QualType(VBase, 0)
1796 << From->getSourceRange();
1797 return true;
1798 }
1799
John McCall5b0829a2010-02-10 09:31:12 +00001800 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001801 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1802 Paths.front(),
1803 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001804
Anders Carlssond7923c62009-08-22 23:33:40 +00001805 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001806 BuildBasePathArray(Paths, BasePath);
Anders Carlssond7923c62009-08-22 23:33:40 +00001807 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001808 return false;
1809}
1810
Douglas Gregor9a657932008-10-21 23:43:52 +00001811/// IsQualificationConversion - Determines whether the conversion from
1812/// an rvalue of type FromType to ToType is a qualification conversion
1813/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001814bool
1815Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001816 FromType = Context.getCanonicalType(FromType);
1817 ToType = Context.getCanonicalType(ToType);
1818
1819 // If FromType and ToType are the same type, this is not a
1820 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001821 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001822 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001823
Douglas Gregor9a657932008-10-21 23:43:52 +00001824 // (C++ 4.4p4):
1825 // A conversion can add cv-qualifiers at levels other than the first
1826 // in multi-level pointers, subject to the following rules: [...]
1827 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001828 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001829 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001830 // Within each iteration of the loop, we check the qualifiers to
1831 // determine if this still looks like a qualification
1832 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001833 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001834 // until there are no more pointers or pointers-to-members left to
1835 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001836 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001837
1838 // -- for every j > 0, if const is in cv 1,j then const is in cv
1839 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001840 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001841 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001842
Douglas Gregor9a657932008-10-21 23:43:52 +00001843 // -- if the cv 1,j and cv 2,j are different, then const is in
1844 // every cv for 0 < k < j.
1845 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001846 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001847 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001848
Douglas Gregor9a657932008-10-21 23:43:52 +00001849 // Keep track of whether all prior cv-qualifiers in the "to" type
1850 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001851 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001852 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001853 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001854
1855 // We are left with FromType and ToType being the pointee types
1856 // after unwrapping the original FromType and ToType the same number
1857 // of types. If we unwrapped any pointers, and if FromType and
1858 // ToType have the same unqualified type (since we checked
1859 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001860 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001861}
1862
Douglas Gregor576e98c2009-01-30 23:27:23 +00001863/// Determines whether there is a user-defined conversion sequence
1864/// (C++ [over.ics.user]) that converts expression From to the type
1865/// ToType. If such a conversion exists, User will contain the
1866/// user-defined conversion sequence that performs such a conversion
1867/// and this routine will return true. Otherwise, this routine returns
1868/// false and User is unspecified.
1869///
Douglas Gregor576e98c2009-01-30 23:27:23 +00001870/// \param AllowExplicit true if the conversion should consider C++0x
1871/// "explicit" conversion functions as well as non-explicit conversion
1872/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001873OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1874 UserDefinedConversionSequence& User,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001875 OverloadCandidateSet& CandidateSet,
1876 bool AllowExplicit) {
1877 // Whether we will only visit constructors.
1878 bool ConstructorsOnly = false;
1879
1880 // If the type we are conversion to is a class type, enumerate its
1881 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001882 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001883 // C++ [over.match.ctor]p1:
1884 // When objects of class type are direct-initialized (8.5), or
1885 // copy-initialized from an expression of the same or a
1886 // derived class type (8.5), overload resolution selects the
1887 // constructor. [...] For copy-initialization, the candidate
1888 // functions are all the converting constructors (12.3.1) of
1889 // that class. The argument list is the expression-list within
1890 // the parentheses of the initializer.
1891 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1892 (From->getType()->getAs<RecordType>() &&
1893 IsDerivedFrom(From->getType(), ToType)))
1894 ConstructorsOnly = true;
1895
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001896 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1897 // We're not going to find any constructors.
1898 } else if (CXXRecordDecl *ToRecordDecl
1899 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001900 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00001901 for (llvm::tie(Con, ConEnd) = LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001902 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00001903 NamedDecl *D = *Con;
1904 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1905
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001906 // Find the constructor (which may be a template).
1907 CXXConstructorDecl *Constructor = 0;
1908 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00001909 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001910 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001911 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001912 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1913 else
John McCalla0296f72010-03-19 07:35:19 +00001914 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001915
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001916 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001917 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001918 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00001919 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001920 /*ExplicitArgs*/ 0,
John McCall6b51f282009-11-23 01:53:49 +00001921 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001922 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001923 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001924 // Allow one user-defined conversion when user specifies a
1925 // From->ToType conversion via an static cast (c-style, etc).
John McCalla0296f72010-03-19 07:35:19 +00001926 AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001927 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001928 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001929 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001930 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001931 }
1932 }
1933
Douglas Gregor5ab11652010-04-17 22:01:05 +00001934 // Enumerate conversion functions, if we're allowed to.
1935 if (ConstructorsOnly) {
Mike Stump11289f42009-09-09 15:08:12 +00001936 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
Douglas Gregor5ab11652010-04-17 22:01:05 +00001937 PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001938 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001939 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00001940 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001941 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001942 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1943 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00001944 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001945 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001946 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001947 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00001948 DeclAccessPair FoundDecl = I.getPair();
1949 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00001950 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1951 if (isa<UsingShadowDecl>(D))
1952 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1953
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001954 CXXConversionDecl *Conv;
1955 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00001956 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1957 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001958 else
John McCallda4458e2010-03-31 01:36:47 +00001959 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001960
1961 if (AllowExplicit || !Conv->isExplicit()) {
1962 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00001963 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001964 ActingContext, From, ToType,
1965 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001966 else
John McCalla0296f72010-03-19 07:35:19 +00001967 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCallb89836b2010-01-26 01:37:31 +00001968 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001969 }
1970 }
1971 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001972 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001973
1974 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001975 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001976 case OR_Success:
1977 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001978 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001979 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1980 // C++ [over.ics.user]p1:
1981 // If the user-defined conversion is specified by a
1982 // constructor (12.3.1), the initial standard conversion
1983 // sequence converts the source type to the type required by
1984 // the argument of the constructor.
1985 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001986 QualType ThisType = Constructor->getThisType(Context);
John McCall0d1da222010-01-12 00:44:57 +00001987 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian55824512009-11-06 00:23:08 +00001988 User.EllipsisConversion = true;
1989 else {
1990 User.Before = Best->Conversions[0].Standard;
1991 User.EllipsisConversion = false;
1992 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001993 User.ConversionFunction = Constructor;
1994 User.After.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00001995 User.After.setFromType(
1996 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001997 User.After.setAllToTypes(ToType);
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001998 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001999 } else if (CXXConversionDecl *Conversion
2000 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2001 // C++ [over.ics.user]p1:
2002 //
2003 // [...] If the user-defined conversion is specified by a
2004 // conversion function (12.3.2), the initial standard
2005 // conversion sequence converts the source type to the
2006 // implicit object parameter of the conversion function.
2007 User.Before = Best->Conversions[0].Standard;
2008 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002009 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002010
2011 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00002012 // The second standard conversion sequence converts the
2013 // result of the user-defined conversion to the target type
2014 // for the sequence. Since an implicit conversion sequence
2015 // is an initialization, the special rules for
2016 // initialization by user-defined conversion apply when
2017 // selecting the best user-defined conversion for a
2018 // user-defined conversion sequence (see 13.3.3 and
2019 // 13.3.3.1).
2020 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002021 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002022 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002023 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002024 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002025 }
Mike Stump11289f42009-09-09 15:08:12 +00002026
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002027 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002028 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00002029 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002030 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002031 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002032
2033 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002034 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002035 }
2036
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002037 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002038}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002039
2040bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002041Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002042 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002043 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002044 OverloadingResult OvResult =
2045 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002046 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002047 if (OvResult == OR_Ambiguous)
2048 Diag(From->getSourceRange().getBegin(),
2049 diag::err_typecheck_ambiguous_condition)
2050 << From->getType() << ToType << From->getSourceRange();
2051 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2052 Diag(From->getSourceRange().getBegin(),
2053 diag::err_typecheck_nonviable_condition)
2054 << From->getType() << ToType << From->getSourceRange();
2055 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002056 return false;
John McCallad907772010-01-12 07:18:19 +00002057 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002058 return true;
2059}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002060
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002061/// CompareImplicitConversionSequences - Compare two implicit
2062/// conversion sequences to determine whether one is better than the
2063/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00002064ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002065Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
2066 const ImplicitConversionSequence& ICS2)
2067{
2068 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2069 // conversion sequences (as defined in 13.3.3.1)
2070 // -- a standard conversion sequence (13.3.3.1.1) is a better
2071 // conversion sequence than a user-defined conversion sequence or
2072 // an ellipsis conversion sequence, and
2073 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2074 // conversion sequence than an ellipsis conversion sequence
2075 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002076 //
John McCall0d1da222010-01-12 00:44:57 +00002077 // C++0x [over.best.ics]p10:
2078 // For the purpose of ranking implicit conversion sequences as
2079 // described in 13.3.3.2, the ambiguous conversion sequence is
2080 // treated as a user-defined sequence that is indistinguishable
2081 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002082 if (ICS1.getKindRank() < ICS2.getKindRank())
2083 return ImplicitConversionSequence::Better;
2084 else if (ICS2.getKindRank() < ICS1.getKindRank())
2085 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002086
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002087 // The following checks require both conversion sequences to be of
2088 // the same kind.
2089 if (ICS1.getKind() != ICS2.getKind())
2090 return ImplicitConversionSequence::Indistinguishable;
2091
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002092 // Two implicit conversion sequences of the same form are
2093 // indistinguishable conversion sequences unless one of the
2094 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002095 if (ICS1.isStandard())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002096 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002097 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002098 // User-defined conversion sequence U1 is a better conversion
2099 // sequence than another user-defined conversion sequence U2 if
2100 // they contain the same user-defined conversion function or
2101 // constructor and if the second standard conversion sequence of
2102 // U1 is better than the second standard conversion sequence of
2103 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002104 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002105 ICS2.UserDefined.ConversionFunction)
2106 return CompareStandardConversionSequences(ICS1.UserDefined.After,
2107 ICS2.UserDefined.After);
2108 }
2109
2110 return ImplicitConversionSequence::Indistinguishable;
2111}
2112
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002113static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2114 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2115 Qualifiers Quals;
2116 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2117 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2118 }
2119
2120 return Context.hasSameUnqualifiedType(T1, T2);
2121}
2122
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002123// Per 13.3.3.2p3, compare the given standard conversion sequences to
2124// determine if one is a proper subset of the other.
2125static ImplicitConversionSequence::CompareKind
2126compareStandardConversionSubsets(ASTContext &Context,
2127 const StandardConversionSequence& SCS1,
2128 const StandardConversionSequence& SCS2) {
2129 ImplicitConversionSequence::CompareKind Result
2130 = ImplicitConversionSequence::Indistinguishable;
2131
Douglas Gregore87561a2010-05-23 22:10:15 +00002132 // the identity conversion sequence is considered to be a subsequence of
2133 // any non-identity conversion sequence
2134 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2135 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2136 return ImplicitConversionSequence::Better;
2137 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2138 return ImplicitConversionSequence::Worse;
2139 }
2140
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002141 if (SCS1.Second != SCS2.Second) {
2142 if (SCS1.Second == ICK_Identity)
2143 Result = ImplicitConversionSequence::Better;
2144 else if (SCS2.Second == ICK_Identity)
2145 Result = ImplicitConversionSequence::Worse;
2146 else
2147 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002148 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002149 return ImplicitConversionSequence::Indistinguishable;
2150
2151 if (SCS1.Third == SCS2.Third) {
2152 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2153 : ImplicitConversionSequence::Indistinguishable;
2154 }
2155
2156 if (SCS1.Third == ICK_Identity)
2157 return Result == ImplicitConversionSequence::Worse
2158 ? ImplicitConversionSequence::Indistinguishable
2159 : ImplicitConversionSequence::Better;
2160
2161 if (SCS2.Third == ICK_Identity)
2162 return Result == ImplicitConversionSequence::Better
2163 ? ImplicitConversionSequence::Indistinguishable
2164 : ImplicitConversionSequence::Worse;
2165
2166 return ImplicitConversionSequence::Indistinguishable;
2167}
2168
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002169/// CompareStandardConversionSequences - Compare two standard
2170/// conversion sequences to determine whether one is better than the
2171/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002172ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002173Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
2174 const StandardConversionSequence& SCS2)
2175{
2176 // Standard conversion sequence S1 is a better conversion sequence
2177 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2178
2179 // -- S1 is a proper subsequence of S2 (comparing the conversion
2180 // sequences in the canonical form defined by 13.3.3.1.1,
2181 // excluding any Lvalue Transformation; the identity conversion
2182 // sequence is considered to be a subsequence of any
2183 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002184 if (ImplicitConversionSequence::CompareKind CK
2185 = compareStandardConversionSubsets(Context, SCS1, SCS2))
2186 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002187
2188 // -- the rank of S1 is better than the rank of S2 (by the rules
2189 // defined below), or, if not that,
2190 ImplicitConversionRank Rank1 = SCS1.getRank();
2191 ImplicitConversionRank Rank2 = SCS2.getRank();
2192 if (Rank1 < Rank2)
2193 return ImplicitConversionSequence::Better;
2194 else if (Rank2 < Rank1)
2195 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002196
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002197 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2198 // are indistinguishable unless one of the following rules
2199 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002200
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002201 // A conversion that is not a conversion of a pointer, or
2202 // pointer to member, to bool is better than another conversion
2203 // that is such a conversion.
2204 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2205 return SCS2.isPointerConversionToBool()
2206 ? ImplicitConversionSequence::Better
2207 : ImplicitConversionSequence::Worse;
2208
Douglas Gregor5c407d92008-10-23 00:40:37 +00002209 // C++ [over.ics.rank]p4b2:
2210 //
2211 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002212 // conversion of B* to A* is better than conversion of B* to
2213 // void*, and conversion of A* to void* is better than conversion
2214 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002215 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00002216 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00002217 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00002218 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002219 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2220 // Exactly one of the conversion sequences is a conversion to
2221 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002222 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2223 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002224 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2225 // Neither conversion sequence converts to a void pointer; compare
2226 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002227 if (ImplicitConversionSequence::CompareKind DerivedCK
2228 = CompareDerivedToBaseConversions(SCS1, SCS2))
2229 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002230 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2231 // Both conversion sequences are conversions to void
2232 // pointers. Compare the source types to determine if there's an
2233 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002234 QualType FromType1 = SCS1.getFromType();
2235 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002236
2237 // Adjust the types we're converting from via the array-to-pointer
2238 // conversion, if we need to.
2239 if (SCS1.First == ICK_Array_To_Pointer)
2240 FromType1 = Context.getArrayDecayedType(FromType1);
2241 if (SCS2.First == ICK_Array_To_Pointer)
2242 FromType2 = Context.getArrayDecayedType(FromType2);
2243
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002244 QualType FromPointee1
2245 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2246 QualType FromPointee2
2247 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002248
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002249 if (IsDerivedFrom(FromPointee2, FromPointee1))
2250 return ImplicitConversionSequence::Better;
2251 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2252 return ImplicitConversionSequence::Worse;
2253
2254 // Objective-C++: If one interface is more specific than the
2255 // other, it is the better one.
John McCall8b07ec22010-05-15 11:32:37 +00002256 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2257 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002258 if (FromIface1 && FromIface1) {
2259 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2260 return ImplicitConversionSequence::Better;
2261 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2262 return ImplicitConversionSequence::Worse;
2263 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002264 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002265
2266 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2267 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002268 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002269 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002270 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002271
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002272 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00002273 // C++0x [over.ics.rank]p3b4:
2274 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2275 // implicit object parameter of a non-static member function declared
2276 // without a ref-qualifier, and S1 binds an rvalue reference to an
2277 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00002278 // FIXME: We don't know if we're dealing with the implicit object parameter,
2279 // or if the member function in this case has a ref qualifier.
2280 // (Of course, we don't have ref qualifiers yet.)
2281 if (SCS1.RRefBinding != SCS2.RRefBinding)
2282 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2283 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00002284
2285 // C++ [over.ics.rank]p3b4:
2286 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2287 // which the references refer are the same type except for
2288 // top-level cv-qualifiers, and the type to which the reference
2289 // initialized by S2 refers is more cv-qualified than the type
2290 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002291 QualType T1 = SCS1.getToType(2);
2292 QualType T2 = SCS2.getToType(2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002293 T1 = Context.getCanonicalType(T1);
2294 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002295 Qualifiers T1Quals, T2Quals;
2296 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2297 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2298 if (UnqualT1 == UnqualT2) {
2299 // If the type is an array type, promote the element qualifiers to the type
2300 // for comparison.
2301 if (isa<ArrayType>(T1) && T1Quals)
2302 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2303 if (isa<ArrayType>(T2) && T2Quals)
2304 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002305 if (T2.isMoreQualifiedThan(T1))
2306 return ImplicitConversionSequence::Better;
2307 else if (T1.isMoreQualifiedThan(T2))
2308 return ImplicitConversionSequence::Worse;
2309 }
2310 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002311
2312 return ImplicitConversionSequence::Indistinguishable;
2313}
2314
2315/// CompareQualificationConversions - Compares two standard conversion
2316/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002317/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2318ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002319Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00002320 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002321 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002322 // -- S1 and S2 differ only in their qualification conversion and
2323 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2324 // cv-qualification signature of type T1 is a proper subset of
2325 // the cv-qualification signature of type T2, and S1 is not the
2326 // deprecated string literal array-to-pointer conversion (4.2).
2327 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2328 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2329 return ImplicitConversionSequence::Indistinguishable;
2330
2331 // FIXME: the example in the standard doesn't use a qualification
2332 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002333 QualType T1 = SCS1.getToType(2);
2334 QualType T2 = SCS2.getToType(2);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002335 T1 = Context.getCanonicalType(T1);
2336 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002337 Qualifiers T1Quals, T2Quals;
2338 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2339 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002340
2341 // If the types are the same, we won't learn anything by unwrapped
2342 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002343 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002344 return ImplicitConversionSequence::Indistinguishable;
2345
Chandler Carruth607f38e2009-12-29 07:16:59 +00002346 // If the type is an array type, promote the element qualifiers to the type
2347 // for comparison.
2348 if (isa<ArrayType>(T1) && T1Quals)
2349 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2350 if (isa<ArrayType>(T2) && T2Quals)
2351 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2352
Mike Stump11289f42009-09-09 15:08:12 +00002353 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002354 = ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002355 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002356 // Within each iteration of the loop, we check the qualifiers to
2357 // determine if this still looks like a qualification
2358 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002359 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002360 // until there are no more pointers or pointers-to-members left
2361 // to unwrap. This essentially mimics what
2362 // IsQualificationConversion does, but here we're checking for a
2363 // strict subset of qualifiers.
2364 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2365 // The qualifiers are the same, so this doesn't tell us anything
2366 // about how the sequences rank.
2367 ;
2368 else if (T2.isMoreQualifiedThan(T1)) {
2369 // T1 has fewer qualifiers, so it could be the better sequence.
2370 if (Result == ImplicitConversionSequence::Worse)
2371 // Neither has qualifiers that are a subset of the other's
2372 // qualifiers.
2373 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002374
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002375 Result = ImplicitConversionSequence::Better;
2376 } else if (T1.isMoreQualifiedThan(T2)) {
2377 // T2 has fewer qualifiers, so it could be the better sequence.
2378 if (Result == ImplicitConversionSequence::Better)
2379 // Neither has qualifiers that are a subset of the other's
2380 // qualifiers.
2381 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002382
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002383 Result = ImplicitConversionSequence::Worse;
2384 } else {
2385 // Qualifiers are disjoint.
2386 return ImplicitConversionSequence::Indistinguishable;
2387 }
2388
2389 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002390 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002391 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002392 }
2393
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002394 // Check that the winning standard conversion sequence isn't using
2395 // the deprecated string literal array to pointer conversion.
2396 switch (Result) {
2397 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002398 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002399 Result = ImplicitConversionSequence::Indistinguishable;
2400 break;
2401
2402 case ImplicitConversionSequence::Indistinguishable:
2403 break;
2404
2405 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002406 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002407 Result = ImplicitConversionSequence::Indistinguishable;
2408 break;
2409 }
2410
2411 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002412}
2413
Douglas Gregor5c407d92008-10-23 00:40:37 +00002414/// CompareDerivedToBaseConversions - Compares two standard conversion
2415/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002416/// various kinds of derived-to-base conversions (C++
2417/// [over.ics.rank]p4b3). As part of these checks, we also look at
2418/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002419ImplicitConversionSequence::CompareKind
2420Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2421 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002422 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002423 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002424 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002425 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002426
2427 // Adjust the types we're converting from via the array-to-pointer
2428 // conversion, if we need to.
2429 if (SCS1.First == ICK_Array_To_Pointer)
2430 FromType1 = Context.getArrayDecayedType(FromType1);
2431 if (SCS2.First == ICK_Array_To_Pointer)
2432 FromType2 = Context.getArrayDecayedType(FromType2);
2433
2434 // Canonicalize all of the types.
2435 FromType1 = Context.getCanonicalType(FromType1);
2436 ToType1 = Context.getCanonicalType(ToType1);
2437 FromType2 = Context.getCanonicalType(FromType2);
2438 ToType2 = Context.getCanonicalType(ToType2);
2439
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002440 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002441 //
2442 // If class B is derived directly or indirectly from class A and
2443 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002444 //
2445 // For Objective-C, we let A, B, and C also be Objective-C
2446 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002447
2448 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002449 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002450 SCS2.Second == ICK_Pointer_Conversion &&
2451 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2452 FromType1->isPointerType() && FromType2->isPointerType() &&
2453 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002454 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002455 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002456 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002457 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002458 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002459 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002460 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002461 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002462
John McCall8b07ec22010-05-15 11:32:37 +00002463 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2464 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2465 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2466 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002467
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002468 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002469 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2470 if (IsDerivedFrom(ToPointee1, ToPointee2))
2471 return ImplicitConversionSequence::Better;
2472 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2473 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002474
2475 if (ToIface1 && ToIface2) {
2476 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2477 return ImplicitConversionSequence::Better;
2478 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2479 return ImplicitConversionSequence::Worse;
2480 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002481 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002482
2483 // -- conversion of B* to A* is better than conversion of C* to A*,
2484 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2485 if (IsDerivedFrom(FromPointee2, FromPointee1))
2486 return ImplicitConversionSequence::Better;
2487 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2488 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002489
Douglas Gregor237f96c2008-11-26 23:31:11 +00002490 if (FromIface1 && FromIface2) {
2491 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2492 return ImplicitConversionSequence::Better;
2493 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2494 return ImplicitConversionSequence::Worse;
2495 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002496 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002497 }
2498
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002499 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002500 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2501 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2502 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2503 const MemberPointerType * FromMemPointer1 =
2504 FromType1->getAs<MemberPointerType>();
2505 const MemberPointerType * ToMemPointer1 =
2506 ToType1->getAs<MemberPointerType>();
2507 const MemberPointerType * FromMemPointer2 =
2508 FromType2->getAs<MemberPointerType>();
2509 const MemberPointerType * ToMemPointer2 =
2510 ToType2->getAs<MemberPointerType>();
2511 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2512 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2513 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2514 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2515 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2516 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2517 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2518 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002519 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002520 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2521 if (IsDerivedFrom(ToPointee1, ToPointee2))
2522 return ImplicitConversionSequence::Worse;
2523 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2524 return ImplicitConversionSequence::Better;
2525 }
2526 // conversion of B::* to C::* is better than conversion of A::* to C::*
2527 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2528 if (IsDerivedFrom(FromPointee1, FromPointee2))
2529 return ImplicitConversionSequence::Better;
2530 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2531 return ImplicitConversionSequence::Worse;
2532 }
2533 }
2534
Douglas Gregor5ab11652010-04-17 22:01:05 +00002535 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002536 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002537 // -- binding of an expression of type C to a reference of type
2538 // B& is better than binding an expression of type C to a
2539 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002540 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2541 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002542 if (IsDerivedFrom(ToType1, ToType2))
2543 return ImplicitConversionSequence::Better;
2544 else if (IsDerivedFrom(ToType2, ToType1))
2545 return ImplicitConversionSequence::Worse;
2546 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002547
Douglas Gregor2fe98832008-11-03 19:09:14 +00002548 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002549 // -- binding of an expression of type B to a reference of type
2550 // A& is better than binding an expression of type C to a
2551 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002552 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2553 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002554 if (IsDerivedFrom(FromType2, FromType1))
2555 return ImplicitConversionSequence::Better;
2556 else if (IsDerivedFrom(FromType1, FromType2))
2557 return ImplicitConversionSequence::Worse;
2558 }
2559 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002560
Douglas Gregor5c407d92008-10-23 00:40:37 +00002561 return ImplicitConversionSequence::Indistinguishable;
2562}
2563
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002564/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2565/// determine whether they are reference-related,
2566/// reference-compatible, reference-compatible with added
2567/// qualification, or incompatible, for use in C++ initialization by
2568/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2569/// type, and the first type (T1) is the pointee type of the reference
2570/// type being initialized.
2571Sema::ReferenceCompareResult
2572Sema::CompareReferenceRelationship(SourceLocation Loc,
2573 QualType OrigT1, QualType OrigT2,
2574 bool& DerivedToBase) {
2575 assert(!OrigT1->isReferenceType() &&
2576 "T1 must be the pointee type of the reference type");
2577 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2578
2579 QualType T1 = Context.getCanonicalType(OrigT1);
2580 QualType T2 = Context.getCanonicalType(OrigT2);
2581 Qualifiers T1Quals, T2Quals;
2582 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2583 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2584
2585 // C++ [dcl.init.ref]p4:
2586 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2587 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2588 // T1 is a base class of T2.
2589 if (UnqualT1 == UnqualT2)
2590 DerivedToBase = false;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002591 else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002592 IsDerivedFrom(UnqualT2, UnqualT1))
2593 DerivedToBase = true;
2594 else
2595 return Ref_Incompatible;
2596
2597 // At this point, we know that T1 and T2 are reference-related (at
2598 // least).
2599
2600 // If the type is an array type, promote the element qualifiers to the type
2601 // for comparison.
2602 if (isa<ArrayType>(T1) && T1Quals)
2603 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2604 if (isa<ArrayType>(T2) && T2Quals)
2605 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2606
2607 // C++ [dcl.init.ref]p4:
2608 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2609 // reference-related to T2 and cv1 is the same cv-qualification
2610 // as, or greater cv-qualification than, cv2. For purposes of
2611 // overload resolution, cases for which cv1 is greater
2612 // cv-qualification than cv2 are identified as
2613 // reference-compatible with added qualification (see 13.3.3.2).
2614 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2615 return Ref_Compatible;
2616 else if (T1.isMoreQualifiedThan(T2))
2617 return Ref_Compatible_With_Added_Qualification;
2618 else
2619 return Ref_Related;
2620}
2621
Sebastian Redld92badf2010-06-30 18:13:39 +00002622/// \brief Look for a user-defined conversion to an lvalue reference-compatible
2623/// with DeclType. Return true if something definite is found.
2624static bool
2625FindConversionToLValue(Sema &S, ImplicitConversionSequence &ICS,
2626 QualType DeclType, SourceLocation DeclLoc,
2627 Expr *Init, QualType T2, bool AllowExplicit) {
2628 assert(T2->isRecordType() && "Can only find conversions of record types.");
2629 CXXRecordDecl *T2RecordDecl
2630 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2631
2632 OverloadCandidateSet CandidateSet(DeclLoc);
2633 const UnresolvedSetImpl *Conversions
2634 = T2RecordDecl->getVisibleConversionFunctions();
2635 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2636 E = Conversions->end(); I != E; ++I) {
2637 NamedDecl *D = *I;
2638 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2639 if (isa<UsingShadowDecl>(D))
2640 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2641
2642 FunctionTemplateDecl *ConvTemplate
2643 = dyn_cast<FunctionTemplateDecl>(D);
2644 CXXConversionDecl *Conv;
2645 if (ConvTemplate)
2646 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2647 else
2648 Conv = cast<CXXConversionDecl>(D);
2649
2650 // If the conversion function doesn't return a reference type,
2651 // it can't be considered for this conversion. An rvalue reference
2652 // is only acceptable if its referencee is a function type.
2653 const ReferenceType *RefType =
2654 Conv->getConversionType()->getAs<ReferenceType>();
2655 if (RefType && (RefType->isLValueReferenceType() ||
2656 RefType->getPointeeType()->isFunctionType()) &&
2657 (AllowExplicit || !Conv->isExplicit())) {
2658 if (ConvTemplate)
2659 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2660 Init, DeclType, CandidateSet);
2661 else
2662 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2663 DeclType, CandidateSet);
2664 }
2665 }
2666
2667 OverloadCandidateSet::iterator Best;
2668 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2669 case OR_Success:
2670 // C++ [over.ics.ref]p1:
2671 //
2672 // [...] If the parameter binds directly to the result of
2673 // applying a conversion function to the argument
2674 // expression, the implicit conversion sequence is a
2675 // user-defined conversion sequence (13.3.3.1.2), with the
2676 // second standard conversion sequence either an identity
2677 // conversion or, if the conversion function returns an
2678 // entity of a type that is a derived class of the parameter
2679 // type, a derived-to-base Conversion.
2680 if (!Best->FinalConversion.DirectBinding)
2681 return false;
2682
2683 ICS.setUserDefined();
2684 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2685 ICS.UserDefined.After = Best->FinalConversion;
2686 ICS.UserDefined.ConversionFunction = Best->Function;
2687 ICS.UserDefined.EllipsisConversion = false;
2688 assert(ICS.UserDefined.After.ReferenceBinding &&
2689 ICS.UserDefined.After.DirectBinding &&
2690 "Expected a direct reference binding!");
2691 return true;
2692
2693 case OR_Ambiguous:
2694 ICS.setAmbiguous();
2695 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2696 Cand != CandidateSet.end(); ++Cand)
2697 if (Cand->Viable)
2698 ICS.Ambiguous.addConversion(Cand->Function);
2699 return true;
2700
2701 case OR_No_Viable_Function:
2702 case OR_Deleted:
2703 // There was no suitable conversion, or we found a deleted
2704 // conversion; continue with other checks.
2705 return false;
2706 }
Eric Christopheraba9fb22010-06-30 18:36:32 +00002707
2708 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002709}
2710
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002711/// \brief Compute an implicit conversion sequence for reference
2712/// initialization.
2713static ImplicitConversionSequence
2714TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2715 SourceLocation DeclLoc,
2716 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002717 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002718 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2719
2720 // Most paths end in a failed conversion.
2721 ImplicitConversionSequence ICS;
2722 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2723
2724 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2725 QualType T2 = Init->getType();
2726
2727 // If the initializer is the address of an overloaded function, try
2728 // to resolve the overloaded function. If all goes well, T2 is the
2729 // type of the resulting function.
2730 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2731 DeclAccessPair Found;
2732 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2733 false, Found))
2734 T2 = Fn->getType();
2735 }
2736
2737 // Compute some basic properties of the types and the initializer.
2738 bool isRValRef = DeclType->isRValueReferenceType();
2739 bool DerivedToBase = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002740 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002741 Sema::ReferenceCompareResult RefRelationship
2742 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
2743
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002744
Sebastian Redld92badf2010-06-30 18:13:39 +00002745 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00002746 // A reference to type "cv1 T1" is initialized by an expression
2747 // of type "cv2 T2" as follows:
2748
Sebastian Redld92badf2010-06-30 18:13:39 +00002749 // -- If reference is an lvalue reference and the initializer expression
2750 // The next bullet point (T1 is a function) is pretty much equivalent to this
2751 // one, so it's handled here.
2752 if (!isRValRef || T1->isFunctionType()) {
2753 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2754 // reference-compatible with "cv2 T2," or
2755 //
2756 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2757 if (InitCategory.isLValue() &&
2758 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002759 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00002760 // When a parameter of reference type binds directly (8.5.3)
2761 // to an argument expression, the implicit conversion sequence
2762 // is the identity conversion, unless the argument expression
2763 // has a type that is a derived class of the parameter type,
2764 // in which case the implicit conversion sequence is a
2765 // derived-to-base Conversion (13.3.3.1).
2766 ICS.setStandard();
2767 ICS.Standard.First = ICK_Identity;
2768 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2769 ICS.Standard.Third = ICK_Identity;
2770 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2771 ICS.Standard.setToType(0, T2);
2772 ICS.Standard.setToType(1, T1);
2773 ICS.Standard.setToType(2, T1);
2774 ICS.Standard.ReferenceBinding = true;
2775 ICS.Standard.DirectBinding = true;
2776 ICS.Standard.RRefBinding = isRValRef;
2777 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002778
Sebastian Redld92badf2010-06-30 18:13:39 +00002779 // Nothing more to do: the inaccessibility/ambiguity check for
2780 // derived-to-base conversions is suppressed when we're
2781 // computing the implicit conversion sequence (C++
2782 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002783 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00002784 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002785
Sebastian Redld92badf2010-06-30 18:13:39 +00002786 // -- has a class type (i.e., T2 is a class type), where T1 is
2787 // not reference-related to T2, and can be implicitly
2788 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2789 // is reference-compatible with "cv3 T3" 92) (this
2790 // conversion is selected by enumerating the applicable
2791 // conversion functions (13.3.1.6) and choosing the best
2792 // one through overload resolution (13.3)),
2793 if (!SuppressUserConversions && T2->isRecordType() &&
2794 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2795 RefRelationship == Sema::Ref_Incompatible) {
2796 if (FindConversionToLValue(S, ICS, DeclType, DeclLoc,
2797 Init, T2, AllowExplicit))
2798 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002799 }
2800 }
2801
Sebastian Redld92badf2010-06-30 18:13:39 +00002802 // -- Otherwise, the reference shall be an lvalue reference to a
2803 // non-volatile const type (i.e., cv1 shall be const), or the reference
2804 // shall be an rvalue reference and the initializer expression shall be
2805 // an rvalue or have a function type.
Douglas Gregor870f3742010-04-18 09:22:00 +00002806 //
2807 // We actually handle one oddity of C++ [over.ics.ref] at this
2808 // point, which is that, due to p2 (which short-circuits reference
2809 // binding by only attempting a simple conversion for non-direct
2810 // bindings) and p3's strange wording, we allow a const volatile
2811 // reference to bind to an rvalue. Hence the check for the presence
2812 // of "const" rather than checking for "const" being the only
2813 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00002814 // This is also the point where rvalue references and lvalue inits no longer
2815 // go together.
2816 if ((!isRValRef && !T1.isConstQualified()) ||
2817 (isRValRef && InitCategory.isLValue()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002818 return ICS;
2819
Sebastian Redld92badf2010-06-30 18:13:39 +00002820 // -- If T1 is a function type, then
2821 // -- if T2 is the same type as T1, the reference is bound to the
2822 // initializer expression lvalue;
2823 // -- if T2 is a class type and the initializer expression can be
2824 // implicitly converted to an lvalue of type T1 [...], the
2825 // reference is bound to the function lvalue that is the result
2826 // of the conversion;
2827 // This is the same as for the lvalue case above, so it was handled there.
2828 // -- otherwise, the program is ill-formed.
2829 // This is the one difference to the lvalue case.
2830 if (T1->isFunctionType())
2831 return ICS;
2832
2833 // -- Otherwise, if T2 is a class type and
Douglas Gregorf93df192010-04-18 08:46:23 +00002834 // -- the initializer expression is an rvalue and "cv1 T1"
2835 // is reference-compatible with "cv2 T2," or
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002836 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002837 // -- T1 is not reference-related to T2 and the initializer
2838 // expression can be implicitly converted to an rvalue
2839 // of type "cv3 T3" (this conversion is selected by
2840 // enumerating the applicable conversion functions
2841 // (13.3.1.6) and choosing the best one through overload
2842 // resolution (13.3)),
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002843 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002844 // then the reference is bound to the initializer
2845 // expression rvalue in the first case and to the object
2846 // that is the result of the conversion in the second case
2847 // (or, in either case, to the appropriate base class
2848 // subobject of the object).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002849 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002850 // We're only checking the first case here, which is a direct
2851 // binding in C++0x but not in C++03.
Sebastian Redld92badf2010-06-30 18:13:39 +00002852 if (InitCategory.isRValue() && T2->isRecordType() &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002853 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2854 ICS.setStandard();
2855 ICS.Standard.First = ICK_Identity;
2856 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2857 ICS.Standard.Third = ICK_Identity;
2858 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2859 ICS.Standard.setToType(0, T2);
2860 ICS.Standard.setToType(1, T1);
2861 ICS.Standard.setToType(2, T1);
2862 ICS.Standard.ReferenceBinding = true;
Douglas Gregorf93df192010-04-18 08:46:23 +00002863 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002864 ICS.Standard.RRefBinding = isRValRef;
2865 ICS.Standard.CopyConstructor = 0;
2866 return ICS;
2867 }
2868
2869 // -- Otherwise, a temporary of type "cv1 T1" is created and
2870 // initialized from the initializer expression using the
2871 // rules for a non-reference copy initialization (8.5). The
2872 // reference is then bound to the temporary. If T1 is
2873 // reference-related to T2, cv1 must be the same
2874 // cv-qualification as, or greater cv-qualification than,
2875 // cv2; otherwise, the program is ill-formed.
2876 if (RefRelationship == Sema::Ref_Related) {
2877 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2878 // we would be reference-compatible or reference-compatible with
2879 // added qualification. But that wasn't the case, so the reference
2880 // initialization fails.
2881 return ICS;
2882 }
2883
2884 // If at least one of the types is a class type, the types are not
2885 // related, and we aren't allowed any user conversions, the
2886 // reference binding fails. This case is important for breaking
2887 // recursion, since TryImplicitConversion below will attempt to
2888 // create a temporary through the use of a copy constructor.
2889 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2890 (T1->isRecordType() || T2->isRecordType()))
2891 return ICS;
2892
2893 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002894 // When a parameter of reference type is not bound directly to
2895 // an argument expression, the conversion sequence is the one
2896 // required to convert the argument expression to the
2897 // underlying type of the reference according to
2898 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2899 // to copy-initializing a temporary of the underlying type with
2900 // the argument expression. Any difference in top-level
2901 // cv-qualification is subsumed by the initialization itself
2902 // and does not constitute a conversion.
2903 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2904 /*AllowExplicit=*/false,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002905 /*InOverloadResolution=*/false);
2906
2907 // Of course, that's still a reference binding.
2908 if (ICS.isStandard()) {
2909 ICS.Standard.ReferenceBinding = true;
2910 ICS.Standard.RRefBinding = isRValRef;
2911 } else if (ICS.isUserDefined()) {
2912 ICS.UserDefined.After.ReferenceBinding = true;
2913 ICS.UserDefined.After.RRefBinding = isRValRef;
2914 }
2915 return ICS;
2916}
2917
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002918/// TryCopyInitialization - Try to copy-initialize a value of type
2919/// ToType from the expression From. Return the implicit conversion
2920/// sequence required to pass this argument, which may be a bad
2921/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002922/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00002923/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002924static ImplicitConversionSequence
2925TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00002926 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002927 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002928 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002929 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002930 /*FIXME:*/From->getLocStart(),
2931 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002932 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002933
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002934 return S.TryImplicitConversion(From, ToType,
2935 SuppressUserConversions,
2936 /*AllowExplicit=*/false,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002937 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002938}
2939
Douglas Gregor436424c2008-11-18 23:14:02 +00002940/// TryObjectArgumentInitialization - Try to initialize the object
2941/// parameter of the given member function (@c Method) from the
2942/// expression @p From.
2943ImplicitConversionSequence
John McCall47000992010-01-14 03:28:57 +00002944Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall6e9f8f62009-12-03 04:06:58 +00002945 CXXMethodDecl *Method,
2946 CXXRecordDecl *ActingContext) {
2947 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002948 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2949 // const volatile object.
2950 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2951 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2952 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002953
2954 // Set up the conversion sequence as a "bad" conversion, to allow us
2955 // to exit early.
2956 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00002957
2958 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00002959 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002960 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002961 FromType = PT->getPointeeType();
2962
2963 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002964
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002965 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002966 // where X is the class of which the function is a member
2967 // (C++ [over.match.funcs]p4). However, when finding an implicit
2968 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002969 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002970 // (C++ [over.match.funcs]p5). We perform a simplified version of
2971 // reference binding here, that allows class rvalues to bind to
2972 // non-constant references.
2973
2974 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2975 // with the implicit object parameter (C++ [over.match.funcs]p5).
2976 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002977 if (ImplicitParamType.getCVRQualifiers()
2978 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00002979 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00002980 ICS.setBad(BadConversionSequence::bad_qualifiers,
2981 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002982 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002983 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002984
2985 // Check that we have either the same type or a derived type. It
2986 // affects the conversion rank.
2987 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00002988 ImplicitConversionKind SecondKind;
2989 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2990 SecondKind = ICK_Identity;
2991 } else if (IsDerivedFrom(FromType, ClassType))
2992 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00002993 else {
John McCall65eb8792010-02-25 01:37:24 +00002994 ICS.setBad(BadConversionSequence::unrelated_class,
2995 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002996 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002997 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002998
2999 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003000 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003001 ICS.Standard.setAsIdentityConversion();
3002 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003003 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003004 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003005 ICS.Standard.ReferenceBinding = true;
3006 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00003007 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003008 return ICS;
3009}
3010
3011/// PerformObjectArgumentInitialization - Perform initialization of
3012/// the implicit object parameter for the given Method with the given
3013/// expression.
3014bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003015Sema::PerformObjectArgumentInitialization(Expr *&From,
3016 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003017 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003018 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003019 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003020 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003021 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003022
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003023 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003024 FromRecordType = PT->getPointeeType();
3025 DestType = Method->getThisType(Context);
3026 } else {
3027 FromRecordType = From->getType();
3028 DestType = ImplicitParamRecordType;
3029 }
3030
John McCall6e9f8f62009-12-03 04:06:58 +00003031 // Note that we always use the true parent context when performing
3032 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003033 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00003034 = TryObjectArgumentInitialization(From->getType(), Method,
3035 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00003036 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00003037 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003038 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003039 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003040
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003041 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00003042 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00003043
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003044 if (!Context.hasSameType(From->getType(), DestType))
Anders Carlsson0c509ee2010-04-24 16:57:13 +00003045 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003046 From->getType()->isPointerType() ?
3047 ImplicitCastExpr::RValue : ImplicitCastExpr::LValue);
Douglas Gregor436424c2008-11-18 23:14:02 +00003048 return false;
3049}
3050
Douglas Gregor5fb53972009-01-14 15:45:31 +00003051/// TryContextuallyConvertToBool - Attempt to contextually convert the
3052/// expression From to bool (C++0x [conv]p3).
3053ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003054 // FIXME: This is pretty broken.
Mike Stump11289f42009-09-09 15:08:12 +00003055 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003056 // FIXME: Are these flags correct?
3057 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003058 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00003059 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003060}
3061
3062/// PerformContextuallyConvertToBool - Perform a contextual conversion
3063/// of the expression From to bool (C++0x [conv]p3).
3064bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
3065 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00003066 if (!ICS.isBad())
3067 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003068
Fariborz Jahanian76197412009-11-18 18:26:29 +00003069 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003070 return Diag(From->getSourceRange().getBegin(),
3071 diag::err_typecheck_bool_condition)
3072 << From->getType() << From->getSourceRange();
3073 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003074}
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003075
3076/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3077/// expression From to 'id'.
3078ImplicitConversionSequence Sema::TryContextuallyConvertToObjCId(Expr *From) {
John McCall8b07ec22010-05-15 11:32:37 +00003079 QualType Ty = Context.getObjCIdType();
3080 return TryImplicitConversion(From, Ty,
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003081 // FIXME: Are these flags correct?
3082 /*SuppressUserConversions=*/false,
3083 /*AllowExplicit=*/true,
3084 /*InOverloadResolution=*/false);
3085}
3086
3087/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3088/// of the expression From to 'id'.
3089bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCall8b07ec22010-05-15 11:32:37 +00003090 QualType Ty = Context.getObjCIdType();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003091 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(From);
3092 if (!ICS.isBad())
3093 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3094 return true;
3095}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003096
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003097/// \brief Attempt to convert the given expression to an integral or
3098/// enumeration type.
3099///
3100/// This routine will attempt to convert an expression of class type to an
3101/// integral or enumeration type, if that class type only has a single
3102/// conversion to an integral or enumeration type.
3103///
Douglas Gregor4799d032010-06-30 00:20:43 +00003104/// \param Loc The source location of the construct that requires the
3105/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003106///
Douglas Gregor4799d032010-06-30 00:20:43 +00003107/// \param FromE The expression we're converting from.
3108///
3109/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3110/// have integral or enumeration type.
3111///
3112/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3113/// incomplete class type.
3114///
3115/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3116/// explicit conversion function (because no implicit conversion functions
3117/// were available). This is a recovery mode.
3118///
3119/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3120/// showing which conversion was picked.
3121///
3122/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3123/// conversion function that could convert to integral or enumeration type.
3124///
3125/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3126/// usable conversion function.
3127///
3128/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3129/// function, which may be an extension in this case.
3130///
3131/// \returns The expression, converted to an integral or enumeration type if
3132/// successful.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003133Sema::OwningExprResult
3134Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, ExprArg FromE,
3135 const PartialDiagnostic &NotIntDiag,
3136 const PartialDiagnostic &IncompleteDiag,
3137 const PartialDiagnostic &ExplicitConvDiag,
3138 const PartialDiagnostic &ExplicitConvNote,
3139 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003140 const PartialDiagnostic &AmbigNote,
3141 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003142 Expr *From = static_cast<Expr *>(FromE.get());
3143
3144 // We can't perform any more checking for type-dependent expressions.
3145 if (From->isTypeDependent())
3146 return move(FromE);
3147
3148 // If the expression already has integral or enumeration type, we're golden.
3149 QualType T = From->getType();
3150 if (T->isIntegralOrEnumerationType())
3151 return move(FromE);
3152
3153 // FIXME: Check for missing '()' if T is a function type?
3154
3155 // If we don't have a class type in C++, there's no way we can get an
3156 // expression of integral or enumeration type.
3157 const RecordType *RecordTy = T->getAs<RecordType>();
3158 if (!RecordTy || !getLangOptions().CPlusPlus) {
3159 Diag(Loc, NotIntDiag)
3160 << T << From->getSourceRange();
Douglas Gregor5823da32010-06-29 23:25:20 +00003161 return move(FromE);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003162 }
3163
3164 // We must have a complete class type.
3165 if (RequireCompleteType(Loc, T, IncompleteDiag))
Douglas Gregor4799d032010-06-30 00:20:43 +00003166 return move(FromE);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003167
3168 // Look for a conversion to an integral or enumeration type.
3169 UnresolvedSet<4> ViableConversions;
3170 UnresolvedSet<4> ExplicitConversions;
3171 const UnresolvedSetImpl *Conversions
3172 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3173
3174 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3175 E = Conversions->end();
3176 I != E;
3177 ++I) {
3178 if (CXXConversionDecl *Conversion
3179 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3180 if (Conversion->getConversionType().getNonReferenceType()
3181 ->isIntegralOrEnumerationType()) {
3182 if (Conversion->isExplicit())
3183 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3184 else
3185 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3186 }
3187 }
3188
3189 switch (ViableConversions.size()) {
3190 case 0:
3191 if (ExplicitConversions.size() == 1) {
3192 DeclAccessPair Found = ExplicitConversions[0];
3193 CXXConversionDecl *Conversion
3194 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3195
3196 // The user probably meant to invoke the given explicit
3197 // conversion; use it.
3198 QualType ConvTy
3199 = Conversion->getConversionType().getNonReferenceType();
3200 std::string TypeStr;
3201 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3202
3203 Diag(Loc, ExplicitConvDiag)
3204 << T << ConvTy
3205 << FixItHint::CreateInsertion(From->getLocStart(),
3206 "static_cast<" + TypeStr + ">(")
3207 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3208 ")");
3209 Diag(Conversion->getLocation(), ExplicitConvNote)
3210 << ConvTy->isEnumeralType() << ConvTy;
3211
3212 // If we aren't in a SFINAE context, build a call to the
3213 // explicit conversion function.
3214 if (isSFINAEContext())
3215 return ExprError();
3216
3217 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
3218 From = BuildCXXMemberCallExpr(FromE.takeAs<Expr>(), Found, Conversion);
3219 FromE = Owned(From);
3220 }
3221
3222 // We'll complain below about a non-integral condition type.
3223 break;
3224
3225 case 1: {
3226 // Apply this conversion.
3227 DeclAccessPair Found = ViableConversions[0];
3228 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor4799d032010-06-30 00:20:43 +00003229
3230 CXXConversionDecl *Conversion
3231 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3232 QualType ConvTy
3233 = Conversion->getConversionType().getNonReferenceType();
3234 if (ConvDiag.getDiagID()) {
3235 if (isSFINAEContext())
3236 return ExprError();
3237
3238 Diag(Loc, ConvDiag)
3239 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3240 }
3241
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003242 From = BuildCXXMemberCallExpr(FromE.takeAs<Expr>(), Found,
3243 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
3244 FromE = Owned(From);
3245 break;
3246 }
3247
3248 default:
3249 Diag(Loc, AmbigDiag)
3250 << T << From->getSourceRange();
3251 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3252 CXXConversionDecl *Conv
3253 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3254 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3255 Diag(Conv->getLocation(), AmbigNote)
3256 << ConvTy->isEnumeralType() << ConvTy;
3257 }
Douglas Gregor5823da32010-06-29 23:25:20 +00003258 return move(FromE);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003259 }
3260
Douglas Gregor5823da32010-06-29 23:25:20 +00003261 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003262 Diag(Loc, NotIntDiag)
3263 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003264
3265 return move(FromE);
3266}
3267
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003268/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003269/// candidate functions, using the given function call arguments. If
3270/// @p SuppressUserConversions, then don't allow user-defined
3271/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003272///
3273/// \para PartialOverloading true if we are performing "partial" overloading
3274/// based on an incomplete set of function arguments. This feature is used by
3275/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003276void
3277Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003278 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003279 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003280 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003281 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003282 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003283 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003284 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003285 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003286 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003287 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003288
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003289 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003290 if (!isa<CXXConstructorDecl>(Method)) {
3291 // If we get here, it's because we're calling a member function
3292 // that is named without a member access expression (e.g.,
3293 // "this->f") that was either written explicitly or created
3294 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003295 // function, e.g., X::f(). We use an empty type for the implied
3296 // object argument (C++ [over.call.func]p3), and the acting context
3297 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003298 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00003299 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003300 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003301 return;
3302 }
3303 // We treat a constructor like a non-member function, since its object
3304 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003305 }
3306
Douglas Gregorff7028a2009-11-13 23:59:09 +00003307 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003308 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003309
Douglas Gregor27381f32009-11-23 12:27:39 +00003310 // Overload resolution is always an unevaluated context.
3311 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3312
Douglas Gregorffe14e32009-11-14 01:20:54 +00003313 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3314 // C++ [class.copy]p3:
3315 // A member function template is never instantiated to perform the copy
3316 // of a class object to an object of its class type.
3317 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3318 if (NumArgs == 1 &&
3319 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003320 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3321 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003322 return;
3323 }
3324
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003325 // Add this candidate
3326 CandidateSet.push_back(OverloadCandidate());
3327 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003328 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003329 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003330 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003331 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003332 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003333
3334 unsigned NumArgsInProto = Proto->getNumArgs();
3335
3336 // (C++ 13.3.2p2): A candidate function having fewer than m
3337 // parameters is viable only if it has an ellipsis in its parameter
3338 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00003339 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3340 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003341 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003342 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003343 return;
3344 }
3345
3346 // (C++ 13.3.2p2): A candidate function having more than m parameters
3347 // is viable only if the (m+1)st parameter has a default argument
3348 // (8.3.6). For the purposes of overload resolution, the
3349 // parameter list is truncated on the right, so that there are
3350 // exactly m parameters.
3351 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003352 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003353 // Not enough arguments.
3354 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003355 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003356 return;
3357 }
3358
3359 // Determine the implicit conversion sequences for each of the
3360 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003361 Candidate.Conversions.resize(NumArgs);
3362 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3363 if (ArgIdx < NumArgsInProto) {
3364 // (C++ 13.3.2p3): for F to be a viable function, there shall
3365 // exist for each argument an implicit conversion sequence
3366 // (13.3.3.1) that converts that argument to the corresponding
3367 // parameter of F.
3368 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003369 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003370 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00003371 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003372 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003373 if (Candidate.Conversions[ArgIdx].isBad()) {
3374 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003375 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003376 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003377 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003378 } else {
3379 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3380 // argument for which there is no corresponding parameter is
3381 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003382 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003383 }
3384 }
3385}
3386
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003387/// \brief Add all of the function declarations in the given function set to
3388/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003389void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003390 Expr **Args, unsigned NumArgs,
3391 OverloadCandidateSet& CandidateSet,
3392 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003393 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003394 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3395 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003396 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003397 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003398 cast<CXXMethodDecl>(FD)->getParent(),
3399 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003400 CandidateSet, SuppressUserConversions);
3401 else
John McCalla0296f72010-03-19 07:35:19 +00003402 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003403 SuppressUserConversions);
3404 } else {
John McCalla0296f72010-03-19 07:35:19 +00003405 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003406 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3407 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003408 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003409 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003410 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003411 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003412 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003413 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003414 else
John McCalla0296f72010-03-19 07:35:19 +00003415 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003416 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003417 Args, NumArgs, CandidateSet,
3418 SuppressUserConversions);
3419 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003420 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003421}
3422
John McCallf0f1cf02009-11-17 07:50:12 +00003423/// AddMethodCandidate - Adds a named decl (which is some kind of
3424/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003425void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003426 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00003427 Expr **Args, unsigned NumArgs,
3428 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003429 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003430 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003431 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003432
3433 if (isa<UsingShadowDecl>(Decl))
3434 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3435
3436 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3437 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3438 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003439 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3440 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003441 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003442 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003443 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003444 } else {
John McCalla0296f72010-03-19 07:35:19 +00003445 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00003446 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003447 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003448 }
3449}
3450
Douglas Gregor436424c2008-11-18 23:14:02 +00003451/// AddMethodCandidate - Adds the given C++ member function to the set
3452/// of candidate functions, using the given function call arguments
3453/// and the object argument (@c Object). For example, in a call
3454/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3455/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3456/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003457/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003458void
John McCalla0296f72010-03-19 07:35:19 +00003459Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003460 CXXRecordDecl *ActingContext, QualType ObjectType,
3461 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003462 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003463 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003464 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003465 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003466 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003467 assert(!isa<CXXConstructorDecl>(Method) &&
3468 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003469
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003470 if (!CandidateSet.isNewCandidate(Method))
3471 return;
3472
Douglas Gregor27381f32009-11-23 12:27:39 +00003473 // Overload resolution is always an unevaluated context.
3474 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3475
Douglas Gregor436424c2008-11-18 23:14:02 +00003476 // Add this candidate
3477 CandidateSet.push_back(OverloadCandidate());
3478 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003479 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003480 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003481 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003482 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003483
3484 unsigned NumArgsInProto = Proto->getNumArgs();
3485
3486 // (C++ 13.3.2p2): A candidate function having fewer than m
3487 // parameters is viable only if it has an ellipsis in its parameter
3488 // list (8.3.5).
3489 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3490 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003491 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003492 return;
3493 }
3494
3495 // (C++ 13.3.2p2): A candidate function having more than m parameters
3496 // is viable only if the (m+1)st parameter has a default argument
3497 // (8.3.6). For the purposes of overload resolution, the
3498 // parameter list is truncated on the right, so that there are
3499 // exactly m parameters.
3500 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3501 if (NumArgs < MinRequiredArgs) {
3502 // Not enough arguments.
3503 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003504 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003505 return;
3506 }
3507
3508 Candidate.Viable = true;
3509 Candidate.Conversions.resize(NumArgs + 1);
3510
John McCall6e9f8f62009-12-03 04:06:58 +00003511 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003512 // The implicit object argument is ignored.
3513 Candidate.IgnoreObjectArgument = true;
3514 else {
3515 // Determine the implicit conversion sequence for the object
3516 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00003517 Candidate.Conversions[0]
3518 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003519 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003520 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003521 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003522 return;
3523 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003524 }
3525
3526 // Determine the implicit conversion sequences for each of the
3527 // arguments.
3528 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3529 if (ArgIdx < NumArgsInProto) {
3530 // (C++ 13.3.2p3): for F to be a viable function, there shall
3531 // exist for each argument an implicit conversion sequence
3532 // (13.3.3.1) that converts that argument to the corresponding
3533 // parameter of F.
3534 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003535 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003536 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003537 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003538 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003539 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003540 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003541 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003542 break;
3543 }
3544 } else {
3545 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3546 // argument for which there is no corresponding parameter is
3547 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003548 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003549 }
3550 }
3551}
Douglas Gregor3626a5c2010-05-08 17:41:32 +00003552
Douglas Gregor97628d62009-08-21 00:16:32 +00003553/// \brief Add a C++ member function template as a candidate to the candidate
3554/// set, using template argument deduction to produce an appropriate member
3555/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003556void
Douglas Gregor97628d62009-08-21 00:16:32 +00003557Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003558 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003559 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003560 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003561 QualType ObjectType,
3562 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003563 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003564 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003565 if (!CandidateSet.isNewCandidate(MethodTmpl))
3566 return;
3567
Douglas Gregor97628d62009-08-21 00:16:32 +00003568 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003569 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003570 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003571 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003572 // candidate functions in the usual way.113) A given name can refer to one
3573 // or more function templates and also to a set of overloaded non-template
3574 // functions. In such a case, the candidate functions generated from each
3575 // function template are combined with the set of non-template candidate
3576 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003577 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003578 FunctionDecl *Specialization = 0;
3579 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003580 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003581 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003582 CandidateSet.push_back(OverloadCandidate());
3583 OverloadCandidate &Candidate = CandidateSet.back();
3584 Candidate.FoundDecl = FoundDecl;
3585 Candidate.Function = MethodTmpl->getTemplatedDecl();
3586 Candidate.Viable = false;
3587 Candidate.FailureKind = ovl_fail_bad_deduction;
3588 Candidate.IsSurrogate = false;
3589 Candidate.IgnoreObjectArgument = false;
3590 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3591 Info);
3592 return;
3593 }
Mike Stump11289f42009-09-09 15:08:12 +00003594
Douglas Gregor97628d62009-08-21 00:16:32 +00003595 // Add the function template specialization produced by template argument
3596 // deduction as a candidate.
3597 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003598 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003599 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003600 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003601 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003602 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003603}
3604
Douglas Gregor05155d82009-08-21 23:19:43 +00003605/// \brief Add a C++ function template specialization as a candidate
3606/// in the candidate set, using template argument deduction to produce
3607/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003608void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003609Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003610 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003611 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003612 Expr **Args, unsigned NumArgs,
3613 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003614 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003615 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3616 return;
3617
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003618 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003619 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003620 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003621 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003622 // candidate functions in the usual way.113) A given name can refer to one
3623 // or more function templates and also to a set of overloaded non-template
3624 // functions. In such a case, the candidate functions generated from each
3625 // function template are combined with the set of non-template candidate
3626 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003627 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003628 FunctionDecl *Specialization = 0;
3629 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003630 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003631 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003632 CandidateSet.push_back(OverloadCandidate());
3633 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003634 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003635 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3636 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003637 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003638 Candidate.IsSurrogate = false;
3639 Candidate.IgnoreObjectArgument = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003640 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3641 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003642 return;
3643 }
Mike Stump11289f42009-09-09 15:08:12 +00003644
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003645 // Add the function template specialization produced by template argument
3646 // deduction as a candidate.
3647 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003648 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003649 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003650}
Mike Stump11289f42009-09-09 15:08:12 +00003651
Douglas Gregora1f013e2008-11-07 22:36:19 +00003652/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003653/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003654/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003655/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003656/// (which may or may not be the same type as the type that the
3657/// conversion function produces).
3658void
3659Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003660 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003661 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003662 Expr *From, QualType ToType,
3663 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003664 assert(!Conversion->getDescribedFunctionTemplate() &&
3665 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003666 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003667 if (!CandidateSet.isNewCandidate(Conversion))
3668 return;
3669
Douglas Gregor27381f32009-11-23 12:27:39 +00003670 // Overload resolution is always an unevaluated context.
3671 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3672
Douglas Gregora1f013e2008-11-07 22:36:19 +00003673 // Add this candidate
3674 CandidateSet.push_back(OverloadCandidate());
3675 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003676 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003677 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003678 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003679 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003680 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003681 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003682 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003683
Douglas Gregor436424c2008-11-18 23:14:02 +00003684 // Determine the implicit conversion sequence for the implicit
3685 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00003686 Candidate.Viable = true;
3687 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00003688 Candidate.Conversions[0]
3689 = TryObjectArgumentInitialization(From->getType(), Conversion,
3690 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00003691 // Conversion functions to a different type in the base class is visible in
3692 // the derived class. So, a derived to base conversion should not participate
3693 // in overload resolution.
3694 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
3695 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00003696 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003697 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003698 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003699 return;
3700 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003701
3702 // We won't go through a user-define type conversion function to convert a
3703 // derived to base as such conversions are given Conversion Rank. They only
3704 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3705 QualType FromCanon
3706 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3707 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3708 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3709 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003710 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003711 return;
3712 }
3713
Douglas Gregora1f013e2008-11-07 22:36:19 +00003714 // To determine what the conversion from the result of calling the
3715 // conversion function to the type we're eventually trying to
3716 // convert to (ToType), we need to synthesize a call to the
3717 // conversion function and attempt copy initialization from it. This
3718 // makes sure that we get the right semantics with respect to
3719 // lvalues/rvalues and the type. Fortunately, we can allocate this
3720 // call on the stack and we don't need its arguments to be
3721 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003722 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003723 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00003724 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00003725 CastExpr::CK_FunctionToPointerDecay,
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003726 &ConversionRef, CXXBaseSpecifierArray(),
3727 ImplicitCastExpr::RValue);
Mike Stump11289f42009-09-09 15:08:12 +00003728
3729 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003730 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3731 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00003732 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003733 Conversion->getConversionType().getNonLValueExprType(Context),
Douglas Gregore8f080122009-11-17 21:16:22 +00003734 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003735 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003736 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003737 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003738 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003739
John McCall0d1da222010-01-12 00:44:57 +00003740 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003741 case ImplicitConversionSequence::StandardConversion:
3742 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003743
3744 // C++ [over.ics.user]p3:
3745 // If the user-defined conversion is specified by a specialization of a
3746 // conversion function template, the second standard conversion sequence
3747 // shall have exact match rank.
3748 if (Conversion->getPrimaryTemplate() &&
3749 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3750 Candidate.Viable = false;
3751 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3752 }
3753
Douglas Gregora1f013e2008-11-07 22:36:19 +00003754 break;
3755
3756 case ImplicitConversionSequence::BadConversion:
3757 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003758 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003759 break;
3760
3761 default:
Mike Stump11289f42009-09-09 15:08:12 +00003762 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003763 "Can only end up with a standard conversion sequence or failure");
3764 }
3765}
3766
Douglas Gregor05155d82009-08-21 23:19:43 +00003767/// \brief Adds a conversion function template specialization
3768/// candidate to the overload set, using template argument deduction
3769/// to deduce the template arguments of the conversion function
3770/// template from the type that we are converting to (C++
3771/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003772void
Douglas Gregor05155d82009-08-21 23:19:43 +00003773Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003774 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003775 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003776 Expr *From, QualType ToType,
3777 OverloadCandidateSet &CandidateSet) {
3778 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3779 "Only conversion function templates permitted here");
3780
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003781 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3782 return;
3783
John McCallbc077cf2010-02-08 23:07:23 +00003784 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003785 CXXConversionDecl *Specialization = 0;
3786 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003787 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003788 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003789 CandidateSet.push_back(OverloadCandidate());
3790 OverloadCandidate &Candidate = CandidateSet.back();
3791 Candidate.FoundDecl = FoundDecl;
3792 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3793 Candidate.Viable = false;
3794 Candidate.FailureKind = ovl_fail_bad_deduction;
3795 Candidate.IsSurrogate = false;
3796 Candidate.IgnoreObjectArgument = false;
3797 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3798 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00003799 return;
3800 }
Mike Stump11289f42009-09-09 15:08:12 +00003801
Douglas Gregor05155d82009-08-21 23:19:43 +00003802 // Add the conversion function template specialization produced by
3803 // template argument deduction as a candidate.
3804 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003805 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00003806 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003807}
3808
Douglas Gregorab7897a2008-11-19 22:57:39 +00003809/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3810/// converts the given @c Object to a function pointer via the
3811/// conversion function @c Conversion, and then attempts to call it
3812/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3813/// the type of function that we'll eventually be calling.
3814void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003815 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003816 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003817 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00003818 QualType ObjectType,
3819 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00003820 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003821 if (!CandidateSet.isNewCandidate(Conversion))
3822 return;
3823
Douglas Gregor27381f32009-11-23 12:27:39 +00003824 // Overload resolution is always an unevaluated context.
3825 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3826
Douglas Gregorab7897a2008-11-19 22:57:39 +00003827 CandidateSet.push_back(OverloadCandidate());
3828 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003829 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003830 Candidate.Function = 0;
3831 Candidate.Surrogate = Conversion;
3832 Candidate.Viable = true;
3833 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003834 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003835 Candidate.Conversions.resize(NumArgs + 1);
3836
3837 // Determine the implicit conversion sequence for the implicit
3838 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003839 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00003840 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003841 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003842 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003843 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00003844 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003845 return;
3846 }
3847
3848 // The first conversion is actually a user-defined conversion whose
3849 // first conversion is ObjectInit's standard conversion (which is
3850 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00003851 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003852 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003853 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003854 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00003855 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00003856 = Candidate.Conversions[0].UserDefined.Before;
3857 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3858
Mike Stump11289f42009-09-09 15:08:12 +00003859 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00003860 unsigned NumArgsInProto = Proto->getNumArgs();
3861
3862 // (C++ 13.3.2p2): A candidate function having fewer than m
3863 // parameters is viable only if it has an ellipsis in its parameter
3864 // list (8.3.5).
3865 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3866 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003867 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003868 return;
3869 }
3870
3871 // Function types don't have any default arguments, so just check if
3872 // we have enough arguments.
3873 if (NumArgs < NumArgsInProto) {
3874 // Not enough arguments.
3875 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003876 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003877 return;
3878 }
3879
3880 // Determine the implicit conversion sequences for each of the
3881 // arguments.
3882 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3883 if (ArgIdx < NumArgsInProto) {
3884 // (C++ 13.3.2p3): for F to be a viable function, there shall
3885 // exist for each argument an implicit conversion sequence
3886 // (13.3.3.1) that converts that argument to the corresponding
3887 // parameter of F.
3888 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003889 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003890 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003891 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00003892 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00003893 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003894 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003895 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003896 break;
3897 }
3898 } else {
3899 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3900 // argument for which there is no corresponding parameter is
3901 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003902 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003903 }
3904 }
3905}
3906
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003907/// \brief Add overload candidates for overloaded operators that are
3908/// member functions.
3909///
3910/// Add the overloaded operator candidates that are member functions
3911/// for the operator Op that was used in an operator expression such
3912/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3913/// CandidateSet will store the added overload candidates. (C++
3914/// [over.match.oper]).
3915void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3916 SourceLocation OpLoc,
3917 Expr **Args, unsigned NumArgs,
3918 OverloadCandidateSet& CandidateSet,
3919 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003920 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3921
3922 // C++ [over.match.oper]p3:
3923 // For a unary operator @ with an operand of a type whose
3924 // cv-unqualified version is T1, and for a binary operator @ with
3925 // a left operand of a type whose cv-unqualified version is T1 and
3926 // a right operand of a type whose cv-unqualified version is T2,
3927 // three sets of candidate functions, designated member
3928 // candidates, non-member candidates and built-in candidates, are
3929 // constructed as follows:
3930 QualType T1 = Args[0]->getType();
3931 QualType T2;
3932 if (NumArgs > 1)
3933 T2 = Args[1]->getType();
3934
3935 // -- If T1 is a class type, the set of member candidates is the
3936 // result of the qualified lookup of T1::operator@
3937 // (13.3.1.1.1); otherwise, the set of member candidates is
3938 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003939 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003940 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003941 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003942 return;
Mike Stump11289f42009-09-09 15:08:12 +00003943
John McCall27b18f82009-11-17 02:14:36 +00003944 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3945 LookupQualifiedName(Operators, T1Rec->getDecl());
3946 Operators.suppressDiagnostics();
3947
Mike Stump11289f42009-09-09 15:08:12 +00003948 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003949 OperEnd = Operators.end();
3950 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00003951 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00003952 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00003953 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00003954 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00003955 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003956}
3957
Douglas Gregora11693b2008-11-12 17:17:38 +00003958/// AddBuiltinCandidate - Add a candidate for a built-in
3959/// operator. ResultTy and ParamTys are the result and parameter types
3960/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00003961/// arguments being passed to the candidate. IsAssignmentOperator
3962/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00003963/// operator. NumContextualBoolArguments is the number of arguments
3964/// (at the beginning of the argument list) that will be contextually
3965/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00003966void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00003967 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00003968 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003969 bool IsAssignmentOperator,
3970 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00003971 // Overload resolution is always an unevaluated context.
3972 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3973
Douglas Gregora11693b2008-11-12 17:17:38 +00003974 // Add this candidate
3975 CandidateSet.push_back(OverloadCandidate());
3976 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003977 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00003978 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00003979 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003980 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00003981 Candidate.BuiltinTypes.ResultTy = ResultTy;
3982 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3983 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3984
3985 // Determine the implicit conversion sequences for each of the
3986 // arguments.
3987 Candidate.Viable = true;
3988 Candidate.Conversions.resize(NumArgs);
3989 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00003990 // C++ [over.match.oper]p4:
3991 // For the built-in assignment operators, conversions of the
3992 // left operand are restricted as follows:
3993 // -- no temporaries are introduced to hold the left operand, and
3994 // -- no user-defined conversions are applied to the left
3995 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00003996 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00003997 //
3998 // We block these conversions by turning off user-defined
3999 // conversions, since that is the only way that initialization of
4000 // a reference to a non-class type can occur from something that
4001 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004002 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004003 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004004 "Contextual conversion to bool requires bool type");
4005 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
4006 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004007 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004008 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004009 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00004010 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004011 }
John McCall0d1da222010-01-12 00:44:57 +00004012 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004013 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004014 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004015 break;
4016 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004017 }
4018}
4019
4020/// BuiltinCandidateTypeSet - A set of types that will be used for the
4021/// candidate operator functions for built-in operators (C++
4022/// [over.built]). The types are separated into pointer types and
4023/// enumeration types.
4024class BuiltinCandidateTypeSet {
4025 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004026 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004027
4028 /// PointerTypes - The set of pointer types that will be used in the
4029 /// built-in candidates.
4030 TypeSet PointerTypes;
4031
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004032 /// MemberPointerTypes - The set of member pointer types that will be
4033 /// used in the built-in candidates.
4034 TypeSet MemberPointerTypes;
4035
Douglas Gregora11693b2008-11-12 17:17:38 +00004036 /// EnumerationTypes - The set of enumeration types that will be
4037 /// used in the built-in candidates.
4038 TypeSet EnumerationTypes;
4039
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004040 /// \brief The set of vector types that will be used in the built-in
4041 /// candidates.
4042 TypeSet VectorTypes;
4043
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004044 /// Sema - The semantic analysis instance where we are building the
4045 /// candidate type set.
4046 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004047
Douglas Gregora11693b2008-11-12 17:17:38 +00004048 /// Context - The AST context in which we will build the type sets.
4049 ASTContext &Context;
4050
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004051 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4052 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004053 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004054
4055public:
4056 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004057 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004058
Mike Stump11289f42009-09-09 15:08:12 +00004059 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004060 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004061
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004062 void AddTypesConvertedFrom(QualType Ty,
4063 SourceLocation Loc,
4064 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004065 bool AllowExplicitConversions,
4066 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004067
4068 /// pointer_begin - First pointer type found;
4069 iterator pointer_begin() { return PointerTypes.begin(); }
4070
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004071 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004072 iterator pointer_end() { return PointerTypes.end(); }
4073
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004074 /// member_pointer_begin - First member pointer type found;
4075 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4076
4077 /// member_pointer_end - Past the last member pointer type found;
4078 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4079
Douglas Gregora11693b2008-11-12 17:17:38 +00004080 /// enumeration_begin - First enumeration type found;
4081 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4082
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004083 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004084 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004085
4086 iterator vector_begin() { return VectorTypes.begin(); }
4087 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregora11693b2008-11-12 17:17:38 +00004088};
4089
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004090/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004091/// the set of pointer types along with any more-qualified variants of
4092/// that type. For example, if @p Ty is "int const *", this routine
4093/// will add "int const *", "int const volatile *", "int const
4094/// restrict *", and "int const volatile restrict *" to the set of
4095/// pointer types. Returns true if the add of @p Ty itself succeeded,
4096/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004097///
4098/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004099bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004100BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4101 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004102
Douglas Gregora11693b2008-11-12 17:17:38 +00004103 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004104 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004105 return false;
4106
John McCall8ccfcb52009-09-24 19:53:00 +00004107 const PointerType *PointerTy = Ty->getAs<PointerType>();
4108 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00004109
John McCall8ccfcb52009-09-24 19:53:00 +00004110 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004111 // Don't add qualified variants of arrays. For one, they're not allowed
4112 // (the qualifier would sink to the element type), and for another, the
4113 // only overload situation where it matters is subscript or pointer +- int,
4114 // and those shouldn't have qualifier variants anyway.
4115 if (PointeeTy->isArrayType())
4116 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004117 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00004118 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00004119 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004120 bool hasVolatile = VisibleQuals.hasVolatile();
4121 bool hasRestrict = VisibleQuals.hasRestrict();
4122
John McCall8ccfcb52009-09-24 19:53:00 +00004123 // Iterate through all strict supersets of BaseCVR.
4124 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4125 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004126 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4127 // in the types.
4128 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4129 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00004130 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4131 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00004132 }
4133
4134 return true;
4135}
4136
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004137/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4138/// to the set of pointer types along with any more-qualified variants of
4139/// that type. For example, if @p Ty is "int const *", this routine
4140/// will add "int const *", "int const volatile *", "int const
4141/// restrict *", and "int const volatile restrict *" to the set of
4142/// pointer types. Returns true if the add of @p Ty itself succeeded,
4143/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004144///
4145/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004146bool
4147BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4148 QualType Ty) {
4149 // Insert this type.
4150 if (!MemberPointerTypes.insert(Ty))
4151 return false;
4152
John McCall8ccfcb52009-09-24 19:53:00 +00004153 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4154 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004155
John McCall8ccfcb52009-09-24 19:53:00 +00004156 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004157 // Don't add qualified variants of arrays. For one, they're not allowed
4158 // (the qualifier would sink to the element type), and for another, the
4159 // only overload situation where it matters is subscript or pointer +- int,
4160 // and those shouldn't have qualifier variants anyway.
4161 if (PointeeTy->isArrayType())
4162 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004163 const Type *ClassTy = PointerTy->getClass();
4164
4165 // Iterate through all strict supersets of the pointee type's CVR
4166 // qualifiers.
4167 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4168 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4169 if ((CVR | BaseCVR) != CVR) continue;
4170
4171 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4172 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004173 }
4174
4175 return true;
4176}
4177
Douglas Gregora11693b2008-11-12 17:17:38 +00004178/// AddTypesConvertedFrom - Add each of the types to which the type @p
4179/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004180/// primarily interested in pointer types and enumeration types. We also
4181/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004182/// AllowUserConversions is true if we should look at the conversion
4183/// functions of a class type, and AllowExplicitConversions if we
4184/// should also include the explicit conversion functions of a class
4185/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004186void
Douglas Gregor5fb53972009-01-14 15:45:31 +00004187BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004188 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004189 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004190 bool AllowExplicitConversions,
4191 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004192 // Only deal with canonical types.
4193 Ty = Context.getCanonicalType(Ty);
4194
4195 // Look through reference types; they aren't part of the type of an
4196 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004197 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00004198 Ty = RefTy->getPointeeType();
4199
4200 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004201 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00004202
Sebastian Redl65ae2002009-11-05 16:36:20 +00004203 // If we're dealing with an array type, decay to the pointer.
4204 if (Ty->isArrayType())
4205 Ty = SemaRef.Context.getArrayDecayedType(Ty);
4206
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004207 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004208 QualType PointeeTy = PointerTy->getPointeeType();
4209
4210 // Insert our type, and its more-qualified variants, into the set
4211 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004212 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00004213 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004214 } else if (Ty->isMemberPointerType()) {
4215 // Member pointers are far easier, since the pointee can't be converted.
4216 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4217 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00004218 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00004219 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004220 } else if (Ty->isVectorType()) {
4221 VectorTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004222 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004223 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004224 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004225 // No conversion functions in incomplete types.
4226 return;
4227 }
Mike Stump11289f42009-09-09 15:08:12 +00004228
Douglas Gregora11693b2008-11-12 17:17:38 +00004229 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00004230 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00004231 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00004232 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004233 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004234 NamedDecl *D = I.getDecl();
4235 if (isa<UsingShadowDecl>(D))
4236 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004237
Mike Stump11289f42009-09-09 15:08:12 +00004238 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00004239 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00004240 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00004241 continue;
4242
John McCallda4458e2010-03-31 01:36:47 +00004243 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004244 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004245 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004246 VisibleQuals);
4247 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004248 }
4249 }
4250 }
4251}
4252
Douglas Gregor84605ae2009-08-24 13:43:27 +00004253/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4254/// the volatile- and non-volatile-qualified assignment operators for the
4255/// given type to the candidate set.
4256static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4257 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004258 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004259 unsigned NumArgs,
4260 OverloadCandidateSet &CandidateSet) {
4261 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004262
Douglas Gregor84605ae2009-08-24 13:43:27 +00004263 // T& operator=(T&, T)
4264 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4265 ParamTypes[1] = T;
4266 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4267 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004268
Douglas Gregor84605ae2009-08-24 13:43:27 +00004269 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4270 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004271 ParamTypes[0]
4272 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004273 ParamTypes[1] = T;
4274 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004275 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004276 }
4277}
Mike Stump11289f42009-09-09 15:08:12 +00004278
Sebastian Redl1054fae2009-10-25 17:03:50 +00004279/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4280/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004281static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4282 Qualifiers VRQuals;
4283 const RecordType *TyRec;
4284 if (const MemberPointerType *RHSMPType =
4285 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004286 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004287 else
4288 TyRec = ArgExpr->getType()->getAs<RecordType>();
4289 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004290 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004291 VRQuals.addVolatile();
4292 VRQuals.addRestrict();
4293 return VRQuals;
4294 }
4295
4296 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004297 if (!ClassDecl->hasDefinition())
4298 return VRQuals;
4299
John McCallad371252010-01-20 00:46:10 +00004300 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004301 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004302
John McCallad371252010-01-20 00:46:10 +00004303 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004304 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004305 NamedDecl *D = I.getDecl();
4306 if (isa<UsingShadowDecl>(D))
4307 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4308 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004309 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4310 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4311 CanTy = ResTypeRef->getPointeeType();
4312 // Need to go down the pointer/mempointer chain and add qualifiers
4313 // as see them.
4314 bool done = false;
4315 while (!done) {
4316 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4317 CanTy = ResTypePtr->getPointeeType();
4318 else if (const MemberPointerType *ResTypeMPtr =
4319 CanTy->getAs<MemberPointerType>())
4320 CanTy = ResTypeMPtr->getPointeeType();
4321 else
4322 done = true;
4323 if (CanTy.isVolatileQualified())
4324 VRQuals.addVolatile();
4325 if (CanTy.isRestrictQualified())
4326 VRQuals.addRestrict();
4327 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4328 return VRQuals;
4329 }
4330 }
4331 }
4332 return VRQuals;
4333}
4334
Douglas Gregord08452f2008-11-19 15:42:04 +00004335/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4336/// operator overloads to the candidate set (C++ [over.built]), based
4337/// on the operator @p Op and the arguments given. For example, if the
4338/// operator is a binary '+', this routine might add "int
4339/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00004340void
Mike Stump11289f42009-09-09 15:08:12 +00004341Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004342 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00004343 Expr **Args, unsigned NumArgs,
4344 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004345 // The set of "promoted arithmetic types", which are the arithmetic
4346 // types are that preserved by promotion (C++ [over.built]p2). Note
4347 // that the first few of these types are the promoted integral
4348 // types; these types need to be first.
4349 // FIXME: What about complex?
4350 const unsigned FirstIntegralType = 0;
4351 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00004352 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00004353 LastPromotedIntegralType = 13;
4354 const unsigned FirstPromotedArithmeticType = 7,
4355 LastPromotedArithmeticType = 16;
4356 const unsigned NumArithmeticTypes = 16;
4357 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00004358 Context.BoolTy, Context.CharTy, Context.WCharTy,
4359// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00004360 Context.SignedCharTy, Context.ShortTy,
4361 Context.UnsignedCharTy, Context.UnsignedShortTy,
4362 Context.IntTy, Context.LongTy, Context.LongLongTy,
4363 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
4364 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
4365 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00004366 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
4367 "Invalid first promoted integral type");
4368 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4369 == Context.UnsignedLongLongTy &&
4370 "Invalid last promoted integral type");
4371 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
4372 "Invalid first promoted arithmetic type");
4373 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4374 == Context.LongDoubleTy &&
4375 "Invalid last promoted arithmetic type");
4376
Douglas Gregora11693b2008-11-12 17:17:38 +00004377 // Find all of the types that the arguments can convert to, but only
4378 // if the operator we're looking at has built-in operator candidates
4379 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004380 Qualifiers VisibleTypeConversionsQuals;
4381 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004382 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4383 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4384
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004385 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004386 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4387 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4388 OpLoc,
4389 true,
4390 (Op == OO_Exclaim ||
4391 Op == OO_AmpAmp ||
4392 Op == OO_PipePipe),
4393 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004394
4395 bool isComparison = false;
4396 switch (Op) {
4397 case OO_None:
4398 case NUM_OVERLOADED_OPERATORS:
4399 assert(false && "Expected an overloaded operator");
4400 break;
4401
Douglas Gregord08452f2008-11-19 15:42:04 +00004402 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00004403 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00004404 goto UnaryStar;
4405 else
4406 goto BinaryStar;
4407 break;
4408
4409 case OO_Plus: // '+' is either unary or binary
4410 if (NumArgs == 1)
4411 goto UnaryPlus;
4412 else
4413 goto BinaryPlus;
4414 break;
4415
4416 case OO_Minus: // '-' is either unary or binary
4417 if (NumArgs == 1)
4418 goto UnaryMinus;
4419 else
4420 goto BinaryMinus;
4421 break;
4422
4423 case OO_Amp: // '&' is either unary or binary
4424 if (NumArgs == 1)
4425 goto UnaryAmp;
4426 else
4427 goto BinaryAmp;
4428
4429 case OO_PlusPlus:
4430 case OO_MinusMinus:
4431 // C++ [over.built]p3:
4432 //
4433 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4434 // is either volatile or empty, there exist candidate operator
4435 // functions of the form
4436 //
4437 // VQ T& operator++(VQ T&);
4438 // T operator++(VQ T&, int);
4439 //
4440 // C++ [over.built]p4:
4441 //
4442 // For every pair (T, VQ), where T is an arithmetic type other
4443 // than bool, and VQ is either volatile or empty, there exist
4444 // candidate operator functions of the form
4445 //
4446 // VQ T& operator--(VQ T&);
4447 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00004448 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004449 Arith < NumArithmeticTypes; ++Arith) {
4450 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00004451 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004452 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00004453
4454 // Non-volatile version.
4455 if (NumArgs == 1)
4456 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4457 else
4458 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004459 // heuristic to reduce number of builtin candidates in the set.
4460 // Add volatile version only if there are conversions to a volatile type.
4461 if (VisibleTypeConversionsQuals.hasVolatile()) {
4462 // Volatile version
4463 ParamTypes[0]
4464 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4465 if (NumArgs == 1)
4466 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4467 else
4468 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4469 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004470 }
4471
4472 // C++ [over.built]p5:
4473 //
4474 // For every pair (T, VQ), where T is a cv-qualified or
4475 // cv-unqualified object type, and VQ is either volatile or
4476 // empty, there exist candidate operator functions of the form
4477 //
4478 // T*VQ& operator++(T*VQ&);
4479 // T*VQ& operator--(T*VQ&);
4480 // T* operator++(T*VQ&, int);
4481 // T* operator--(T*VQ&, int);
4482 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4483 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4484 // Skip pointer types that aren't pointers to object types.
Eli Friedmana170cd62010-08-05 02:49:48 +00004485 if (!(*Ptr)->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00004486 continue;
4487
Mike Stump11289f42009-09-09 15:08:12 +00004488 QualType ParamTypes[2] = {
4489 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00004490 };
Mike Stump11289f42009-09-09 15:08:12 +00004491
Douglas Gregord08452f2008-11-19 15:42:04 +00004492 // Without volatile
4493 if (NumArgs == 1)
4494 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4495 else
4496 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4497
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004498 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4499 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004500 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00004501 ParamTypes[0]
4502 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00004503 if (NumArgs == 1)
4504 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4505 else
4506 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4507 }
4508 }
4509 break;
4510
4511 UnaryStar:
4512 // C++ [over.built]p6:
4513 // For every cv-qualified or cv-unqualified object type T, there
4514 // exist candidate operator functions of the form
4515 //
4516 // T& operator*(T*);
4517 //
4518 // C++ [over.built]p7:
4519 // For every function type T, there exist candidate operator
4520 // functions of the form
4521 // T& operator*(T*);
4522 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4523 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4524 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004525 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004526 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00004527 &ParamTy, Args, 1, CandidateSet);
4528 }
4529 break;
4530
4531 UnaryPlus:
4532 // C++ [over.built]p8:
4533 // For every type T, there exist candidate operator functions of
4534 // the form
4535 //
4536 // T* operator+(T*);
4537 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4538 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4539 QualType ParamTy = *Ptr;
4540 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4541 }
Mike Stump11289f42009-09-09 15:08:12 +00004542
Douglas Gregord08452f2008-11-19 15:42:04 +00004543 // Fall through
4544
4545 UnaryMinus:
4546 // C++ [over.built]p9:
4547 // For every promoted arithmetic type T, there exist candidate
4548 // operator functions of the form
4549 //
4550 // T operator+(T);
4551 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00004552 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004553 Arith < LastPromotedArithmeticType; ++Arith) {
4554 QualType ArithTy = ArithmeticTypes[Arith];
4555 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4556 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004557
4558 // Extension: We also add these operators for vector types.
4559 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4560 VecEnd = CandidateTypes.vector_end();
4561 Vec != VecEnd; ++Vec) {
4562 QualType VecTy = *Vec;
4563 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4564 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004565 break;
4566
4567 case OO_Tilde:
4568 // C++ [over.built]p10:
4569 // For every promoted integral type T, there exist candidate
4570 // operator functions of the form
4571 //
4572 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00004573 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004574 Int < LastPromotedIntegralType; ++Int) {
4575 QualType IntTy = ArithmeticTypes[Int];
4576 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4577 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004578
4579 // Extension: We also add this operator for vector types.
4580 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4581 VecEnd = CandidateTypes.vector_end();
4582 Vec != VecEnd; ++Vec) {
4583 QualType VecTy = *Vec;
4584 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4585 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004586 break;
4587
Douglas Gregora11693b2008-11-12 17:17:38 +00004588 case OO_New:
4589 case OO_Delete:
4590 case OO_Array_New:
4591 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00004592 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00004593 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00004594 break;
4595
4596 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00004597 UnaryAmp:
4598 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00004599 // C++ [over.match.oper]p3:
4600 // -- For the operator ',', the unary operator '&', or the
4601 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00004602 break;
4603
Douglas Gregor84605ae2009-08-24 13:43:27 +00004604 case OO_EqualEqual:
4605 case OO_ExclaimEqual:
4606 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00004607 // For every pointer to member type T, there exist candidate operator
4608 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00004609 //
4610 // bool operator==(T,T);
4611 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00004612 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00004613 MemPtr = CandidateTypes.member_pointer_begin(),
4614 MemPtrEnd = CandidateTypes.member_pointer_end();
4615 MemPtr != MemPtrEnd;
4616 ++MemPtr) {
4617 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4618 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4619 }
Mike Stump11289f42009-09-09 15:08:12 +00004620
Douglas Gregor84605ae2009-08-24 13:43:27 +00004621 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004622
Douglas Gregora11693b2008-11-12 17:17:38 +00004623 case OO_Less:
4624 case OO_Greater:
4625 case OO_LessEqual:
4626 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004627 // C++ [over.built]p15:
4628 //
4629 // For every pointer or enumeration type T, there exist
4630 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004631 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004632 // bool operator<(T, T);
4633 // bool operator>(T, T);
4634 // bool operator<=(T, T);
4635 // bool operator>=(T, T);
4636 // bool operator==(T, T);
4637 // bool operator!=(T, T);
4638 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4639 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4640 QualType ParamTypes[2] = { *Ptr, *Ptr };
4641 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4642 }
Mike Stump11289f42009-09-09 15:08:12 +00004643 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00004644 = CandidateTypes.enumeration_begin();
4645 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4646 QualType ParamTypes[2] = { *Enum, *Enum };
4647 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4648 }
4649
4650 // Fall through.
4651 isComparison = true;
4652
Douglas Gregord08452f2008-11-19 15:42:04 +00004653 BinaryPlus:
4654 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00004655 if (!isComparison) {
4656 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4657
4658 // C++ [over.built]p13:
4659 //
4660 // For every cv-qualified or cv-unqualified object type T
4661 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004662 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004663 // T* operator+(T*, ptrdiff_t);
4664 // T& operator[](T*, ptrdiff_t); [BELOW]
4665 // T* operator-(T*, ptrdiff_t);
4666 // T* operator+(ptrdiff_t, T*);
4667 // T& operator[](ptrdiff_t, T*); [BELOW]
4668 //
4669 // C++ [over.built]p14:
4670 //
4671 // For every T, where T is a pointer to object type, there
4672 // exist candidate operator functions of the form
4673 //
4674 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00004675 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00004676 = CandidateTypes.pointer_begin();
4677 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4678 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4679
4680 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4681 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4682
4683 if (Op == OO_Plus) {
4684 // T* operator+(ptrdiff_t, T*);
4685 ParamTypes[0] = ParamTypes[1];
4686 ParamTypes[1] = *Ptr;
4687 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4688 } else {
4689 // ptrdiff_t operator-(T, T);
4690 ParamTypes[1] = *Ptr;
4691 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4692 Args, 2, CandidateSet);
4693 }
4694 }
4695 }
4696 // Fall through
4697
Douglas Gregora11693b2008-11-12 17:17:38 +00004698 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00004699 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00004700 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00004701 // C++ [over.built]p12:
4702 //
4703 // For every pair of promoted arithmetic types L and R, there
4704 // exist candidate operator functions of the form
4705 //
4706 // LR operator*(L, R);
4707 // LR operator/(L, R);
4708 // LR operator+(L, R);
4709 // LR operator-(L, R);
4710 // bool operator<(L, R);
4711 // bool operator>(L, R);
4712 // bool operator<=(L, R);
4713 // bool operator>=(L, R);
4714 // bool operator==(L, R);
4715 // bool operator!=(L, R);
4716 //
4717 // where LR is the result of the usual arithmetic conversions
4718 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004719 //
4720 // C++ [over.built]p24:
4721 //
4722 // For every pair of promoted arithmetic types L and R, there exist
4723 // candidate operator functions of the form
4724 //
4725 // LR operator?(bool, L, R);
4726 //
4727 // where LR is the result of the usual arithmetic conversions
4728 // between types L and R.
4729 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004730 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004731 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004732 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004733 Right < LastPromotedArithmeticType; ++Right) {
4734 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004735 QualType Result
4736 = isComparison
4737 ? Context.BoolTy
4738 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004739 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4740 }
4741 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004742
4743 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
4744 // conditional operator for vector types.
4745 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4746 Vec1End = CandidateTypes.vector_end();
4747 Vec1 != Vec1End; ++Vec1)
4748 for (BuiltinCandidateTypeSet::iterator
4749 Vec2 = CandidateTypes.vector_begin(),
4750 Vec2End = CandidateTypes.vector_end();
4751 Vec2 != Vec2End; ++Vec2) {
4752 QualType LandR[2] = { *Vec1, *Vec2 };
4753 QualType Result;
4754 if (isComparison)
4755 Result = Context.BoolTy;
4756 else {
4757 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
4758 Result = *Vec1;
4759 else
4760 Result = *Vec2;
4761 }
4762
4763 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4764 }
4765
Douglas Gregora11693b2008-11-12 17:17:38 +00004766 break;
4767
4768 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00004769 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00004770 case OO_Caret:
4771 case OO_Pipe:
4772 case OO_LessLess:
4773 case OO_GreaterGreater:
4774 // C++ [over.built]p17:
4775 //
4776 // For every pair of promoted integral types L and R, there
4777 // exist candidate operator functions of the form
4778 //
4779 // LR operator%(L, R);
4780 // LR operator&(L, R);
4781 // LR operator^(L, R);
4782 // LR operator|(L, R);
4783 // L operator<<(L, R);
4784 // L operator>>(L, R);
4785 //
4786 // where LR is the result of the usual arithmetic conversions
4787 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00004788 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004789 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004790 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004791 Right < LastPromotedIntegralType; ++Right) {
4792 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4793 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4794 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004795 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004796 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4797 }
4798 }
4799 break;
4800
4801 case OO_Equal:
4802 // C++ [over.built]p20:
4803 //
4804 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00004805 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00004806 // empty, there exist candidate operator functions of the form
4807 //
4808 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004809 for (BuiltinCandidateTypeSet::iterator
4810 Enum = CandidateTypes.enumeration_begin(),
4811 EnumEnd = CandidateTypes.enumeration_end();
4812 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00004813 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004814 CandidateSet);
4815 for (BuiltinCandidateTypeSet::iterator
4816 MemPtr = CandidateTypes.member_pointer_begin(),
4817 MemPtrEnd = CandidateTypes.member_pointer_end();
4818 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00004819 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004820 CandidateSet);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004821
4822 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00004823
4824 case OO_PlusEqual:
4825 case OO_MinusEqual:
4826 // C++ [over.built]p19:
4827 //
4828 // For every pair (T, VQ), where T is any type and VQ is either
4829 // volatile or empty, there exist candidate operator functions
4830 // of the form
4831 //
4832 // T*VQ& operator=(T*VQ&, T*);
4833 //
4834 // C++ [over.built]p21:
4835 //
4836 // For every pair (T, VQ), where T is a cv-qualified or
4837 // cv-unqualified object type and VQ is either volatile or
4838 // empty, there exist candidate operator functions of the form
4839 //
4840 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4841 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4842 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4843 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4844 QualType ParamTypes[2];
4845 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4846
4847 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004848 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004849 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4850 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004851
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004852 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4853 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004854 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00004855 ParamTypes[0]
4856 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00004857 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4858 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00004859 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004860 }
4861 // Fall through.
4862
4863 case OO_StarEqual:
4864 case OO_SlashEqual:
4865 // C++ [over.built]p18:
4866 //
4867 // For every triple (L, VQ, R), where L is an arithmetic type,
4868 // VQ is either volatile or empty, and R is a promoted
4869 // arithmetic type, there exist candidate operator functions of
4870 // the form
4871 //
4872 // VQ L& operator=(VQ L&, R);
4873 // VQ L& operator*=(VQ L&, R);
4874 // VQ L& operator/=(VQ L&, R);
4875 // VQ L& operator+=(VQ L&, R);
4876 // VQ L& operator-=(VQ L&, R);
4877 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004878 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004879 Right < LastPromotedArithmeticType; ++Right) {
4880 QualType ParamTypes[2];
4881 ParamTypes[1] = ArithmeticTypes[Right];
4882
4883 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004884 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004885 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4886 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004887
4888 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004889 if (VisibleTypeConversionsQuals.hasVolatile()) {
4890 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4891 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4892 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4893 /*IsAssigmentOperator=*/Op == OO_Equal);
4894 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004895 }
4896 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004897
4898 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
4899 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4900 Vec1End = CandidateTypes.vector_end();
4901 Vec1 != Vec1End; ++Vec1)
4902 for (BuiltinCandidateTypeSet::iterator
4903 Vec2 = CandidateTypes.vector_begin(),
4904 Vec2End = CandidateTypes.vector_end();
4905 Vec2 != Vec2End; ++Vec2) {
4906 QualType ParamTypes[2];
4907 ParamTypes[1] = *Vec2;
4908 // Add this built-in operator as a candidate (VQ is empty).
4909 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
4910 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4911 /*IsAssigmentOperator=*/Op == OO_Equal);
4912
4913 // Add this built-in operator as a candidate (VQ is 'volatile').
4914 if (VisibleTypeConversionsQuals.hasVolatile()) {
4915 ParamTypes[0] = Context.getVolatileType(*Vec1);
4916 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4917 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4918 /*IsAssigmentOperator=*/Op == OO_Equal);
4919 }
4920 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004921 break;
4922
4923 case OO_PercentEqual:
4924 case OO_LessLessEqual:
4925 case OO_GreaterGreaterEqual:
4926 case OO_AmpEqual:
4927 case OO_CaretEqual:
4928 case OO_PipeEqual:
4929 // C++ [over.built]p22:
4930 //
4931 // For every triple (L, VQ, R), where L is an integral type, VQ
4932 // is either volatile or empty, and R is a promoted integral
4933 // type, there exist candidate operator functions of the form
4934 //
4935 // VQ L& operator%=(VQ L&, R);
4936 // VQ L& operator<<=(VQ L&, R);
4937 // VQ L& operator>>=(VQ L&, R);
4938 // VQ L& operator&=(VQ L&, R);
4939 // VQ L& operator^=(VQ L&, R);
4940 // VQ L& operator|=(VQ L&, R);
4941 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004942 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004943 Right < LastPromotedIntegralType; ++Right) {
4944 QualType ParamTypes[2];
4945 ParamTypes[1] = ArithmeticTypes[Right];
4946
4947 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004948 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004949 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00004950 if (VisibleTypeConversionsQuals.hasVolatile()) {
4951 // Add this built-in operator as a candidate (VQ is 'volatile').
4952 ParamTypes[0] = ArithmeticTypes[Left];
4953 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4954 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4955 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4956 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004957 }
4958 }
4959 break;
4960
Douglas Gregord08452f2008-11-19 15:42:04 +00004961 case OO_Exclaim: {
4962 // C++ [over.operator]p23:
4963 //
4964 // There also exist candidate operator functions of the form
4965 //
Mike Stump11289f42009-09-09 15:08:12 +00004966 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00004967 // bool operator&&(bool, bool); [BELOW]
4968 // bool operator||(bool, bool); [BELOW]
4969 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00004970 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4971 /*IsAssignmentOperator=*/false,
4972 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004973 break;
4974 }
4975
Douglas Gregora11693b2008-11-12 17:17:38 +00004976 case OO_AmpAmp:
4977 case OO_PipePipe: {
4978 // C++ [over.operator]p23:
4979 //
4980 // There also exist candidate operator functions of the form
4981 //
Douglas Gregord08452f2008-11-19 15:42:04 +00004982 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00004983 // bool operator&&(bool, bool);
4984 // bool operator||(bool, bool);
4985 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00004986 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4987 /*IsAssignmentOperator=*/false,
4988 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00004989 break;
4990 }
4991
4992 case OO_Subscript:
4993 // C++ [over.built]p13:
4994 //
4995 // For every cv-qualified or cv-unqualified object type T there
4996 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004997 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004998 // T* operator+(T*, ptrdiff_t); [ABOVE]
4999 // T& operator[](T*, ptrdiff_t);
5000 // T* operator-(T*, ptrdiff_t); [ABOVE]
5001 // T* operator+(ptrdiff_t, T*); [ABOVE]
5002 // T& operator[](ptrdiff_t, T*);
5003 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
5004 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5005 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005006 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005007 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00005008
5009 // T& operator[](T*, ptrdiff_t)
5010 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5011
5012 // T& operator[](ptrdiff_t, T*);
5013 ParamTypes[0] = ParamTypes[1];
5014 ParamTypes[1] = *Ptr;
5015 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005016 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005017 break;
5018
5019 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005020 // C++ [over.built]p11:
5021 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5022 // C1 is the same type as C2 or is a derived class of C2, T is an object
5023 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5024 // there exist candidate operator functions of the form
5025 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5026 // where CV12 is the union of CV1 and CV2.
5027 {
5028 for (BuiltinCandidateTypeSet::iterator Ptr =
5029 CandidateTypes.pointer_begin();
5030 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5031 QualType C1Ty = (*Ptr);
5032 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005033 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005034 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005035 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005036 if (!isa<RecordType>(C1))
5037 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005038 // heuristic to reduce number of builtin candidates in the set.
5039 // Add volatile/restrict version only if there are conversions to a
5040 // volatile/restrict type.
5041 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5042 continue;
5043 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5044 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005045 }
5046 for (BuiltinCandidateTypeSet::iterator
5047 MemPtr = CandidateTypes.member_pointer_begin(),
5048 MemPtrEnd = CandidateTypes.member_pointer_end();
5049 MemPtr != MemPtrEnd; ++MemPtr) {
5050 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5051 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00005052 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005053 if (C1 != C2 && !IsDerivedFrom(C1, C2))
5054 break;
5055 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5056 // build CV12 T&
5057 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005058 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5059 T.isVolatileQualified())
5060 continue;
5061 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5062 T.isRestrictQualified())
5063 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005064 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005065 QualType ResultTy = Context.getLValueReferenceType(T);
5066 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5067 }
5068 }
5069 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005070 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005071
5072 case OO_Conditional:
5073 // Note that we don't consider the first argument, since it has been
5074 // contextually converted to bool long ago. The candidates below are
5075 // therefore added as binary.
5076 //
5077 // C++ [over.built]p24:
5078 // For every type T, where T is a pointer or pointer-to-member type,
5079 // there exist candidate operator functions of the form
5080 //
5081 // T operator?(bool, T, T);
5082 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00005083 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
5084 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
5085 QualType ParamTypes[2] = { *Ptr, *Ptr };
5086 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5087 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005088 for (BuiltinCandidateTypeSet::iterator Ptr =
5089 CandidateTypes.member_pointer_begin(),
5090 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
5091 QualType ParamTypes[2] = { *Ptr, *Ptr };
5092 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5093 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005094 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00005095 }
5096}
5097
Douglas Gregore254f902009-02-04 00:32:51 +00005098/// \brief Add function candidates found via argument-dependent lookup
5099/// to the set of overloading candidates.
5100///
5101/// This routine performs argument-dependent name lookup based on the
5102/// given function name (which may also be an operator name) and adds
5103/// all of the overload candidates found by ADL to the overload
5104/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00005105void
Douglas Gregore254f902009-02-04 00:32:51 +00005106Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00005107 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00005108 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00005109 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005110 OverloadCandidateSet& CandidateSet,
5111 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00005112 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00005113
John McCall91f61fc2010-01-26 06:04:06 +00005114 // FIXME: This approach for uniquing ADL results (and removing
5115 // redundant candidates from the set) relies on pointer-equality,
5116 // which means we need to key off the canonical decl. However,
5117 // always going back to the canonical decl might not get us the
5118 // right set of default arguments. What default arguments are
5119 // we supposed to consider on ADL candidates, anyway?
5120
Douglas Gregorcabea402009-09-22 15:41:20 +00005121 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00005122 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00005123
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005124 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005125 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5126 CandEnd = CandidateSet.end();
5127 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00005128 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00005129 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00005130 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00005131 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00005132 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005133
5134 // For each of the ADL candidates we found, add it to the overload
5135 // set.
John McCall8fe68082010-01-26 07:16:45 +00005136 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00005137 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00005138 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00005139 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00005140 continue;
5141
John McCalla0296f72010-03-19 07:35:19 +00005142 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005143 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005144 } else
John McCall4c4c1df2010-01-26 03:27:55 +00005145 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00005146 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00005147 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00005148 }
Douglas Gregore254f902009-02-04 00:32:51 +00005149}
5150
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005151/// isBetterOverloadCandidate - Determines whether the first overload
5152/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00005153bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005154Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCallbc077cf2010-02-08 23:07:23 +00005155 const OverloadCandidate& Cand2,
5156 SourceLocation Loc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005157 // Define viable functions to be better candidates than non-viable
5158 // functions.
5159 if (!Cand2.Viable)
5160 return Cand1.Viable;
5161 else if (!Cand1.Viable)
5162 return false;
5163
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005164 // C++ [over.match.best]p1:
5165 //
5166 // -- if F is a static member function, ICS1(F) is defined such
5167 // that ICS1(F) is neither better nor worse than ICS1(G) for
5168 // any function G, and, symmetrically, ICS1(G) is neither
5169 // better nor worse than ICS1(F).
5170 unsigned StartArg = 0;
5171 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5172 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005173
Douglas Gregord3cb3562009-07-07 23:38:56 +00005174 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005175 // A viable function F1 is defined to be a better function than another
5176 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00005177 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005178 unsigned NumArgs = Cand1.Conversions.size();
5179 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5180 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005181 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005182 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
5183 Cand2.Conversions[ArgIdx])) {
5184 case ImplicitConversionSequence::Better:
5185 // Cand1 has a better conversion sequence.
5186 HasBetterConversion = true;
5187 break;
5188
5189 case ImplicitConversionSequence::Worse:
5190 // Cand1 can't be better than Cand2.
5191 return false;
5192
5193 case ImplicitConversionSequence::Indistinguishable:
5194 // Do nothing.
5195 break;
5196 }
5197 }
5198
Mike Stump11289f42009-09-09 15:08:12 +00005199 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00005200 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005201 if (HasBetterConversion)
5202 return true;
5203
Mike Stump11289f42009-09-09 15:08:12 +00005204 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00005205 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00005206 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00005207 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5208 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005209
5210 // -- F1 and F2 are function template specializations, and the function
5211 // template for F1 is more specialized than the template for F2
5212 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00005213 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00005214 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5215 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00005216 if (FunctionTemplateDecl *BetterTemplate
5217 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5218 Cand2.Function->getPrimaryTemplate(),
John McCallbc077cf2010-02-08 23:07:23 +00005219 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00005220 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5221 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00005222 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005223
Douglas Gregora1f013e2008-11-07 22:36:19 +00005224 // -- the context is an initialization by user-defined conversion
5225 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5226 // from the return type of F1 to the destination type (i.e.,
5227 // the type of the entity being initialized) is a better
5228 // conversion sequence than the standard conversion sequence
5229 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00005230 if (Cand1.Function && Cand2.Function &&
5231 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00005232 isa<CXXConversionDecl>(Cand2.Function)) {
5233 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
5234 Cand2.FinalConversion)) {
5235 case ImplicitConversionSequence::Better:
5236 // Cand1 has a better conversion sequence.
5237 return true;
5238
5239 case ImplicitConversionSequence::Worse:
5240 // Cand1 can't be better than Cand2.
5241 return false;
5242
5243 case ImplicitConversionSequence::Indistinguishable:
5244 // Do nothing
5245 break;
5246 }
5247 }
5248
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005249 return false;
5250}
5251
Mike Stump11289f42009-09-09 15:08:12 +00005252/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005253/// within an overload candidate set.
5254///
5255/// \param CandidateSet the set of candidate functions.
5256///
5257/// \param Loc the location of the function name (or operator symbol) for
5258/// which overload resolution occurs.
5259///
Mike Stump11289f42009-09-09 15:08:12 +00005260/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005261/// function, Best points to the candidate function found.
5262///
5263/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005264OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
5265 SourceLocation Loc,
5266 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005267 // Find the best viable function.
5268 Best = CandidateSet.end();
5269 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5270 Cand != CandidateSet.end(); ++Cand) {
5271 if (Cand->Viable) {
John McCallbc077cf2010-02-08 23:07:23 +00005272 if (Best == CandidateSet.end() ||
5273 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005274 Best = Cand;
5275 }
5276 }
5277
5278 // If we didn't find any viable functions, abort.
5279 if (Best == CandidateSet.end())
5280 return OR_No_Viable_Function;
5281
5282 // Make sure that this function is better than every other viable
5283 // function. If not, we have an ambiguity.
5284 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5285 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00005286 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005287 Cand != Best &&
John McCallbc077cf2010-02-08 23:07:23 +00005288 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005289 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005290 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005291 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005292 }
Mike Stump11289f42009-09-09 15:08:12 +00005293
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005294 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00005295 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005296 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005297 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00005298 return OR_Deleted;
5299
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005300 // C++ [basic.def.odr]p2:
5301 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00005302 // when referred to from a potentially-evaluated expression. [Note: this
5303 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005304 // (clause 13), user-defined conversions (12.3.2), allocation function for
5305 // placement new (5.3.4), as well as non-default initialization (8.5).
5306 if (Best->Function)
5307 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005308 return OR_Success;
5309}
5310
John McCall53262c92010-01-12 02:15:36 +00005311namespace {
5312
5313enum OverloadCandidateKind {
5314 oc_function,
5315 oc_method,
5316 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005317 oc_function_template,
5318 oc_method_template,
5319 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00005320 oc_implicit_default_constructor,
5321 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005322 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00005323};
5324
John McCalle1ac8d12010-01-13 00:25:19 +00005325OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5326 FunctionDecl *Fn,
5327 std::string &Description) {
5328 bool isTemplate = false;
5329
5330 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5331 isTemplate = true;
5332 Description = S.getTemplateArgumentBindingsText(
5333 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5334 }
John McCallfd0b2f82010-01-06 09:43:14 +00005335
5336 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00005337 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005338 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005339
John McCall53262c92010-01-12 02:15:36 +00005340 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5341 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005342 }
5343
5344 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5345 // This actually gets spelled 'candidate function' for now, but
5346 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00005347 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005348 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00005349
5350 assert(Meth->isCopyAssignment()
5351 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00005352 return oc_implicit_copy_assignment;
5353 }
5354
John McCalle1ac8d12010-01-13 00:25:19 +00005355 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00005356}
5357
5358} // end anonymous namespace
5359
5360// Notes the location of an overload candidate.
5361void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00005362 std::string FnDesc;
5363 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5364 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5365 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00005366}
5367
John McCall0d1da222010-01-12 00:44:57 +00005368/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5369/// "lead" diagnostic; it will be given two arguments, the source and
5370/// target types of the conversion.
5371void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
5372 SourceLocation CaretLoc,
5373 const PartialDiagnostic &PDiag) {
5374 Diag(CaretLoc, PDiag)
5375 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
5376 for (AmbiguousConversionSequence::const_iterator
5377 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
5378 NoteOverloadCandidate(*I);
5379 }
John McCall12f97bc2010-01-08 04:41:39 +00005380}
5381
John McCall0d1da222010-01-12 00:44:57 +00005382namespace {
5383
John McCall6a61b522010-01-13 09:16:55 +00005384void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5385 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5386 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00005387 assert(Cand->Function && "for now, candidate must be a function");
5388 FunctionDecl *Fn = Cand->Function;
5389
5390 // There's a conversion slot for the object argument if this is a
5391 // non-constructor method. Note that 'I' corresponds the
5392 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00005393 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00005394 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00005395 if (I == 0)
5396 isObjectArgument = true;
5397 else
5398 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00005399 }
5400
John McCalle1ac8d12010-01-13 00:25:19 +00005401 std::string FnDesc;
5402 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5403
John McCall6a61b522010-01-13 09:16:55 +00005404 Expr *FromExpr = Conv.Bad.FromExpr;
5405 QualType FromTy = Conv.Bad.getFromType();
5406 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00005407
John McCallfb7ad0f2010-02-02 02:42:52 +00005408 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00005409 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00005410 Expr *E = FromExpr->IgnoreParens();
5411 if (isa<UnaryOperator>(E))
5412 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00005413 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00005414
5415 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5416 << (unsigned) FnKind << FnDesc
5417 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5418 << ToTy << Name << I+1;
5419 return;
5420 }
5421
John McCall6d174642010-01-23 08:10:49 +00005422 // Do some hand-waving analysis to see if the non-viability is due
5423 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00005424 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5425 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5426 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5427 CToTy = RT->getPointeeType();
5428 else {
5429 // TODO: detect and diagnose the full richness of const mismatches.
5430 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5431 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5432 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5433 }
5434
5435 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5436 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5437 // It is dumb that we have to do this here.
5438 while (isa<ArrayType>(CFromTy))
5439 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5440 while (isa<ArrayType>(CToTy))
5441 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5442
5443 Qualifiers FromQs = CFromTy.getQualifiers();
5444 Qualifiers ToQs = CToTy.getQualifiers();
5445
5446 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5447 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5448 << (unsigned) FnKind << FnDesc
5449 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5450 << FromTy
5451 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5452 << (unsigned) isObjectArgument << I+1;
5453 return;
5454 }
5455
5456 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5457 assert(CVR && "unexpected qualifiers mismatch");
5458
5459 if (isObjectArgument) {
5460 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5461 << (unsigned) FnKind << FnDesc
5462 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5463 << FromTy << (CVR - 1);
5464 } else {
5465 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5466 << (unsigned) FnKind << FnDesc
5467 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5468 << FromTy << (CVR - 1) << I+1;
5469 }
5470 return;
5471 }
5472
John McCall6d174642010-01-23 08:10:49 +00005473 // Diagnose references or pointers to incomplete types differently,
5474 // since it's far from impossible that the incompleteness triggered
5475 // the failure.
5476 QualType TempFromTy = FromTy.getNonReferenceType();
5477 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5478 TempFromTy = PTy->getPointeeType();
5479 if (TempFromTy->isIncompleteType()) {
5480 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5481 << (unsigned) FnKind << FnDesc
5482 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5483 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5484 return;
5485 }
5486
Douglas Gregor56f2e342010-06-30 23:01:39 +00005487 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005488 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00005489 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
5490 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
5491 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5492 FromPtrTy->getPointeeType()) &&
5493 !FromPtrTy->getPointeeType()->isIncompleteType() &&
5494 !ToPtrTy->getPointeeType()->isIncompleteType() &&
5495 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
5496 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005497 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00005498 }
5499 } else if (const ObjCObjectPointerType *FromPtrTy
5500 = FromTy->getAs<ObjCObjectPointerType>()) {
5501 if (const ObjCObjectPointerType *ToPtrTy
5502 = ToTy->getAs<ObjCObjectPointerType>())
5503 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
5504 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
5505 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5506 FromPtrTy->getPointeeType()) &&
5507 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005508 BaseToDerivedConversion = 2;
5509 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
5510 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
5511 !FromTy->isIncompleteType() &&
5512 !ToRefTy->getPointeeType()->isIncompleteType() &&
5513 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
5514 BaseToDerivedConversion = 3;
5515 }
5516
5517 if (BaseToDerivedConversion) {
Douglas Gregor56f2e342010-06-30 23:01:39 +00005518 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005519 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00005520 << (unsigned) FnKind << FnDesc
5521 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005522 << (BaseToDerivedConversion - 1)
Douglas Gregor56f2e342010-06-30 23:01:39 +00005523 << FromTy << ToTy << I+1;
5524 return;
5525 }
5526
John McCall47000992010-01-14 03:28:57 +00005527 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00005528 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5529 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00005530 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00005531 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00005532}
5533
5534void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5535 unsigned NumFormalArgs) {
5536 // TODO: treat calls to a missing default constructor as a special case
5537
5538 FunctionDecl *Fn = Cand->Function;
5539 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5540
5541 unsigned MinParams = Fn->getMinRequiredArguments();
5542
5543 // at least / at most / exactly
Douglas Gregor02eb4832010-05-08 18:13:28 +00005544 // FIXME: variadic templates "at most" should account for parameter packs
John McCall6a61b522010-01-13 09:16:55 +00005545 unsigned mode, modeCount;
5546 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005547 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5548 (Cand->FailureKind == ovl_fail_bad_deduction &&
5549 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCall6a61b522010-01-13 09:16:55 +00005550 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5551 mode = 0; // "at least"
5552 else
5553 mode = 2; // "exactly"
5554 modeCount = MinParams;
5555 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005556 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5557 (Cand->FailureKind == ovl_fail_bad_deduction &&
5558 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00005559 if (MinParams != FnTy->getNumArgs())
5560 mode = 1; // "at most"
5561 else
5562 mode = 2; // "exactly"
5563 modeCount = FnTy->getNumArgs();
5564 }
5565
5566 std::string Description;
5567 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5568
5569 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregor02eb4832010-05-08 18:13:28 +00005570 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5571 << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00005572}
5573
John McCall8b9ed552010-02-01 18:53:26 +00005574/// Diagnose a failed template-argument deduction.
5575void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5576 Expr **Args, unsigned NumArgs) {
5577 FunctionDecl *Fn = Cand->Function; // pattern
5578
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005579 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005580 NamedDecl *ParamD;
5581 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5582 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5583 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00005584 switch (Cand->DeductionFailure.Result) {
5585 case Sema::TDK_Success:
5586 llvm_unreachable("TDK_success while diagnosing bad deduction");
5587
5588 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00005589 assert(ParamD && "no parameter found for incomplete deduction result");
5590 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5591 << ParamD->getDeclName();
5592 return;
5593 }
5594
John McCall42d7d192010-08-05 09:05:08 +00005595 case Sema::TDK_Underqualified: {
5596 assert(ParamD && "no parameter found for bad qualifiers deduction result");
5597 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
5598
5599 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
5600
5601 // Param will have been canonicalized, but it should just be a
5602 // qualified version of ParamD, so move the qualifiers to that.
5603 QualifierCollector Qs(S.Context);
5604 Qs.strip(Param);
5605 QualType NonCanonParam = Qs.apply(TParam->getTypeForDecl());
5606 assert(S.Context.hasSameType(Param, NonCanonParam));
5607
5608 // Arg has also been canonicalized, but there's nothing we can do
5609 // about that. It also doesn't matter as much, because it won't
5610 // have any template parameters in it (because deduction isn't
5611 // done on dependent types).
5612 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
5613
5614 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
5615 << ParamD->getDeclName() << Arg << NonCanonParam;
5616 return;
5617 }
5618
5619 case Sema::TDK_Inconsistent: {
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005620 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005621 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005622 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005623 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005624 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005625 which = 1;
5626 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005627 which = 2;
5628 }
5629
5630 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5631 << which << ParamD->getDeclName()
5632 << *Cand->DeductionFailure.getFirstArg()
5633 << *Cand->DeductionFailure.getSecondArg();
5634 return;
5635 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00005636
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005637 case Sema::TDK_InvalidExplicitArguments:
5638 assert(ParamD && "no parameter found for invalid explicit arguments");
5639 if (ParamD->getDeclName())
5640 S.Diag(Fn->getLocation(),
5641 diag::note_ovl_candidate_explicit_arg_mismatch_named)
5642 << ParamD->getDeclName();
5643 else {
5644 int index = 0;
5645 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5646 index = TTP->getIndex();
5647 else if (NonTypeTemplateParmDecl *NTTP
5648 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5649 index = NTTP->getIndex();
5650 else
5651 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
5652 S.Diag(Fn->getLocation(),
5653 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
5654 << (index + 1);
5655 }
5656 return;
5657
Douglas Gregor02eb4832010-05-08 18:13:28 +00005658 case Sema::TDK_TooManyArguments:
5659 case Sema::TDK_TooFewArguments:
5660 DiagnoseArityMismatch(S, Cand, NumArgs);
5661 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00005662
5663 case Sema::TDK_InstantiationDepth:
5664 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
5665 return;
5666
5667 case Sema::TDK_SubstitutionFailure: {
5668 std::string ArgString;
5669 if (TemplateArgumentList *Args
5670 = Cand->DeductionFailure.getTemplateArgumentList())
5671 ArgString = S.getTemplateArgumentBindingsText(
5672 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
5673 *Args);
5674 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
5675 << ArgString;
5676 return;
5677 }
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005678
John McCall8b9ed552010-02-01 18:53:26 +00005679 // TODO: diagnose these individually, then kill off
5680 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00005681 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00005682 case Sema::TDK_FailedOverloadResolution:
5683 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
5684 return;
5685 }
5686}
5687
5688/// Generates a 'note' diagnostic for an overload candidate. We've
5689/// already generated a primary error at the call site.
5690///
5691/// It really does need to be a single diagnostic with its caret
5692/// pointed at the candidate declaration. Yes, this creates some
5693/// major challenges of technical writing. Yes, this makes pointing
5694/// out problems with specific arguments quite awkward. It's still
5695/// better than generating twenty screens of text for every failed
5696/// overload.
5697///
5698/// It would be great to be able to express per-candidate problems
5699/// more richly for those diagnostic clients that cared, but we'd
5700/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00005701void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
5702 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00005703 FunctionDecl *Fn = Cand->Function;
5704
John McCall12f97bc2010-01-08 04:41:39 +00005705 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00005706 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00005707 std::string FnDesc;
5708 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00005709
5710 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00005711 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00005712 return;
John McCall12f97bc2010-01-08 04:41:39 +00005713 }
5714
John McCalle1ac8d12010-01-13 00:25:19 +00005715 // We don't really have anything else to say about viable candidates.
5716 if (Cand->Viable) {
5717 S.NoteOverloadCandidate(Fn);
5718 return;
5719 }
John McCall0d1da222010-01-12 00:44:57 +00005720
John McCall6a61b522010-01-13 09:16:55 +00005721 switch (Cand->FailureKind) {
5722 case ovl_fail_too_many_arguments:
5723 case ovl_fail_too_few_arguments:
5724 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00005725
John McCall6a61b522010-01-13 09:16:55 +00005726 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00005727 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5728
John McCallfe796dd2010-01-23 05:17:32 +00005729 case ovl_fail_trivial_conversion:
5730 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005731 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00005732 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005733
John McCall65eb8792010-02-25 01:37:24 +00005734 case ovl_fail_bad_conversion: {
5735 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5736 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00005737 if (Cand->Conversions[I].isBad())
5738 return DiagnoseBadConversion(S, Cand, I);
5739
5740 // FIXME: this currently happens when we're called from SemaInit
5741 // when user-conversion overload fails. Figure out how to handle
5742 // those conditions and diagnose them well.
5743 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005744 }
John McCall65eb8792010-02-25 01:37:24 +00005745 }
John McCalld3224162010-01-08 00:58:21 +00005746}
5747
5748void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5749 // Desugar the type of the surrogate down to a function type,
5750 // retaining as many typedefs as possible while still showing
5751 // the function type (and, therefore, its parameter types).
5752 QualType FnType = Cand->Surrogate->getConversionType();
5753 bool isLValueReference = false;
5754 bool isRValueReference = false;
5755 bool isPointer = false;
5756 if (const LValueReferenceType *FnTypeRef =
5757 FnType->getAs<LValueReferenceType>()) {
5758 FnType = FnTypeRef->getPointeeType();
5759 isLValueReference = true;
5760 } else if (const RValueReferenceType *FnTypeRef =
5761 FnType->getAs<RValueReferenceType>()) {
5762 FnType = FnTypeRef->getPointeeType();
5763 isRValueReference = true;
5764 }
5765 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5766 FnType = FnTypePtr->getPointeeType();
5767 isPointer = true;
5768 }
5769 // Desugar down to a function type.
5770 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5771 // Reconstruct the pointer/reference as appropriate.
5772 if (isPointer) FnType = S.Context.getPointerType(FnType);
5773 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5774 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5775
5776 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5777 << FnType;
5778}
5779
5780void NoteBuiltinOperatorCandidate(Sema &S,
5781 const char *Opc,
5782 SourceLocation OpLoc,
5783 OverloadCandidate *Cand) {
5784 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5785 std::string TypeStr("operator");
5786 TypeStr += Opc;
5787 TypeStr += "(";
5788 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5789 if (Cand->Conversions.size() == 1) {
5790 TypeStr += ")";
5791 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5792 } else {
5793 TypeStr += ", ";
5794 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5795 TypeStr += ")";
5796 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5797 }
5798}
5799
5800void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5801 OverloadCandidate *Cand) {
5802 unsigned NoOperands = Cand->Conversions.size();
5803 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5804 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00005805 if (ICS.isBad()) break; // all meaningless after first invalid
5806 if (!ICS.isAmbiguous()) continue;
5807
5808 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00005809 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00005810 }
5811}
5812
John McCall3712d9e2010-01-15 23:32:50 +00005813SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5814 if (Cand->Function)
5815 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00005816 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00005817 return Cand->Surrogate->getLocation();
5818 return SourceLocation();
5819}
5820
John McCallad2587a2010-01-12 00:48:53 +00005821struct CompareOverloadCandidatesForDisplay {
5822 Sema &S;
5823 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00005824
5825 bool operator()(const OverloadCandidate *L,
5826 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00005827 // Fast-path this check.
5828 if (L == R) return false;
5829
John McCall12f97bc2010-01-08 04:41:39 +00005830 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00005831 if (L->Viable) {
5832 if (!R->Viable) return true;
5833
5834 // TODO: introduce a tri-valued comparison for overload
5835 // candidates. Would be more worthwhile if we had a sort
5836 // that could exploit it.
John McCallbc077cf2010-02-08 23:07:23 +00005837 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5838 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00005839 } else if (R->Viable)
5840 return false;
John McCall12f97bc2010-01-08 04:41:39 +00005841
John McCall3712d9e2010-01-15 23:32:50 +00005842 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00005843
John McCall3712d9e2010-01-15 23:32:50 +00005844 // Criteria by which we can sort non-viable candidates:
5845 if (!L->Viable) {
5846 // 1. Arity mismatches come after other candidates.
5847 if (L->FailureKind == ovl_fail_too_many_arguments ||
5848 L->FailureKind == ovl_fail_too_few_arguments)
5849 return false;
5850 if (R->FailureKind == ovl_fail_too_many_arguments ||
5851 R->FailureKind == ovl_fail_too_few_arguments)
5852 return true;
John McCall12f97bc2010-01-08 04:41:39 +00005853
John McCallfe796dd2010-01-23 05:17:32 +00005854 // 2. Bad conversions come first and are ordered by the number
5855 // of bad conversions and quality of good conversions.
5856 if (L->FailureKind == ovl_fail_bad_conversion) {
5857 if (R->FailureKind != ovl_fail_bad_conversion)
5858 return true;
5859
5860 // If there's any ordering between the defined conversions...
5861 // FIXME: this might not be transitive.
5862 assert(L->Conversions.size() == R->Conversions.size());
5863
5864 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00005865 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5866 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCallfe796dd2010-01-23 05:17:32 +00005867 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5868 R->Conversions[I])) {
5869 case ImplicitConversionSequence::Better:
5870 leftBetter++;
5871 break;
5872
5873 case ImplicitConversionSequence::Worse:
5874 leftBetter--;
5875 break;
5876
5877 case ImplicitConversionSequence::Indistinguishable:
5878 break;
5879 }
5880 }
5881 if (leftBetter > 0) return true;
5882 if (leftBetter < 0) return false;
5883
5884 } else if (R->FailureKind == ovl_fail_bad_conversion)
5885 return false;
5886
John McCall3712d9e2010-01-15 23:32:50 +00005887 // TODO: others?
5888 }
5889
5890 // Sort everything else by location.
5891 SourceLocation LLoc = GetLocationForCandidate(L);
5892 SourceLocation RLoc = GetLocationForCandidate(R);
5893
5894 // Put candidates without locations (e.g. builtins) at the end.
5895 if (LLoc.isInvalid()) return false;
5896 if (RLoc.isInvalid()) return true;
5897
5898 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00005899 }
5900};
5901
John McCallfe796dd2010-01-23 05:17:32 +00005902/// CompleteNonViableCandidate - Normally, overload resolution only
5903/// computes up to the first
5904void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5905 Expr **Args, unsigned NumArgs) {
5906 assert(!Cand->Viable);
5907
5908 // Don't do anything on failures other than bad conversion.
5909 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5910
5911 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00005912 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00005913 unsigned ConvCount = Cand->Conversions.size();
5914 while (true) {
5915 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5916 ConvIdx++;
5917 if (Cand->Conversions[ConvIdx - 1].isBad())
5918 break;
5919 }
5920
5921 if (ConvIdx == ConvCount)
5922 return;
5923
John McCall65eb8792010-02-25 01:37:24 +00005924 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
5925 "remaining conversion is initialized?");
5926
Douglas Gregoradc7a702010-04-16 17:45:54 +00005927 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00005928 // operation somehow.
5929 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00005930
5931 const FunctionProtoType* Proto;
5932 unsigned ArgIdx = ConvIdx;
5933
5934 if (Cand->IsSurrogate) {
5935 QualType ConvType
5936 = Cand->Surrogate->getConversionType().getNonReferenceType();
5937 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5938 ConvType = ConvPtrType->getPointeeType();
5939 Proto = ConvType->getAs<FunctionProtoType>();
5940 ArgIdx--;
5941 } else if (Cand->Function) {
5942 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
5943 if (isa<CXXMethodDecl>(Cand->Function) &&
5944 !isa<CXXConstructorDecl>(Cand->Function))
5945 ArgIdx--;
5946 } else {
5947 // Builtin binary operator with a bad first conversion.
5948 assert(ConvCount <= 3);
5949 for (; ConvIdx != ConvCount; ++ConvIdx)
5950 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005951 = TryCopyInitialization(S, Args[ConvIdx],
5952 Cand->BuiltinTypes.ParamTypes[ConvIdx],
5953 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005954 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00005955 return;
5956 }
5957
5958 // Fill in the rest of the conversions.
5959 unsigned NumArgsInProto = Proto->getNumArgs();
5960 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
5961 if (ArgIdx < NumArgsInProto)
5962 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005963 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
5964 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005965 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00005966 else
5967 Cand->Conversions[ConvIdx].setEllipsis();
5968 }
5969}
5970
John McCalld3224162010-01-08 00:58:21 +00005971} // end anonymous namespace
5972
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005973/// PrintOverloadCandidates - When overload resolution fails, prints
5974/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00005975/// set.
Mike Stump11289f42009-09-09 15:08:12 +00005976void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005977Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00005978 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00005979 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005980 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00005981 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00005982 // Sort the candidates by viability and position. Sorting directly would
5983 // be prohibitive, so we make a set of pointers and sort those.
5984 llvm::SmallVector<OverloadCandidate*, 32> Cands;
5985 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
5986 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5987 LastCand = CandidateSet.end();
John McCallfe796dd2010-01-23 05:17:32 +00005988 Cand != LastCand; ++Cand) {
5989 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00005990 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00005991 else if (OCD == OCD_AllCandidates) {
5992 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00005993 if (Cand->Function || Cand->IsSurrogate)
5994 Cands.push_back(Cand);
5995 // Otherwise, this a non-viable builtin candidate. We do not, in general,
5996 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00005997 }
5998 }
5999
John McCallad2587a2010-01-12 00:48:53 +00006000 std::sort(Cands.begin(), Cands.end(),
6001 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00006002
John McCall0d1da222010-01-12 00:44:57 +00006003 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00006004
John McCall12f97bc2010-01-08 04:41:39 +00006005 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006006 const Diagnostic::OverloadsShown ShowOverloads = Diags.getShowOverloads();
6007 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00006008 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6009 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00006010
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006011 // Set an arbitrary limit on the number of candidate functions we'll spam
6012 // the user with. FIXME: This limit should depend on details of the
6013 // candidate list.
6014 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6015 break;
6016 }
6017 ++CandsShown;
6018
John McCalld3224162010-01-08 00:58:21 +00006019 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00006020 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00006021 else if (Cand->IsSurrogate)
6022 NoteSurrogateCandidate(*this, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006023 else {
6024 assert(Cand->Viable &&
6025 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00006026 // Generally we only see ambiguities including viable builtin
6027 // operators if overload resolution got screwed up by an
6028 // ambiguous user-defined conversion.
6029 //
6030 // FIXME: It's quite possible for different conversions to see
6031 // different ambiguities, though.
6032 if (!ReportedAmbiguousConversions) {
6033 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
6034 ReportedAmbiguousConversions = true;
6035 }
John McCalld3224162010-01-08 00:58:21 +00006036
John McCall0d1da222010-01-12 00:44:57 +00006037 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00006038 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00006039 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006040 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006041
6042 if (I != E)
Jeffrey Yasskin5d474d02010-06-11 06:58:43 +00006043 Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006044}
6045
John McCalla0296f72010-03-19 07:35:19 +00006046static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00006047 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00006048 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006049
John McCalla0296f72010-03-19 07:35:19 +00006050 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006051}
6052
Douglas Gregorcd695e52008-11-10 20:40:00 +00006053/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6054/// an overloaded function (C++ [over.over]), where @p From is an
6055/// expression with overloaded function type and @p ToType is the type
6056/// we're trying to resolve to. For example:
6057///
6058/// @code
6059/// int f(double);
6060/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00006061///
Douglas Gregorcd695e52008-11-10 20:40:00 +00006062/// int (*pfd)(double) = f; // selects f(double)
6063/// @endcode
6064///
6065/// This routine returns the resulting FunctionDecl if it could be
6066/// resolved, and NULL otherwise. When @p Complain is true, this
6067/// routine will emit diagnostics if there is an error.
6068FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006069Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00006070 bool Complain,
6071 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006072 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006073 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006074 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00006075 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006076 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00006077 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006078 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006079 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006080 FunctionType = MemTypePtr->getPointeeType();
6081 IsMember = true;
6082 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006083
Douglas Gregorcd695e52008-11-10 20:40:00 +00006084 // C++ [over.over]p1:
6085 // [...] [Note: any redundant set of parentheses surrounding the
6086 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00006087 // C++ [over.over]p1:
6088 // [...] The overloaded function name can be preceded by the &
6089 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00006090 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
6091 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6092 if (OvlExpr->hasExplicitTemplateArgs()) {
6093 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6094 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregorcd695e52008-11-10 20:40:00 +00006095 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00006096
6097 // We expect a pointer or reference to function, or a function pointer.
6098 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6099 if (!FunctionType->isFunctionType()) {
6100 if (Complain)
6101 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6102 << OvlExpr->getName() << ToType;
6103
6104 return 0;
6105 }
6106
6107 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006108
Douglas Gregorcd695e52008-11-10 20:40:00 +00006109 // Look through all of the overloaded functions, searching for one
6110 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00006111 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006112 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
6113
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006114 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00006115 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6116 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006117 // Look through any using declarations to find the underlying function.
6118 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6119
Douglas Gregorcd695e52008-11-10 20:40:00 +00006120 // C++ [over.over]p3:
6121 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00006122 // targets of type "pointer-to-function" or "reference-to-function."
6123 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006124 // type "pointer-to-member-function."
6125 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00006126
Mike Stump11289f42009-09-09 15:08:12 +00006127 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006128 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00006129 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006130 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00006131 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006132 // static when converting to member pointer.
6133 if (Method->isStatic() == IsMember)
6134 continue;
6135 } else if (IsMember)
6136 continue;
Mike Stump11289f42009-09-09 15:08:12 +00006137
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006138 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006139 // If the name is a function template, template argument deduction is
6140 // done (14.8.2.2), and if the argument deduction succeeds, the
6141 // resulting template argument list is used to generate a single
6142 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006143 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006144 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00006145 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006146 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00006147 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00006148 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00006149 FunctionType, Specialization, Info)) {
6150 // FIXME: make a note of the failed deduction for diagnostics.
6151 (void)Result;
6152 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006153 // FIXME: If the match isn't exact, shouldn't we just drop this as
6154 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00006155 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00006156 == Context.getCanonicalType(Specialization->getType()));
John McCalla0296f72010-03-19 07:35:19 +00006157 Matches.push_back(std::make_pair(I.getPair(),
6158 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor9b146582009-07-08 20:55:45 +00006159 }
John McCalld14a8642009-11-21 08:51:07 +00006160
6161 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00006162 }
Mike Stump11289f42009-09-09 15:08:12 +00006163
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006164 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006165 // Skip non-static functions when converting to pointer, and static
6166 // when converting to member pointer.
6167 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00006168 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00006169
6170 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00006171 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00006172 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006173 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006174 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00006175
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006176 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00006177 QualType ResultTy;
6178 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6179 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6180 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00006181 Matches.push_back(std::make_pair(I.getPair(),
6182 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006183 FoundNonTemplateFunction = true;
6184 }
Mike Stump11289f42009-09-09 15:08:12 +00006185 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006186 }
6187
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006188 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00006189 if (Matches.empty()) {
6190 if (Complain) {
6191 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6192 << OvlExpr->getName() << FunctionType;
6193 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6194 E = OvlExpr->decls_end();
6195 I != E; ++I)
6196 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6197 NoteOverloadCandidate(F);
6198 }
6199
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006200 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00006201 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006202 FunctionDecl *Result = Matches[0].second;
John McCall16df1e52010-03-30 21:47:33 +00006203 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006204 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCall58cc69d2010-01-27 01:50:18 +00006205 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00006206 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006207 return Result;
6208 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006209
6210 // C++ [over.over]p4:
6211 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00006212 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006213 // [...] and any given function template specialization F1 is
6214 // eliminated if the set contains a second function template
6215 // specialization whose function template is more specialized
6216 // than the function template of F1 according to the partial
6217 // ordering rules of 14.5.5.2.
6218
6219 // The algorithm specified above is quadratic. We instead use a
6220 // two-pass algorithm (similar to the one used to identify the
6221 // best viable function in an overload set) that identifies the
6222 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00006223
6224 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6225 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6226 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00006227
6228 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00006229 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006230 TPOC_Other, From->getLocStart(),
6231 PDiag(),
6232 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006233 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00006234 PDiag(diag::note_ovl_candidate)
6235 << (unsigned) oc_function_template);
John McCalla0296f72010-03-19 07:35:19 +00006236 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCall58cc69d2010-01-27 01:50:18 +00006237 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00006238 FoundResult = Matches[Result - MatchesCopy.begin()].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00006239 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00006240 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall4fa0d5f2010-05-06 18:15:07 +00006241 DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc());
6242 }
John McCall58cc69d2010-01-27 01:50:18 +00006243 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006244 }
Mike Stump11289f42009-09-09 15:08:12 +00006245
Douglas Gregorfae1d712009-09-26 03:56:17 +00006246 // [...] any function template specializations in the set are
6247 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00006248 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00006249 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00006250 ++I;
6251 else {
John McCalla0296f72010-03-19 07:35:19 +00006252 Matches[I] = Matches[--N];
6253 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00006254 }
6255 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00006256
Mike Stump11289f42009-09-09 15:08:12 +00006257 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006258 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00006259 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006260 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00006261 FoundResult = Matches[0].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00006262 if (Complain) {
John McCalla0296f72010-03-19 07:35:19 +00006263 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
John McCall4fa0d5f2010-05-06 18:15:07 +00006264 DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc());
6265 }
John McCalla0296f72010-03-19 07:35:19 +00006266 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006267 }
Mike Stump11289f42009-09-09 15:08:12 +00006268
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006269 // FIXME: We should probably return the same thing that BestViableFunction
6270 // returns (even if we issue the diagnostics here).
6271 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006272 << Matches[0].second->getDeclName();
6273 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6274 NoteOverloadCandidate(Matches[I].second);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006275 return 0;
6276}
6277
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006278/// \brief Given an expression that refers to an overloaded function, try to
6279/// resolve that overloaded function expression down to a single function.
6280///
6281/// This routine can only resolve template-ids that refer to a single function
6282/// template, where that template-id refers to a single template whose template
6283/// arguments are either provided by the template-id or have defaults,
6284/// as described in C++0x [temp.arg.explicit]p3.
6285FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6286 // C++ [over.over]p1:
6287 // [...] [Note: any redundant set of parentheses surrounding the
6288 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006289 // C++ [over.over]p1:
6290 // [...] The overloaded function name can be preceded by the &
6291 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00006292
6293 if (From->getType() != Context.OverloadTy)
6294 return 0;
6295
6296 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006297
6298 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00006299 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006300 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00006301
6302 TemplateArgumentListInfo ExplicitTemplateArgs;
6303 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006304
6305 // Look through all of the overloaded functions, searching for one
6306 // whose type matches exactly.
6307 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00006308 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6309 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006310 // C++0x [temp.arg.explicit]p3:
6311 // [...] In contexts where deduction is done and fails, or in contexts
6312 // where deduction is not done, if a template argument list is
6313 // specified and it, along with any default template arguments,
6314 // identifies a single function template specialization, then the
6315 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00006316 FunctionTemplateDecl *FunctionTemplate
6317 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006318
6319 // C++ [over.over]p2:
6320 // If the name is a function template, template argument deduction is
6321 // done (14.8.2.2), and if the argument deduction succeeds, the
6322 // resulting template argument list is used to generate a single
6323 // function template specialization, which is added to the set of
6324 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006325 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006326 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006327 if (TemplateDeductionResult Result
6328 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6329 Specialization, Info)) {
6330 // FIXME: make a note of the failed deduction for diagnostics.
6331 (void)Result;
6332 continue;
6333 }
6334
6335 // Multiple matches; we can't resolve to a single declaration.
6336 if (Matched)
6337 return 0;
6338
6339 Matched = Specialization;
6340 }
6341
6342 return Matched;
6343}
6344
Douglas Gregorcabea402009-09-22 15:41:20 +00006345/// \brief Add a single candidate to the overload set.
6346static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00006347 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00006348 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006349 Expr **Args, unsigned NumArgs,
6350 OverloadCandidateSet &CandidateSet,
6351 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00006352 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00006353 if (isa<UsingShadowDecl>(Callee))
6354 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6355
Douglas Gregorcabea402009-09-22 15:41:20 +00006356 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00006357 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00006358 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006359 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006360 return;
John McCalld14a8642009-11-21 08:51:07 +00006361 }
6362
6363 if (FunctionTemplateDecl *FuncTemplate
6364 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00006365 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6366 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006367 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00006368 return;
6369 }
6370
6371 assert(false && "unhandled case in overloaded call candidate");
6372
6373 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00006374}
6375
6376/// \brief Add the overload candidates named by callee and/or found by argument
6377/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00006378void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00006379 Expr **Args, unsigned NumArgs,
6380 OverloadCandidateSet &CandidateSet,
6381 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00006382
6383#ifndef NDEBUG
6384 // Verify that ArgumentDependentLookup is consistent with the rules
6385 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00006386 //
Douglas Gregorcabea402009-09-22 15:41:20 +00006387 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6388 // and let Y be the lookup set produced by argument dependent
6389 // lookup (defined as follows). If X contains
6390 //
6391 // -- a declaration of a class member, or
6392 //
6393 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00006394 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00006395 //
6396 // -- a declaration that is neither a function or a function
6397 // template
6398 //
6399 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00006400
John McCall57500772009-12-16 12:17:52 +00006401 if (ULE->requiresADL()) {
6402 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6403 E = ULE->decls_end(); I != E; ++I) {
6404 assert(!(*I)->getDeclContext()->isRecord());
6405 assert(isa<UsingShadowDecl>(*I) ||
6406 !(*I)->getDeclContext()->isFunctionOrMethod());
6407 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00006408 }
6409 }
6410#endif
6411
John McCall57500772009-12-16 12:17:52 +00006412 // It would be nice to avoid this copy.
6413 TemplateArgumentListInfo TABuffer;
6414 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6415 if (ULE->hasExplicitTemplateArgs()) {
6416 ULE->copyTemplateArgumentsInto(TABuffer);
6417 ExplicitTemplateArgs = &TABuffer;
6418 }
6419
6420 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6421 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00006422 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006423 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00006424 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00006425
John McCall57500772009-12-16 12:17:52 +00006426 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00006427 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6428 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006429 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006430 CandidateSet,
6431 PartialOverloading);
6432}
John McCalld681c392009-12-16 08:11:27 +00006433
6434/// Attempts to recover from a call where no functions were found.
6435///
6436/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00006437static Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006438BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00006439 UnresolvedLookupExpr *ULE,
6440 SourceLocation LParenLoc,
6441 Expr **Args, unsigned NumArgs,
6442 SourceLocation *CommaLocs,
6443 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00006444
6445 CXXScopeSpec SS;
6446 if (ULE->getQualifier()) {
6447 SS.setScopeRep(ULE->getQualifier());
6448 SS.setRange(ULE->getQualifierRange());
6449 }
6450
John McCall57500772009-12-16 12:17:52 +00006451 TemplateArgumentListInfo TABuffer;
6452 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6453 if (ULE->hasExplicitTemplateArgs()) {
6454 ULE->copyTemplateArgumentsInto(TABuffer);
6455 ExplicitTemplateArgs = &TABuffer;
6456 }
6457
John McCalld681c392009-12-16 08:11:27 +00006458 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6459 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00006460 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
Douglas Gregorb412e172010-07-25 18:17:45 +00006461 return SemaRef.ExprError();
John McCalld681c392009-12-16 08:11:27 +00006462
John McCall57500772009-12-16 12:17:52 +00006463 assert(!R.empty() && "lookup results empty despite recovery");
6464
6465 // Build an implicit member call if appropriate. Just drop the
6466 // casts and such from the call, we don't really care.
6467 Sema::OwningExprResult NewFn = SemaRef.ExprError();
6468 if ((*R.begin())->isCXXClassMember())
6469 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6470 else if (ExplicitTemplateArgs)
6471 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6472 else
6473 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6474
6475 if (NewFn.isInvalid())
Douglas Gregorb412e172010-07-25 18:17:45 +00006476 return SemaRef.ExprError();
John McCall57500772009-12-16 12:17:52 +00006477
6478 // This shouldn't cause an infinite loop because we're giving it
6479 // an expression with non-empty lookup results, which should never
6480 // end up here.
6481 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
6482 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
6483 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006484}
Douglas Gregor4038cf42010-06-08 17:35:15 +00006485
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006486/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00006487/// (which eventually refers to the declaration Func) and the call
6488/// arguments Args/NumArgs, attempt to resolve the function call down
6489/// to a specific function. If overload resolution succeeds, returns
6490/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00006491/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006492/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00006493Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006494Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00006495 SourceLocation LParenLoc,
6496 Expr **Args, unsigned NumArgs,
6497 SourceLocation *CommaLocs,
6498 SourceLocation RParenLoc) {
6499#ifndef NDEBUG
6500 if (ULE->requiresADL()) {
6501 // To do ADL, we must have found an unqualified name.
6502 assert(!ULE->getQualifier() && "qualified name with ADL");
6503
6504 // We don't perform ADL for implicit declarations of builtins.
6505 // Verify that this was correctly set up.
6506 FunctionDecl *F;
6507 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6508 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6509 F->getBuiltinID() && F->isImplicit())
6510 assert(0 && "performing ADL for builtin");
6511
6512 // We don't perform ADL in C.
6513 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6514 }
6515#endif
6516
John McCallbc077cf2010-02-08 23:07:23 +00006517 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00006518
John McCall57500772009-12-16 12:17:52 +00006519 // Add the functions denoted by the callee to the set of candidate
6520 // functions, including those from argument-dependent lookup.
6521 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00006522
6523 // If we found nothing, try to recover.
6524 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6525 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00006526 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006527 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall57500772009-12-16 12:17:52 +00006528 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006529
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006530 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006531 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00006532 case OR_Success: {
6533 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00006534 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006535 DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00006536 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00006537 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6538 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006539
6540 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00006541 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006542 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00006543 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006544 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006545 break;
6546
6547 case OR_Ambiguous:
6548 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00006549 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006550 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006551 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006552
6553 case OR_Deleted:
6554 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6555 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00006556 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00006557 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006558 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006559 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006560 }
6561
Douglas Gregorb412e172010-07-25 18:17:45 +00006562 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00006563 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006564}
6565
John McCall4c4c1df2010-01-26 03:27:55 +00006566static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00006567 return Functions.size() > 1 ||
6568 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6569}
6570
Douglas Gregor084d8552009-03-13 23:49:33 +00006571/// \brief Create a unary operation that may resolve to an overloaded
6572/// operator.
6573///
6574/// \param OpLoc The location of the operator itself (e.g., '*').
6575///
6576/// \param OpcIn The UnaryOperator::Opcode that describes this
6577/// operator.
6578///
6579/// \param Functions The set of non-member functions that will be
6580/// considered by overload resolution. The caller needs to build this
6581/// set based on the context using, e.g.,
6582/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6583/// set should not contain any member functions; those will be added
6584/// by CreateOverloadedUnaryOp().
6585///
6586/// \param input The input argument.
John McCall4c4c1df2010-01-26 03:27:55 +00006587Sema::OwningExprResult
6588Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6589 const UnresolvedSetImpl &Fns,
6590 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006591 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
6592 Expr *Input = (Expr *)input.get();
6593
6594 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6595 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6596 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6597
6598 Expr *Args[2] = { Input, 0 };
6599 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00006600
Douglas Gregor084d8552009-03-13 23:49:33 +00006601 // For post-increment and post-decrement, add the implicit '0' as
6602 // the second argument, so that we know this is a post-increment or
6603 // post-decrement.
6604 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
6605 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00006606 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00006607 SourceLocation());
6608 NumArgs = 2;
6609 }
6610
6611 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00006612 if (Fns.empty())
6613 return Owned(new (Context) UnaryOperator(input.takeAs<Expr>(),
6614 Opc,
6615 Context.DependentTy,
6616 OpLoc));
6617
John McCall58cc69d2010-01-27 01:50:18 +00006618 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006619 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006620 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006621 0, SourceRange(), OpName, OpLoc,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006622 /*ADL*/ true, IsOverloaded(Fns),
6623 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00006624 input.release();
6625 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6626 &Args[0], NumArgs,
6627 Context.DependentTy,
6628 OpLoc));
6629 }
6630
6631 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006632 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006633
6634 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006635 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00006636
6637 // Add operator candidates that are member functions.
6638 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6639
John McCall4c4c1df2010-01-26 03:27:55 +00006640 // Add candidates from ADL.
6641 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00006642 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00006643 /*ExplicitTemplateArgs*/ 0,
6644 CandidateSet);
6645
Douglas Gregor084d8552009-03-13 23:49:33 +00006646 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006647 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00006648
6649 // Perform overload resolution.
6650 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006651 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006652 case OR_Success: {
6653 // We found a built-in operator or an overloaded operator.
6654 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00006655
Douglas Gregor084d8552009-03-13 23:49:33 +00006656 if (FnDecl) {
6657 // We matched an overloaded operator. Build a call to that
6658 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00006659
Douglas Gregor084d8552009-03-13 23:49:33 +00006660 // Convert the arguments.
6661 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00006662 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006663
John McCall16df1e52010-03-30 21:47:33 +00006664 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6665 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00006666 return ExprError();
6667 } else {
6668 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00006669 OwningExprResult InputInit
6670 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006671 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00006672 SourceLocation(),
6673 move(input));
6674 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00006675 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006676
Douglas Gregore6600372009-12-23 17:40:29 +00006677 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006678 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00006679 }
6680
John McCall4fa0d5f2010-05-06 18:15:07 +00006681 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6682
Douglas Gregor084d8552009-03-13 23:49:33 +00006683 // Determine the result type
Douglas Gregor603d81b2010-07-13 08:18:22 +00006684 QualType ResultTy = FnDecl->getCallResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006685
Douglas Gregor084d8552009-03-13 23:49:33 +00006686 // Build the actual expression node.
6687 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6688 SourceLocation());
6689 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00006690
Douglas Gregor084d8552009-03-13 23:49:33 +00006691 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00006692 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006693 ExprOwningPtr<CallExpr> TheCall(this,
6694 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00006695 Args, NumArgs, ResultTy, OpLoc));
John McCall4fa0d5f2010-05-06 18:15:07 +00006696
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006697 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6698 FnDecl))
6699 return ExprError();
6700
6701 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00006702 } else {
6703 // We matched a built-in operator. Convert the arguments, then
6704 // break out so that we will build the appropriate built-in
6705 // operator node.
6706 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006707 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00006708 return ExprError();
6709
6710 break;
6711 }
6712 }
6713
6714 case OR_No_Viable_Function:
6715 // No viable function; fall through to handling this as a
6716 // built-in operator, which will produce an error message for us.
6717 break;
6718
6719 case OR_Ambiguous:
6720 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6721 << UnaryOperator::getOpcodeStr(Opc)
6722 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006723 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006724 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006725 return ExprError();
6726
6727 case OR_Deleted:
6728 Diag(OpLoc, diag::err_ovl_deleted_oper)
6729 << Best->Function->isDeleted()
6730 << UnaryOperator::getOpcodeStr(Opc)
6731 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006732 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00006733 return ExprError();
6734 }
6735
6736 // Either we found no viable overloaded operator or we matched a
6737 // built-in operator. In either case, fall through to trying to
6738 // build a built-in operation.
6739 input.release();
6740 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
6741}
6742
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006743/// \brief Create a binary operation that may resolve to an overloaded
6744/// operator.
6745///
6746/// \param OpLoc The location of the operator itself (e.g., '+').
6747///
6748/// \param OpcIn The BinaryOperator::Opcode that describes this
6749/// operator.
6750///
6751/// \param Functions The set of non-member functions that will be
6752/// considered by overload resolution. The caller needs to build this
6753/// set based on the context using, e.g.,
6754/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6755/// set should not contain any member functions; those will be added
6756/// by CreateOverloadedBinOp().
6757///
6758/// \param LHS Left-hand argument.
6759/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00006760Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006761Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006762 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00006763 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006764 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006765 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00006766 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006767
6768 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6769 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6770 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6771
6772 // If either side is type-dependent, create an appropriate dependent
6773 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00006774 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00006775 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006776 // If there are no functions to store, just build a dependent
6777 // BinaryOperator or CompoundAssignment.
6778 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
6779 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6780 Context.DependentTy, OpLoc));
6781
6782 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6783 Context.DependentTy,
6784 Context.DependentTy,
6785 Context.DependentTy,
6786 OpLoc));
6787 }
John McCall4c4c1df2010-01-26 03:27:55 +00006788
6789 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00006790 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006791 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006792 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006793 0, SourceRange(), OpName, OpLoc,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006794 /*ADL*/ true, IsOverloaded(Fns),
6795 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006796 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00006797 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006798 Context.DependentTy,
6799 OpLoc));
6800 }
6801
6802 // If this is the .* operator, which is not overloadable, just
6803 // create a built-in binary operator.
6804 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00006805 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006806
Sebastian Redl6a96bf72009-11-18 23:10:33 +00006807 // If this is the assignment operator, we only perform overload resolution
6808 // if the left-hand side is a class or enumeration type. This is actually
6809 // a hack. The standard requires that we do overload resolution between the
6810 // various built-in candidates, but as DR507 points out, this can lead to
6811 // problems. So we do it this way, which pretty much follows what GCC does.
6812 // Note that we go the traditional code path for compound assignment forms.
6813 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00006814 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006815
Douglas Gregor084d8552009-03-13 23:49:33 +00006816 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006817 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006818
6819 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006820 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006821
6822 // Add operator candidates that are member functions.
6823 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6824
John McCall4c4c1df2010-01-26 03:27:55 +00006825 // Add candidates from ADL.
6826 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6827 Args, 2,
6828 /*ExplicitTemplateArgs*/ 0,
6829 CandidateSet);
6830
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006831 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006832 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006833
6834 // Perform overload resolution.
6835 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006836 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00006837 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006838 // We found a built-in operator or an overloaded operator.
6839 FunctionDecl *FnDecl = Best->Function;
6840
6841 if (FnDecl) {
6842 // We matched an overloaded operator. Build a call to that
6843 // operator.
6844
6845 // Convert the arguments.
6846 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00006847 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00006848 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006849
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006850 OwningExprResult Arg1
6851 = PerformCopyInitialization(
6852 InitializedEntity::InitializeParameter(
6853 FnDecl->getParamDecl(0)),
6854 SourceLocation(),
6855 Owned(Args[1]));
6856 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006857 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006858
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006859 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006860 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006861 return ExprError();
6862
6863 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006864 } else {
6865 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006866 OwningExprResult Arg0
6867 = PerformCopyInitialization(
6868 InitializedEntity::InitializeParameter(
6869 FnDecl->getParamDecl(0)),
6870 SourceLocation(),
6871 Owned(Args[0]));
6872 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006873 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006874
6875 OwningExprResult Arg1
6876 = PerformCopyInitialization(
6877 InitializedEntity::InitializeParameter(
6878 FnDecl->getParamDecl(1)),
6879 SourceLocation(),
6880 Owned(Args[1]));
6881 if (Arg1.isInvalid())
6882 return ExprError();
6883 Args[0] = LHS = Arg0.takeAs<Expr>();
6884 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006885 }
6886
John McCall4fa0d5f2010-05-06 18:15:07 +00006887 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6888
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006889 // Determine the result type
6890 QualType ResultTy
Douglas Gregor603d81b2010-07-13 08:18:22 +00006891 = FnDecl->getType()->getAs<FunctionType>()
6892 ->getCallResultType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006893
6894 // Build the actual expression node.
6895 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00006896 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006897 UsualUnaryConversions(FnExpr);
6898
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006899 ExprOwningPtr<CXXOperatorCallExpr>
6900 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6901 Args, 2, ResultTy,
6902 OpLoc));
6903
6904 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6905 FnDecl))
6906 return ExprError();
6907
6908 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006909 } else {
6910 // We matched a built-in operator. Convert the arguments, then
6911 // break out so that we will build the appropriate built-in
6912 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00006913 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006914 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00006915 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006916 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006917 return ExprError();
6918
6919 break;
6920 }
6921 }
6922
Douglas Gregor66950a32009-09-30 21:46:01 +00006923 case OR_No_Viable_Function: {
6924 // C++ [over.match.oper]p9:
6925 // If the operator is the operator , [...] and there are no
6926 // viable functions, then the operator is assumed to be the
6927 // built-in operator and interpreted according to clause 5.
6928 if (Opc == BinaryOperator::Comma)
6929 break;
6930
Sebastian Redl027de2a2009-05-21 11:50:50 +00006931 // For class as left operand for assignment or compound assigment operator
6932 // do not fall through to handling in built-in, but report that no overloaded
6933 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00006934 OwningExprResult Result = ExprError();
6935 if (Args[0]->getType()->isRecordType() &&
6936 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00006937 Diag(OpLoc, diag::err_ovl_no_viable_oper)
6938 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006939 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00006940 } else {
6941 // No viable function; try to create a built-in operation, which will
6942 // produce an error. Then, show the non-viable candidates.
6943 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00006944 }
Douglas Gregor66950a32009-09-30 21:46:01 +00006945 assert(Result.isInvalid() &&
6946 "C++ binary operator overloading is missing candidates!");
6947 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00006948 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006949 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00006950 return move(Result);
6951 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006952
6953 case OR_Ambiguous:
6954 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6955 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006956 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006957 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006958 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006959 return ExprError();
6960
6961 case OR_Deleted:
6962 Diag(OpLoc, diag::err_ovl_deleted_oper)
6963 << Best->Function->isDeleted()
6964 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006965 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006966 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006967 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00006968 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006969
Douglas Gregor66950a32009-09-30 21:46:01 +00006970 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00006971 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006972}
6973
Sebastian Redladba46e2009-10-29 20:17:01 +00006974Action::OwningExprResult
6975Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
6976 SourceLocation RLoc,
6977 ExprArg Base, ExprArg Idx) {
6978 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
6979 static_cast<Expr*>(Idx.get()) };
6980 DeclarationName OpName =
6981 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
6982
6983 // If either side is type-dependent, create an appropriate dependent
6984 // expression.
6985 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
6986
John McCall58cc69d2010-01-27 01:50:18 +00006987 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006988 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006989 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006990 0, SourceRange(), OpName, LLoc,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006991 /*ADL*/ true, /*Overloaded*/ false,
6992 UnresolvedSetIterator(),
6993 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00006994 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00006995
6996 Base.release();
6997 Idx.release();
6998 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
6999 Args, 2,
7000 Context.DependentTy,
7001 RLoc));
7002 }
7003
7004 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007005 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007006
7007 // Subscript can only be overloaded as a member function.
7008
7009 // Add operator candidates that are member functions.
7010 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7011
7012 // Add builtin operator candidates.
7013 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7014
7015 // Perform overload resolution.
7016 OverloadCandidateSet::iterator Best;
7017 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
7018 case OR_Success: {
7019 // We found a built-in operator or an overloaded operator.
7020 FunctionDecl *FnDecl = Best->Function;
7021
7022 if (FnDecl) {
7023 // We matched an overloaded operator. Build a call to that
7024 // operator.
7025
John McCalla0296f72010-03-19 07:35:19 +00007026 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007027 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00007028
Sebastian Redladba46e2009-10-29 20:17:01 +00007029 // Convert the arguments.
7030 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007031 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007032 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00007033 return ExprError();
7034
Anders Carlssona68e51e2010-01-29 18:37:50 +00007035 // Convert the arguments.
7036 OwningExprResult InputInit
7037 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7038 FnDecl->getParamDecl(0)),
7039 SourceLocation(),
7040 Owned(Args[1]));
7041 if (InputInit.isInvalid())
7042 return ExprError();
7043
7044 Args[1] = InputInit.takeAs<Expr>();
7045
Sebastian Redladba46e2009-10-29 20:17:01 +00007046 // Determine the result type
7047 QualType ResultTy
Douglas Gregor603d81b2010-07-13 08:18:22 +00007048 = FnDecl->getType()->getAs<FunctionType>()
7049 ->getCallResultType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00007050
7051 // Build the actual expression node.
7052 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7053 LLoc);
7054 UsualUnaryConversions(FnExpr);
7055
7056 Base.release();
7057 Idx.release();
7058 ExprOwningPtr<CXXOperatorCallExpr>
7059 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7060 FnExpr, Args, 2,
7061 ResultTy, RLoc));
7062
7063 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
7064 FnDecl))
7065 return ExprError();
7066
7067 return MaybeBindToTemporary(TheCall.release());
7068 } else {
7069 // We matched a built-in operator. Convert the arguments, then
7070 // break out so that we will build the appropriate built-in
7071 // operator node.
7072 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007073 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00007074 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007075 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00007076 return ExprError();
7077
7078 break;
7079 }
7080 }
7081
7082 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00007083 if (CandidateSet.empty())
7084 Diag(LLoc, diag::err_ovl_no_oper)
7085 << Args[0]->getType() << /*subscript*/ 0
7086 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7087 else
7088 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7089 << Args[0]->getType()
7090 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007091 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00007092 "[]", LLoc);
7093 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00007094 }
7095
7096 case OR_Ambiguous:
7097 Diag(LLoc, diag::err_ovl_ambiguous_oper)
7098 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007099 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00007100 "[]", LLoc);
7101 return ExprError();
7102
7103 case OR_Deleted:
7104 Diag(LLoc, diag::err_ovl_deleted_oper)
7105 << Best->Function->isDeleted() << "[]"
7106 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007107 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00007108 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007109 return ExprError();
7110 }
7111
7112 // We matched a built-in operator; build it.
7113 Base.release();
7114 Idx.release();
7115 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
7116 Owned(Args[1]), RLoc);
7117}
7118
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007119/// BuildCallToMemberFunction - Build a call to a member
7120/// function. MemExpr is the expression that refers to the member
7121/// function (and includes the object parameter), Args/NumArgs are the
7122/// arguments to the function call (not including the object
7123/// parameter). The caller needs to validate that the member
7124/// expression refers to a member function or an overloaded member
7125/// function.
John McCall2d74de92009-12-01 22:10:20 +00007126Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00007127Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7128 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007129 unsigned NumArgs, SourceLocation *CommaLocs,
7130 SourceLocation RParenLoc) {
7131 // Dig out the member expression. This holds both the object
7132 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00007133 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7134
John McCall10eae182009-11-30 22:42:35 +00007135 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007136 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00007137 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007138 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00007139 if (isa<MemberExpr>(NakedMemExpr)) {
7140 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00007141 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00007142 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007143 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00007144 } else {
7145 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007146 Qualifier = UnresExpr->getQualifier();
7147
John McCall6e9f8f62009-12-03 04:06:58 +00007148 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00007149
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007150 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00007151 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00007152
John McCall2d74de92009-12-01 22:10:20 +00007153 // FIXME: avoid copy.
7154 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7155 if (UnresExpr->hasExplicitTemplateArgs()) {
7156 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7157 TemplateArgs = &TemplateArgsBuffer;
7158 }
7159
John McCall10eae182009-11-30 22:42:35 +00007160 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7161 E = UnresExpr->decls_end(); I != E; ++I) {
7162
John McCall6e9f8f62009-12-03 04:06:58 +00007163 NamedDecl *Func = *I;
7164 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7165 if (isa<UsingShadowDecl>(Func))
7166 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7167
John McCall10eae182009-11-30 22:42:35 +00007168 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00007169 // If explicit template arguments were provided, we can't call a
7170 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00007171 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00007172 continue;
7173
John McCalla0296f72010-03-19 07:35:19 +00007174 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00007175 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007176 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007177 } else {
John McCall10eae182009-11-30 22:42:35 +00007178 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00007179 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007180 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007181 CandidateSet,
7182 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007183 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007184 }
Mike Stump11289f42009-09-09 15:08:12 +00007185
John McCall10eae182009-11-30 22:42:35 +00007186 DeclarationName DeclName = UnresExpr->getMemberName();
7187
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007188 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00007189 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007190 case OR_Success:
7191 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007192 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00007193 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007194 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007195 break;
7196
7197 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00007198 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007199 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007200 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007201 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007202 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007203 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007204
7205 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00007206 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007207 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007208 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007209 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007210 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007211
7212 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00007213 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00007214 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00007215 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007216 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007217 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007218 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007219 }
7220
John McCall16df1e52010-03-30 21:47:33 +00007221 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00007222
John McCall2d74de92009-12-01 22:10:20 +00007223 // If overload resolution picked a static member, build a
7224 // non-member call based on that function.
7225 if (Method->isStatic()) {
7226 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7227 Args, NumArgs, RParenLoc);
7228 }
7229
John McCall10eae182009-11-30 22:42:35 +00007230 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007231 }
7232
7233 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00007234 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00007235 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00007236 NumArgs,
Douglas Gregor603d81b2010-07-13 08:18:22 +00007237 Method->getCallResultType(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007238 RParenLoc));
7239
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007240 // Check for a valid return type.
7241 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
7242 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00007243 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007244
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007245 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00007246 // We only need to do this if there was actually an overload; otherwise
7247 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00007248 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00007249 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00007250 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7251 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00007252 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007253 MemExpr->setBase(ObjectArg);
7254
7255 // Convert the rest of the arguments
Douglas Gregorc8be9522010-05-04 18:18:31 +00007256 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00007257 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007258 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00007259 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007260
Anders Carlssonbc4c1072009-08-16 01:56:34 +00007261 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00007262 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00007263
John McCall2d74de92009-12-01 22:10:20 +00007264 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007265}
7266
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007267/// BuildCallToObjectOfClassType - Build a call to an object of class
7268/// type (C++ [over.call.object]), which can end up invoking an
7269/// overloaded function call operator (@c operator()) or performing a
7270/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00007271Sema::ExprResult
7272Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00007273 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007274 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00007275 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007276 SourceLocation RParenLoc) {
7277 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007278 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00007279
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007280 // C++ [over.call.object]p1:
7281 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00007282 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007283 // candidate functions includes at least the function call
7284 // operators of T. The function call operators of T are obtained by
7285 // ordinary lookup of the name operator() in the context of
7286 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00007287 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00007288 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007289
7290 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007291 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007292 << Object->getSourceRange()))
7293 return true;
7294
John McCall27b18f82009-11-17 02:14:36 +00007295 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7296 LookupQualifiedName(R, Record->getDecl());
7297 R.suppressDiagnostics();
7298
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007299 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00007300 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007301 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00007302 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00007303 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00007304 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007305
Douglas Gregorab7897a2008-11-19 22:57:39 +00007306 // C++ [over.call.object]p2:
7307 // In addition, for each conversion function declared in T of the
7308 // form
7309 //
7310 // operator conversion-type-id () cv-qualifier;
7311 //
7312 // where cv-qualifier is the same cv-qualification as, or a
7313 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00007314 // denotes the type "pointer to function of (P1,...,Pn) returning
7315 // R", or the type "reference to pointer to function of
7316 // (P1,...,Pn) returning R", or the type "reference to function
7317 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00007318 // is also considered as a candidate function. Similarly,
7319 // surrogate call functions are added to the set of candidate
7320 // functions for each conversion function declared in an
7321 // accessible base class provided the function is not hidden
7322 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00007323 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00007324 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00007325 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00007326 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00007327 NamedDecl *D = *I;
7328 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7329 if (isa<UsingShadowDecl>(D))
7330 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7331
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007332 // Skip over templated conversion functions; they aren't
7333 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00007334 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007335 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007336
John McCall6e9f8f62009-12-03 04:06:58 +00007337 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00007338
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007339 // Strip the reference type (if any) and then the pointer type (if
7340 // any) to get down to what might be a function type.
7341 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7342 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7343 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007344
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007345 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00007346 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00007347 Object->getType(), Args, NumArgs,
7348 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007349 }
Mike Stump11289f42009-09-09 15:08:12 +00007350
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007351 // Perform overload resolution.
7352 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007353 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007354 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00007355 // Overload resolution succeeded; we'll build the appropriate call
7356 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007357 break;
7358
7359 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00007360 if (CandidateSet.empty())
7361 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7362 << Object->getType() << /*call*/ 1
7363 << Object->getSourceRange();
7364 else
7365 Diag(Object->getSourceRange().getBegin(),
7366 diag::err_ovl_no_viable_object_call)
7367 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007368 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007369 break;
7370
7371 case OR_Ambiguous:
7372 Diag(Object->getSourceRange().getBegin(),
7373 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007374 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007375 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007376 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007377
7378 case OR_Deleted:
7379 Diag(Object->getSourceRange().getBegin(),
7380 diag::err_ovl_deleted_object_call)
7381 << Best->Function->isDeleted()
7382 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007383 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007384 break;
Mike Stump11289f42009-09-09 15:08:12 +00007385 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007386
Douglas Gregorb412e172010-07-25 18:17:45 +00007387 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007388 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007389
Douglas Gregorab7897a2008-11-19 22:57:39 +00007390 if (Best->Function == 0) {
7391 // Since there is no function declaration, this is one of the
7392 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00007393 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00007394 = cast<CXXConversionDecl>(
7395 Best->Conversions[0].UserDefined.ConversionFunction);
7396
John McCalla0296f72010-03-19 07:35:19 +00007397 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007398 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007399
Douglas Gregorab7897a2008-11-19 22:57:39 +00007400 // We selected one of the surrogate functions that converts the
7401 // object parameter to a function pointer. Perform the conversion
7402 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00007403
7404 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007405 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00007406 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7407 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007408
Fariborz Jahanian774cf792009-09-28 18:35:46 +00007409 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007410 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
Douglas Gregore5e775b2010-04-13 15:50:39 +00007411 CommaLocs, RParenLoc).result();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007412 }
7413
John McCalla0296f72010-03-19 07:35:19 +00007414 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007415 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007416
Douglas Gregorab7897a2008-11-19 22:57:39 +00007417 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7418 // that calls this method, using Object for the implicit object
7419 // parameter and passing along the remaining arguments.
7420 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00007421 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007422
7423 unsigned NumArgsInProto = Proto->getNumArgs();
7424 unsigned NumArgsToCheck = NumArgs;
7425
7426 // Build the full argument list for the method call (the
7427 // implicit object parameter is placed at the beginning of the
7428 // list).
7429 Expr **MethodArgs;
7430 if (NumArgs < NumArgsInProto) {
7431 NumArgsToCheck = NumArgsInProto;
7432 MethodArgs = new Expr*[NumArgsInProto + 1];
7433 } else {
7434 MethodArgs = new Expr*[NumArgs + 1];
7435 }
7436 MethodArgs[0] = Object;
7437 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7438 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00007439
7440 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00007441 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007442 UsualUnaryConversions(NewFn);
7443
7444 // Once we've built TheCall, all of the expressions are properly
7445 // owned.
Douglas Gregor603d81b2010-07-13 08:18:22 +00007446 QualType ResultTy = Method->getCallResultType();
Mike Stump11289f42009-09-09 15:08:12 +00007447 ExprOwningPtr<CXXOperatorCallExpr>
7448 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007449 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00007450 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007451 delete [] MethodArgs;
7452
Anders Carlsson3d5829c2009-10-13 21:49:31 +00007453 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
7454 Method))
7455 return true;
7456
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007457 // We may have default arguments. If so, we need to allocate more
7458 // slots in the call for them.
7459 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00007460 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007461 else if (NumArgs > NumArgsInProto)
7462 NumArgsToCheck = NumArgsInProto;
7463
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007464 bool IsError = false;
7465
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007466 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007467 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007468 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007469 TheCall->setArg(0, Object);
7470
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007471
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007472 // Check the argument types.
7473 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007474 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007475 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007476 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00007477
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007478 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007479
7480 OwningExprResult InputInit
7481 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7482 Method->getParamDecl(i)),
7483 SourceLocation(), Owned(Arg));
7484
7485 IsError |= InputInit.isInvalid();
7486 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007487 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00007488 OwningExprResult DefArg
7489 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7490 if (DefArg.isInvalid()) {
7491 IsError = true;
7492 break;
7493 }
7494
7495 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007496 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007497
7498 TheCall->setArg(i + 1, Arg);
7499 }
7500
7501 // If this is a variadic call, handle args passed through "...".
7502 if (Proto->isVariadic()) {
7503 // Promote the arguments (C99 6.5.2.2p7).
7504 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7505 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00007506 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007507 TheCall->setArg(i + 1, Arg);
7508 }
7509 }
7510
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007511 if (IsError) return true;
7512
Anders Carlssonbc4c1072009-08-16 01:56:34 +00007513 if (CheckFunctionCall(Method, TheCall.get()))
7514 return true;
7515
Douglas Gregore5e775b2010-04-13 15:50:39 +00007516 return MaybeBindToTemporary(TheCall.release()).result();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007517}
7518
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007519/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00007520/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007521/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00007522Sema::OwningExprResult
7523Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
7524 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007525 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00007526
John McCallbc077cf2010-02-08 23:07:23 +00007527 SourceLocation Loc = Base->getExprLoc();
7528
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007529 // C++ [over.ref]p1:
7530 //
7531 // [...] An expression x->m is interpreted as (x.operator->())->m
7532 // for a class object x of type T if T::operator->() exists and if
7533 // the operator is selected as the best match function by the
7534 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007535 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00007536 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007537 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00007538
John McCallbc077cf2010-02-08 23:07:23 +00007539 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00007540 PDiag(diag::err_typecheck_incomplete_tag)
7541 << Base->getSourceRange()))
7542 return ExprError();
7543
John McCall27b18f82009-11-17 02:14:36 +00007544 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7545 LookupQualifiedName(R, BaseRecord->getDecl());
7546 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00007547
7548 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00007549 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007550 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007551 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00007552 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007553
7554 // Perform overload resolution.
7555 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007556 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007557 case OR_Success:
7558 // Overload resolution succeeded; we'll build the call below.
7559 break;
7560
7561 case OR_No_Viable_Function:
7562 if (CandidateSet.empty())
7563 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00007564 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007565 else
7566 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00007567 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007568 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007569 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007570
7571 case OR_Ambiguous:
7572 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00007573 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007574 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007575 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007576
7577 case OR_Deleted:
7578 Diag(OpLoc, diag::err_ovl_deleted_oper)
7579 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00007580 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007581 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007582 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007583 }
7584
John McCalla0296f72010-03-19 07:35:19 +00007585 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007586 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00007587
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007588 // Convert the object parameter.
7589 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007590 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7591 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00007592 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00007593
7594 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00007595 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007596
7597 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00007598 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7599 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007600 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007601
Douglas Gregor603d81b2010-07-13 08:18:22 +00007602 QualType ResultTy = Method->getCallResultType();
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007603 ExprOwningPtr<CXXOperatorCallExpr>
7604 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7605 &Base, 1, ResultTy, OpLoc));
7606
7607 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
7608 Method))
7609 return ExprError();
7610 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007611}
7612
Douglas Gregorcd695e52008-11-10 20:40:00 +00007613/// FixOverloadedFunctionReference - E is an expression that refers to
7614/// a C++ overloaded function (possibly with some parentheses and
7615/// perhaps a '&' around it). We have resolved the overloaded function
7616/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007617/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00007618Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00007619 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00007620 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007621 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7622 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007623 if (SubExpr == PE->getSubExpr())
7624 return PE->Retain();
7625
7626 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7627 }
7628
7629 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007630 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7631 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00007632 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00007633 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00007634 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00007635 if (SubExpr == ICE->getSubExpr())
7636 return ICE->Retain();
7637
7638 return new (Context) ImplicitCastExpr(ICE->getType(),
7639 ICE->getCastKind(),
Anders Carlsson0c509ee2010-04-24 16:57:13 +00007640 SubExpr, CXXBaseSpecifierArray(),
Sebastian Redlc57d34b2010-07-20 04:20:21 +00007641 ICE->getCategory());
Douglas Gregor51c538b2009-11-20 19:42:02 +00007642 }
7643
7644 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00007645 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00007646 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007647 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7648 if (Method->isStatic()) {
7649 // Do nothing: static member functions aren't any different
7650 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00007651 } else {
John McCalle66edc12009-11-24 19:00:30 +00007652 // Fix the sub expression, which really has to be an
7653 // UnresolvedLookupExpr holding an overloaded member function
7654 // or template.
John McCall16df1e52010-03-30 21:47:33 +00007655 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7656 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00007657 if (SubExpr == UnOp->getSubExpr())
7658 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00007659
John McCalld14a8642009-11-21 08:51:07 +00007660 assert(isa<DeclRefExpr>(SubExpr)
7661 && "fixed to something other than a decl ref");
7662 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7663 && "fixed to a member ref with no nested name qualifier");
7664
7665 // We have taken the address of a pointer to member
7666 // function. Perform the computation here so that we get the
7667 // appropriate pointer to member type.
7668 QualType ClassType
7669 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7670 QualType MemPtrType
7671 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7672
7673 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7674 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007675 }
7676 }
John McCall16df1e52010-03-30 21:47:33 +00007677 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7678 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007679 if (SubExpr == UnOp->getSubExpr())
7680 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007681
Douglas Gregor51c538b2009-11-20 19:42:02 +00007682 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7683 Context.getPointerType(SubExpr->getType()),
7684 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00007685 }
John McCalld14a8642009-11-21 08:51:07 +00007686
7687 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00007688 // FIXME: avoid copy.
7689 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00007690 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00007691 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7692 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00007693 }
7694
John McCalld14a8642009-11-21 08:51:07 +00007695 return DeclRefExpr::Create(Context,
7696 ULE->getQualifier(),
7697 ULE->getQualifierRange(),
7698 Fn,
7699 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00007700 Fn->getType(),
7701 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00007702 }
7703
John McCall10eae182009-11-30 22:42:35 +00007704 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00007705 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00007706 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7707 if (MemExpr->hasExplicitTemplateArgs()) {
7708 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7709 TemplateArgs = &TemplateArgsBuffer;
7710 }
John McCall6b51f282009-11-23 01:53:49 +00007711
John McCall2d74de92009-12-01 22:10:20 +00007712 Expr *Base;
7713
7714 // If we're filling in
7715 if (MemExpr->isImplicitAccess()) {
7716 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7717 return DeclRefExpr::Create(Context,
7718 MemExpr->getQualifier(),
7719 MemExpr->getQualifierRange(),
7720 Fn,
7721 MemExpr->getMemberLoc(),
7722 Fn->getType(),
7723 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00007724 } else {
7725 SourceLocation Loc = MemExpr->getMemberLoc();
7726 if (MemExpr->getQualifier())
7727 Loc = MemExpr->getQualifierRange().getBegin();
7728 Base = new (Context) CXXThisExpr(Loc,
7729 MemExpr->getBaseType(),
7730 /*isImplicit=*/true);
7731 }
John McCall2d74de92009-12-01 22:10:20 +00007732 } else
7733 Base = MemExpr->getBase()->Retain();
7734
7735 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007736 MemExpr->isArrow(),
7737 MemExpr->getQualifier(),
7738 MemExpr->getQualifierRange(),
7739 Fn,
John McCall16df1e52010-03-30 21:47:33 +00007740 Found,
John McCall6b51f282009-11-23 01:53:49 +00007741 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00007742 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007743 Fn->getType());
7744 }
7745
Douglas Gregor51c538b2009-11-20 19:42:02 +00007746 assert(false && "Invalid reference to overloaded function");
7747 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00007748}
7749
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007750Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCalla8ae2222010-04-06 21:38:20 +00007751 DeclAccessPair Found,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007752 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00007753 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007754}
7755
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007756} // end namespace clang