blob: 339a79384c2ac796095e790c96cdf2921ee49ed8 [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 Gregor836a7e82010-08-11 02:15:33 +0000688 // C++ [over.ics.user]p4:
689 // A conversion of an expression of class type to the same class
690 // type is given Exact Match rank, and a conversion of an
691 // expression of class type to a base class of that type is
692 // given Conversion rank, in spite of the fact that a copy/move
693 // constructor (i.e., a user-defined conversion function) is
694 // called for those cases.
695 QualType FromType = From->getType();
696 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
697 (Context.hasSameUnqualifiedType(FromType, ToType) ||
698 IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000699 ICS.setStandard();
700 ICS.Standard.setAsIdentityConversion();
701 ICS.Standard.setFromType(FromType);
702 ICS.Standard.setAllToTypes(ToType);
703
704 // We don't actually check at this point whether there is a valid
705 // copy/move constructor, since overloading just assumes that it
706 // exists. When we actually perform initialization, we'll find the
707 // appropriate constructor to copy the returned object, if needed.
708 ICS.Standard.CopyConstructor = 0;
Douglas Gregor836a7e82010-08-11 02:15:33 +0000709
Douglas Gregor5ab11652010-04-17 22:01:05 +0000710 // Determine whether this is considered a derived-to-base conversion.
711 if (!Context.hasSameUnqualifiedType(FromType, ToType))
712 ICS.Standard.Second = ICK_Derived_To_Base;
Douglas Gregor836a7e82010-08-11 02:15:33 +0000713
714 return ICS;
715 }
716
717 if (SuppressUserConversions) {
718 // We're not in the case above, so there is no conversion that
719 // we can perform.
720 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor5ab11652010-04-17 22:01:05 +0000721 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 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000853
854 // We can perform the conversion between vector types in the following cases:
855 // 1)vector types are equivalent AltiVec and GCC vector types
856 // 2)lax vector conversions are permitted and the vector types are of the
857 // same size
858 if (ToType->isVectorType() && FromType->isVectorType()) {
859 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +0000860 (Context.getLangOptions().LaxVectorConversions &&
861 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000862 ICK = ICK_Vector_Conversion;
863 return true;
864 }
Douglas Gregor46188682010-05-18 22:42:18 +0000865 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000866
Douglas Gregor46188682010-05-18 22:42:18 +0000867 return false;
868}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000869
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000870/// IsStandardConversion - Determines whether there is a standard
871/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
872/// expression From to the type ToType. Standard conversion sequences
873/// only consider non-class types; for conversions that involve class
874/// types, use TryImplicitConversion. If a conversion exists, SCS will
875/// contain the standard conversion sequence required to perform this
876/// conversion and this routine will return true. Otherwise, this
877/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000878bool
879Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000880 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000881 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000882 QualType FromType = From->getType();
883
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000884 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000885 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000886 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000887 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000888 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000889 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000890
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000891 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000892 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000893 if (FromType->isRecordType() || ToType->isRecordType()) {
894 if (getLangOptions().CPlusPlus)
895 return false;
896
Mike Stump11289f42009-09-09 15:08:12 +0000897 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000898 }
899
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000900 // The first conversion can be an lvalue-to-rvalue conversion,
901 // array-to-pointer conversion, or function-to-pointer conversion
902 // (C++ 4p1).
903
Douglas Gregor980fb162010-04-29 18:24:40 +0000904 if (FromType == Context.OverloadTy) {
905 DeclAccessPair AccessPair;
906 if (FunctionDecl *Fn
907 = ResolveAddressOfOverloadedFunction(From, ToType, false,
908 AccessPair)) {
909 // We were able to resolve the address of the overloaded function,
910 // so we can convert to the type of that function.
911 FromType = Fn->getType();
912 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
913 if (!Method->isStatic()) {
914 Type *ClassType
915 = Context.getTypeDeclType(Method->getParent()).getTypePtr();
916 FromType = Context.getMemberPointerType(FromType, ClassType);
917 }
918 }
919
920 // If the "from" expression takes the address of the overloaded
921 // function, update the type of the resulting expression accordingly.
922 if (FromType->getAs<FunctionType>())
923 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
924 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
925 FromType = Context.getPointerType(FromType);
926
927 // Check that we've computed the proper type after overload resolution.
928 assert(Context.hasSameType(FromType,
929 FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
930 } else {
931 return false;
932 }
933 }
Mike Stump11289f42009-09-09 15:08:12 +0000934 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000935 // An lvalue (3.10) of a non-function, non-array type T can be
936 // converted to an rvalue.
937 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000938 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000939 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000940 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000941 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000942
943 // If T is a non-class type, the type of the rvalue is the
944 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000945 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
946 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000947 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000948 } else if (FromType->isArrayType()) {
949 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000950 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000951
952 // An lvalue or rvalue of type "array of N T" or "array of unknown
953 // bound of T" can be converted to an rvalue of type "pointer to
954 // T" (C++ 4.2p1).
955 FromType = Context.getArrayDecayedType(FromType);
956
957 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
958 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +0000959 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000960
961 // For the purpose of ranking in overload resolution
962 // (13.3.3.1.1), this conversion is considered an
963 // array-to-pointer conversion followed by a qualification
964 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000965 SCS.Second = ICK_Identity;
966 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000967 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000968 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000969 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000970 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
971 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000972 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000973
974 // An lvalue of function type T can be converted to an rvalue of
975 // type "pointer to T." The result is a pointer to the
976 // function. (C++ 4.3p1).
977 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000978 } else {
979 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000980 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000981 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000982 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000983
984 // The second conversion can be an integral promotion, floating
985 // point promotion, integral conversion, floating point conversion,
986 // floating-integral conversion, pointer conversion,
987 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000988 // For overloading in C, this can also be a "compatible-type"
989 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000990 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +0000991 ImplicitConversionKind SecondICK = ICK_Identity;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000992 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000993 // The unqualified versions of the types are the same: there's no
994 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000995 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000996 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000997 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000998 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000999 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001000 } else if (IsFloatingPointPromotion(FromType, ToType)) {
1001 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001002 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001003 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001004 } else if (IsComplexPromotion(FromType, ToType)) {
1005 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001006 SCS.Second = ICK_Complex_Promotion;
1007 FromType = ToType.getUnqualifiedType();
Douglas Gregorb90df602010-06-16 00:17:44 +00001008 } else if (FromType->isIntegralOrEnumerationType() &&
Douglas Gregor6972a622010-06-16 00:35:25 +00001009 ToType->isIntegralType(Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001010 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001011 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001012 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001013 } else if (FromType->isComplexType() && ToType->isComplexType()) {
1014 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001015 SCS.Second = ICK_Complex_Conversion;
1016 FromType = ToType.getUnqualifiedType();
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001017 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
1018 (ToType->isComplexType() && FromType->isArithmeticType())) {
1019 // Complex-real conversions (C99 6.3.1.7)
1020 SCS.Second = ICK_Complex_Real;
1021 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001022 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001023 // Floating point conversions (C++ 4.8).
1024 SCS.Second = ICK_Floating_Conversion;
1025 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001026 } else if ((FromType->isRealFloatingType() &&
Douglas Gregor6972a622010-06-16 00:35:25 +00001027 ToType->isIntegralType(Context) && !ToType->isBooleanType()) ||
Douglas Gregorb90df602010-06-16 00:17:44 +00001028 (FromType->isIntegralOrEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001029 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001030 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001031 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001032 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +00001033 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1034 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001035 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001036 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001037 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +00001038 } else if (IsMemberPointerConversion(From, FromType, ToType,
1039 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001040 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001041 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +00001042 } else if (ToType->isBooleanType() &&
1043 (FromType->isArithmeticType() ||
1044 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +00001045 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +00001046 FromType->isBlockPointerType() ||
1047 FromType->isMemberPointerType() ||
Douglas Gregora3208f92010-06-22 23:41:02 +00001048 FromType->isNullPtrType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001049 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001050 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001051 FromType = Context.BoolTy;
Douglas Gregor46188682010-05-18 22:42:18 +00001052 } else if (IsVectorConversion(Context, FromType, ToType, SecondICK)) {
1053 SCS.Second = SecondICK;
1054 FromType = ToType.getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001055 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +00001056 Context.typesAreCompatible(ToType, FromType)) {
1057 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001058 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001059 FromType = ToType.getUnqualifiedType();
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001060 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
1061 // Treat a conversion that strips "noreturn" as an identity conversion.
1062 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001063 } else {
1064 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001065 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001066 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001067 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001068
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001069 QualType CanonFrom;
1070 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001071 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +00001072 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001073 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001074 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001075 CanonFrom = Context.getCanonicalType(FromType);
1076 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001077 } else {
1078 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001079 SCS.Third = ICK_Identity;
1080
Mike Stump11289f42009-09-09 15:08:12 +00001081 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001082 // [...] Any difference in top-level cv-qualification is
1083 // subsumed by the initialization itself and does not constitute
1084 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001085 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +00001086 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001087 if (CanonFrom.getLocalUnqualifiedType()
1088 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001089 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1090 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001091 FromType = ToType;
1092 CanonFrom = CanonTo;
1093 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001094 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001095 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001096
1097 // If we have not converted the argument type to the parameter type,
1098 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001099 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001100 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001101
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001102 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001103}
1104
1105/// IsIntegralPromotion - Determines whether the conversion from the
1106/// expression From (whose potentially-adjusted type is FromType) to
1107/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1108/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001109bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001110 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001111 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001112 if (!To) {
1113 return false;
1114 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001115
1116 // An rvalue of type char, signed char, unsigned char, short int, or
1117 // unsigned short int can be converted to an rvalue of type int if
1118 // int can represent all the values of the source type; otherwise,
1119 // the source rvalue can be converted to an rvalue of type unsigned
1120 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001121 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1122 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001123 if (// We can promote any signed, promotable integer type to an int
1124 (FromType->isSignedIntegerType() ||
1125 // We can promote any unsigned integer type whose size is
1126 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001127 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001128 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001129 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001130 }
1131
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001132 return To->getKind() == BuiltinType::UInt;
1133 }
1134
1135 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
1136 // can be converted to an rvalue of the first of the following types
1137 // that can represent all the values of its underlying type: int,
1138 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +00001139
1140 // We pre-calculate the promotion type for enum types.
1141 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
1142 if (ToType->isIntegerType())
1143 return Context.hasSameUnqualifiedType(ToType,
1144 FromEnumType->getDecl()->getPromotionType());
1145
1146 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001147 // Determine whether the type we're converting from is signed or
1148 // unsigned.
1149 bool FromIsSigned;
1150 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +00001151
1152 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1153 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001154
1155 // The types we'll try to promote to, in the appropriate
1156 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001157 QualType PromoteTypes[6] = {
1158 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001159 Context.LongTy, Context.UnsignedLongTy ,
1160 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001161 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001162 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001163 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1164 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001165 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001166 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1167 // We found the type that we can promote to. If this is the
1168 // type we wanted, we have a promotion. Otherwise, no
1169 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001170 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001171 }
1172 }
1173 }
1174
1175 // An rvalue for an integral bit-field (9.6) can be converted to an
1176 // rvalue of type int if int can represent all the values of the
1177 // bit-field; otherwise, it can be converted to unsigned int if
1178 // unsigned int can represent all the values of the bit-field. If
1179 // the bit-field is larger yet, no integral promotion applies to
1180 // it. If the bit-field has an enumerated type, it is treated as any
1181 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001182 // FIXME: We should delay checking of bit-fields until we actually perform the
1183 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001184 using llvm::APSInt;
1185 if (From)
1186 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001187 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001188 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001189 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1190 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1191 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001192
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001193 // Are we promoting to an int from a bitfield that fits in an int?
1194 if (BitWidth < ToSize ||
1195 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1196 return To->getKind() == BuiltinType::Int;
1197 }
Mike Stump11289f42009-09-09 15:08:12 +00001198
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001199 // Are we promoting to an unsigned int from an unsigned bitfield
1200 // that fits into an unsigned int?
1201 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1202 return To->getKind() == BuiltinType::UInt;
1203 }
Mike Stump11289f42009-09-09 15:08:12 +00001204
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001205 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001206 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001207 }
Mike Stump11289f42009-09-09 15:08:12 +00001208
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001209 // An rvalue of type bool can be converted to an rvalue of type int,
1210 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001211 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001212 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001213 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001214
1215 return false;
1216}
1217
1218/// IsFloatingPointPromotion - Determines whether the conversion from
1219/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1220/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001221bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001222 /// An rvalue of type float can be converted to an rvalue of type
1223 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001224 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1225 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001226 if (FromBuiltin->getKind() == BuiltinType::Float &&
1227 ToBuiltin->getKind() == BuiltinType::Double)
1228 return true;
1229
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001230 // C99 6.3.1.5p1:
1231 // When a float is promoted to double or long double, or a
1232 // double is promoted to long double [...].
1233 if (!getLangOptions().CPlusPlus &&
1234 (FromBuiltin->getKind() == BuiltinType::Float ||
1235 FromBuiltin->getKind() == BuiltinType::Double) &&
1236 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1237 return true;
1238 }
1239
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001240 return false;
1241}
1242
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001243/// \brief Determine if a conversion is a complex promotion.
1244///
1245/// A complex promotion is defined as a complex -> complex conversion
1246/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001247/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001248bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001249 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001250 if (!FromComplex)
1251 return false;
1252
John McCall9dd450b2009-09-21 23:43:11 +00001253 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001254 if (!ToComplex)
1255 return false;
1256
1257 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001258 ToComplex->getElementType()) ||
1259 IsIntegralPromotion(0, FromComplex->getElementType(),
1260 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001261}
1262
Douglas Gregor237f96c2008-11-26 23:31:11 +00001263/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1264/// the pointer type FromPtr to a pointer to type ToPointee, with the
1265/// same type qualifiers as FromPtr has on its pointee type. ToType,
1266/// if non-empty, will be a pointer to ToType that may or may not have
1267/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001268static QualType
1269BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001270 QualType ToPointee, QualType ToType,
1271 ASTContext &Context) {
1272 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1273 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001274 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001275
1276 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001277 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001278 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001279 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001280 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001281
1282 // Build a pointer to ToPointee. It has the right qualifiers
1283 // already.
1284 return Context.getPointerType(ToPointee);
1285 }
1286
1287 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +00001288 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001289 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1290 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +00001291}
1292
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001293/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1294/// the FromType, which is an objective-c pointer, to ToType, which may or may
1295/// not have the right set of qualifiers.
1296static QualType
1297BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1298 QualType ToType,
1299 ASTContext &Context) {
1300 QualType CanonFromType = Context.getCanonicalType(FromType);
1301 QualType CanonToType = Context.getCanonicalType(ToType);
1302 Qualifiers Quals = CanonFromType.getQualifiers();
1303
1304 // Exact qualifier match -> return the pointer type we're converting to.
1305 if (CanonToType.getLocalQualifiers() == Quals)
1306 return ToType;
1307
1308 // Just build a canonical type that has the right qualifiers.
1309 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1310}
1311
Mike Stump11289f42009-09-09 15:08:12 +00001312static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001313 bool InOverloadResolution,
1314 ASTContext &Context) {
1315 // Handle value-dependent integral null pointer constants correctly.
1316 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1317 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001318 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001319 return !InOverloadResolution;
1320
Douglas Gregor56751b52009-09-25 04:25:58 +00001321 return Expr->isNullPointerConstant(Context,
1322 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1323 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001324}
Mike Stump11289f42009-09-09 15:08:12 +00001325
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001326/// IsPointerConversion - Determines whether the conversion of the
1327/// expression From, which has the (possibly adjusted) type FromType,
1328/// can be converted to the type ToType via a pointer conversion (C++
1329/// 4.10). If so, returns true and places the converted type (that
1330/// might differ from ToType in its cv-qualifiers at some level) into
1331/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001332///
Douglas Gregora29dc052008-11-27 01:19:21 +00001333/// This routine also supports conversions to and from block pointers
1334/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1335/// pointers to interfaces. FIXME: Once we've determined the
1336/// appropriate overloading rules for Objective-C, we may want to
1337/// split the Objective-C checks into a different routine; however,
1338/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001339/// conversions, so for now they live here. IncompatibleObjC will be
1340/// set if the conversion is an allowed Objective-C conversion that
1341/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001342bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001343 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001344 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001345 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001346 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001347 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1348 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001349
Mike Stump11289f42009-09-09 15:08:12 +00001350 // Conversion from a null pointer constant to any Objective-C pointer type.
1351 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001352 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001353 ConvertedType = ToType;
1354 return true;
1355 }
1356
Douglas Gregor231d1c62008-11-27 00:15:41 +00001357 // Blocks: Block pointers can be converted to void*.
1358 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001359 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001360 ConvertedType = ToType;
1361 return true;
1362 }
1363 // Blocks: A null pointer constant can be converted to a block
1364 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001365 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001366 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001367 ConvertedType = ToType;
1368 return true;
1369 }
1370
Sebastian Redl576fd422009-05-10 18:38:11 +00001371 // If the left-hand-side is nullptr_t, the right side can be a null
1372 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001373 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001374 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001375 ConvertedType = ToType;
1376 return true;
1377 }
1378
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001379 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001380 if (!ToTypePtr)
1381 return false;
1382
1383 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001384 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001385 ConvertedType = ToType;
1386 return true;
1387 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001388
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001389 // Beyond this point, both types need to be pointers
1390 // , including objective-c pointers.
1391 QualType ToPointeeType = ToTypePtr->getPointeeType();
1392 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1393 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1394 ToType, Context);
1395 return true;
1396
1397 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001398 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001399 if (!FromTypePtr)
1400 return false;
1401
1402 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001403
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001404 // An rvalue of type "pointer to cv T," where T is an object type,
1405 // can be converted to an rvalue of type "pointer to cv void" (C++
1406 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001407 if (FromPointeeType->isIncompleteOrObjectType() &&
1408 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001409 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001410 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001411 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001412 return true;
1413 }
1414
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001415 // When we're overloading in C, we allow a special kind of pointer
1416 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001417 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001418 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001419 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001420 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001421 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001422 return true;
1423 }
1424
Douglas Gregor5c407d92008-10-23 00:40:37 +00001425 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001426 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001427 // An rvalue of type "pointer to cv D," where D is a class type,
1428 // can be converted to an rvalue of type "pointer to cv B," where
1429 // B is a base class (clause 10) of D. If B is an inaccessible
1430 // (clause 11) or ambiguous (10.2) base class of D, a program that
1431 // necessitates this conversion is ill-formed. The result of the
1432 // conversion is a pointer to the base class sub-object of the
1433 // derived class object. The null pointer value is converted to
1434 // the null pointer value of the destination type.
1435 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001436 // Note that we do not check for ambiguity or inaccessibility
1437 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001438 if (getLangOptions().CPlusPlus &&
1439 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001440 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001441 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001442 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001443 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001444 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001445 ToType, Context);
1446 return true;
1447 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001448
Douglas Gregora119f102008-12-19 19:13:09 +00001449 return false;
1450}
1451
1452/// isObjCPointerConversion - Determines whether this is an
1453/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1454/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001455bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001456 QualType& ConvertedType,
1457 bool &IncompatibleObjC) {
1458 if (!getLangOptions().ObjC1)
1459 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001460
Steve Naroff7cae42b2009-07-10 23:34:53 +00001461 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001462 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001463 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001464 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001465
Steve Naroff7cae42b2009-07-10 23:34:53 +00001466 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001467 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001468 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001469 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001470 ConvertedType = ToType;
1471 return true;
1472 }
1473 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001474 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001475 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001476 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001477 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001478 ConvertedType = ToType;
1479 return true;
1480 }
1481 // Objective C++: We're able to convert from a pointer to an
1482 // interface to a pointer to a different interface.
1483 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001484 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1485 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1486 if (getLangOptions().CPlusPlus && LHS && RHS &&
1487 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1488 FromObjCPtr->getPointeeType()))
1489 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001490 ConvertedType = ToType;
1491 return true;
1492 }
1493
1494 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1495 // Okay: this is some kind of implicit downcast of Objective-C
1496 // interfaces, which is permitted. However, we're going to
1497 // complain about it.
1498 IncompatibleObjC = true;
1499 ConvertedType = FromType;
1500 return true;
1501 }
Mike Stump11289f42009-09-09 15:08:12 +00001502 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001503 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001504 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001505 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001506 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001507 else if (const BlockPointerType *ToBlockPtr =
1508 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001509 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001510 // to a block pointer type.
1511 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1512 ConvertedType = ToType;
1513 return true;
1514 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001515 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001516 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001517 else if (FromType->getAs<BlockPointerType>() &&
1518 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1519 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001520 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001521 ConvertedType = ToType;
1522 return true;
1523 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001524 else
Douglas Gregora119f102008-12-19 19:13:09 +00001525 return false;
1526
Douglas Gregor033f56d2008-12-23 00:53:59 +00001527 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001528 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001529 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001530 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001531 FromPointeeType = FromBlockPtr->getPointeeType();
1532 else
Douglas Gregora119f102008-12-19 19:13:09 +00001533 return false;
1534
Douglas Gregora119f102008-12-19 19:13:09 +00001535 // If we have pointers to pointers, recursively check whether this
1536 // is an Objective-C conversion.
1537 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1538 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1539 IncompatibleObjC)) {
1540 // We always complain about this conversion.
1541 IncompatibleObjC = true;
1542 ConvertedType = ToType;
1543 return true;
1544 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001545 // Allow conversion of pointee being objective-c pointer to another one;
1546 // as in I* to id.
1547 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1548 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1549 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1550 IncompatibleObjC)) {
1551 ConvertedType = ToType;
1552 return true;
1553 }
1554
Douglas Gregor033f56d2008-12-23 00:53:59 +00001555 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001556 // differences in the argument and result types are in Objective-C
1557 // pointer conversions. If so, we permit the conversion (but
1558 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001559 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001560 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001561 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001562 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001563 if (FromFunctionType && ToFunctionType) {
1564 // If the function types are exactly the same, this isn't an
1565 // Objective-C pointer conversion.
1566 if (Context.getCanonicalType(FromPointeeType)
1567 == Context.getCanonicalType(ToPointeeType))
1568 return false;
1569
1570 // Perform the quick checks that will tell us whether these
1571 // function types are obviously different.
1572 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1573 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1574 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1575 return false;
1576
1577 bool HasObjCConversion = false;
1578 if (Context.getCanonicalType(FromFunctionType->getResultType())
1579 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1580 // Okay, the types match exactly. Nothing to do.
1581 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1582 ToFunctionType->getResultType(),
1583 ConvertedType, IncompatibleObjC)) {
1584 // Okay, we have an Objective-C pointer conversion.
1585 HasObjCConversion = true;
1586 } else {
1587 // Function types are too different. Abort.
1588 return false;
1589 }
Mike Stump11289f42009-09-09 15:08:12 +00001590
Douglas Gregora119f102008-12-19 19:13:09 +00001591 // Check argument types.
1592 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1593 ArgIdx != NumArgs; ++ArgIdx) {
1594 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1595 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1596 if (Context.getCanonicalType(FromArgType)
1597 == Context.getCanonicalType(ToArgType)) {
1598 // Okay, the types match exactly. Nothing to do.
1599 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1600 ConvertedType, IncompatibleObjC)) {
1601 // Okay, we have an Objective-C pointer conversion.
1602 HasObjCConversion = true;
1603 } else {
1604 // Argument types are too different. Abort.
1605 return false;
1606 }
1607 }
1608
1609 if (HasObjCConversion) {
1610 // We had an Objective-C conversion. Allow this pointer
1611 // conversion, but complain about it.
1612 ConvertedType = ToType;
1613 IncompatibleObjC = true;
1614 return true;
1615 }
1616 }
1617
Sebastian Redl72b597d2009-01-25 19:43:20 +00001618 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001619}
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001620
1621/// FunctionArgTypesAreEqual - This routine checks two function proto types
1622/// for equlity of their argument types. Caller has already checked that
1623/// they have same number of arguments. This routine assumes that Objective-C
1624/// pointer types which only differ in their protocol qualifiers are equal.
1625bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1626 FunctionProtoType* NewType){
1627 if (!getLangOptions().ObjC1)
1628 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1629 NewType->arg_type_begin());
1630
1631 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1632 N = NewType->arg_type_begin(),
1633 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1634 QualType ToType = (*O);
1635 QualType FromType = (*N);
1636 if (ToType != FromType) {
1637 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1638 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001639 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1640 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1641 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1642 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001643 continue;
1644 }
John McCall8b07ec22010-05-15 11:32:37 +00001645 else if (const ObjCObjectPointerType *PTTo =
1646 ToType->getAs<ObjCObjectPointerType>()) {
1647 if (const ObjCObjectPointerType *PTFr =
1648 FromType->getAs<ObjCObjectPointerType>())
1649 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1650 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001651 }
1652 return false;
1653 }
1654 }
1655 return true;
1656}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001657
Douglas Gregor39c16d42008-10-24 04:54:22 +00001658/// CheckPointerConversion - Check the pointer conversion from the
1659/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001660/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001661/// conversions for which IsPointerConversion has already returned
1662/// true. It returns true and produces a diagnostic if there was an
1663/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001664bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001665 CastExpr::CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001666 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001667 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001668 QualType FromType = From->getType();
1669
Douglas Gregor4038cf42010-06-08 17:35:15 +00001670 if (CXXBoolLiteralExpr* LitBool
1671 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
1672 if (LitBool->getValue() == false)
1673 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1674 << ToType;
1675
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001676 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1677 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001678 QualType FromPointeeType = FromPtrType->getPointeeType(),
1679 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001680
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001681 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1682 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001683 // We must have a derived-to-base conversion. Check an
1684 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001685 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1686 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001687 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001688 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001689 return true;
1690
1691 // The conversion was successful.
1692 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001693 }
1694 }
Mike Stump11289f42009-09-09 15:08:12 +00001695 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001696 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001697 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001698 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001699 // Objective-C++ conversions are always okay.
1700 // FIXME: We should have a different class of conversions for the
1701 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001702 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001703 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001704
Steve Naroff7cae42b2009-07-10 23:34:53 +00001705 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001706 return false;
1707}
1708
Sebastian Redl72b597d2009-01-25 19:43:20 +00001709/// IsMemberPointerConversion - Determines whether the conversion of the
1710/// expression From, which has the (possibly adjusted) type FromType, can be
1711/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1712/// If so, returns true and places the converted type (that might differ from
1713/// ToType in its cv-qualifiers at some level) into ConvertedType.
1714bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001715 QualType ToType,
1716 bool InOverloadResolution,
1717 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001718 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001719 if (!ToTypePtr)
1720 return false;
1721
1722 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001723 if (From->isNullPointerConstant(Context,
1724 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1725 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001726 ConvertedType = ToType;
1727 return true;
1728 }
1729
1730 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001731 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001732 if (!FromTypePtr)
1733 return false;
1734
1735 // A pointer to member of B can be converted to a pointer to member of D,
1736 // where D is derived from B (C++ 4.11p2).
1737 QualType FromClass(FromTypePtr->getClass(), 0);
1738 QualType ToClass(ToTypePtr->getClass(), 0);
1739 // FIXME: What happens when these are dependent? Is this function even called?
1740
1741 if (IsDerivedFrom(ToClass, FromClass)) {
1742 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1743 ToClass.getTypePtr());
1744 return true;
1745 }
1746
1747 return false;
1748}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001749
Sebastian Redl72b597d2009-01-25 19:43:20 +00001750/// CheckMemberPointerConversion - Check the member pointer conversion from the
1751/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001752/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001753/// for which IsMemberPointerConversion has already returned true. It returns
1754/// true and produces a diagnostic if there was an error, or returns false
1755/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001756bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001757 CastExpr::CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001758 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001759 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001760 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001761 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001762 if (!FromPtrType) {
1763 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001764 assert(From->isNullPointerConstant(Context,
1765 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001766 "Expr must be null pointer constant!");
1767 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001768 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001769 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001770
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001771 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001772 assert(ToPtrType && "No member pointer cast has a target type "
1773 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001774
Sebastian Redled8f2002009-01-28 18:33:18 +00001775 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1776 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001777
Sebastian Redled8f2002009-01-28 18:33:18 +00001778 // FIXME: What about dependent types?
1779 assert(FromClass->isRecordType() && "Pointer into non-class.");
1780 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001781
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001782 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001783 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001784 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1785 assert(DerivationOkay &&
1786 "Should not have been called if derivation isn't OK.");
1787 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001788
Sebastian Redled8f2002009-01-28 18:33:18 +00001789 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1790 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001791 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1792 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1793 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1794 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001795 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001796
Douglas Gregor89ee6822009-02-28 01:32:25 +00001797 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001798 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1799 << FromClass << ToClass << QualType(VBase, 0)
1800 << From->getSourceRange();
1801 return true;
1802 }
1803
John McCall5b0829a2010-02-10 09:31:12 +00001804 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001805 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1806 Paths.front(),
1807 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001808
Anders Carlssond7923c62009-08-22 23:33:40 +00001809 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001810 BuildBasePathArray(Paths, BasePath);
Anders Carlssond7923c62009-08-22 23:33:40 +00001811 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001812 return false;
1813}
1814
Douglas Gregor9a657932008-10-21 23:43:52 +00001815/// IsQualificationConversion - Determines whether the conversion from
1816/// an rvalue of type FromType to ToType is a qualification conversion
1817/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001818bool
1819Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001820 FromType = Context.getCanonicalType(FromType);
1821 ToType = Context.getCanonicalType(ToType);
1822
1823 // If FromType and ToType are the same type, this is not a
1824 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001825 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001826 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001827
Douglas Gregor9a657932008-10-21 23:43:52 +00001828 // (C++ 4.4p4):
1829 // A conversion can add cv-qualifiers at levels other than the first
1830 // in multi-level pointers, subject to the following rules: [...]
1831 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001832 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001833 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001834 // Within each iteration of the loop, we check the qualifiers to
1835 // determine if this still looks like a qualification
1836 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001837 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001838 // until there are no more pointers or pointers-to-members left to
1839 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001840 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001841
1842 // -- for every j > 0, if const is in cv 1,j then const is in cv
1843 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001844 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001845 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001846
Douglas Gregor9a657932008-10-21 23:43:52 +00001847 // -- if the cv 1,j and cv 2,j are different, then const is in
1848 // every cv for 0 < k < j.
1849 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001850 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001851 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001852
Douglas Gregor9a657932008-10-21 23:43:52 +00001853 // Keep track of whether all prior cv-qualifiers in the "to" type
1854 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001855 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001856 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001857 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001858
1859 // We are left with FromType and ToType being the pointee types
1860 // after unwrapping the original FromType and ToType the same number
1861 // of types. If we unwrapped any pointers, and if FromType and
1862 // ToType have the same unqualified type (since we checked
1863 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001864 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001865}
1866
Douglas Gregor576e98c2009-01-30 23:27:23 +00001867/// Determines whether there is a user-defined conversion sequence
1868/// (C++ [over.ics.user]) that converts expression From to the type
1869/// ToType. If such a conversion exists, User will contain the
1870/// user-defined conversion sequence that performs such a conversion
1871/// and this routine will return true. Otherwise, this routine returns
1872/// false and User is unspecified.
1873///
Douglas Gregor576e98c2009-01-30 23:27:23 +00001874/// \param AllowExplicit true if the conversion should consider C++0x
1875/// "explicit" conversion functions as well as non-explicit conversion
1876/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001877OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1878 UserDefinedConversionSequence& User,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001879 OverloadCandidateSet& CandidateSet,
1880 bool AllowExplicit) {
1881 // Whether we will only visit constructors.
1882 bool ConstructorsOnly = false;
1883
1884 // If the type we are conversion to is a class type, enumerate its
1885 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001886 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001887 // C++ [over.match.ctor]p1:
1888 // When objects of class type are direct-initialized (8.5), or
1889 // copy-initialized from an expression of the same or a
1890 // derived class type (8.5), overload resolution selects the
1891 // constructor. [...] For copy-initialization, the candidate
1892 // functions are all the converting constructors (12.3.1) of
1893 // that class. The argument list is the expression-list within
1894 // the parentheses of the initializer.
1895 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1896 (From->getType()->getAs<RecordType>() &&
1897 IsDerivedFrom(From->getType(), ToType)))
1898 ConstructorsOnly = true;
1899
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001900 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1901 // We're not going to find any constructors.
1902 } else if (CXXRecordDecl *ToRecordDecl
1903 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001904 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00001905 for (llvm::tie(Con, ConEnd) = LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001906 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00001907 NamedDecl *D = *Con;
1908 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1909
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001910 // Find the constructor (which may be a template).
1911 CXXConstructorDecl *Constructor = 0;
1912 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00001913 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001914 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001915 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001916 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1917 else
John McCalla0296f72010-03-19 07:35:19 +00001918 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001919
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001920 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001921 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001922 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00001923 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001924 /*ExplicitArgs*/ 0,
John McCall6b51f282009-11-23 01:53:49 +00001925 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001926 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001927 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001928 // Allow one user-defined conversion when user specifies a
1929 // From->ToType conversion via an static cast (c-style, etc).
John McCalla0296f72010-03-19 07:35:19 +00001930 AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001931 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001932 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001933 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001934 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001935 }
1936 }
1937
Douglas Gregor5ab11652010-04-17 22:01:05 +00001938 // Enumerate conversion functions, if we're allowed to.
1939 if (ConstructorsOnly) {
Mike Stump11289f42009-09-09 15:08:12 +00001940 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
Douglas Gregor5ab11652010-04-17 22:01:05 +00001941 PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001942 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001943 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00001944 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001945 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001946 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1947 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00001948 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001949 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001950 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001951 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00001952 DeclAccessPair FoundDecl = I.getPair();
1953 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00001954 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1955 if (isa<UsingShadowDecl>(D))
1956 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1957
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001958 CXXConversionDecl *Conv;
1959 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00001960 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1961 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001962 else
John McCallda4458e2010-03-31 01:36:47 +00001963 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001964
1965 if (AllowExplicit || !Conv->isExplicit()) {
1966 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00001967 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001968 ActingContext, From, ToType,
1969 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001970 else
John McCalla0296f72010-03-19 07:35:19 +00001971 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCallb89836b2010-01-26 01:37:31 +00001972 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001973 }
1974 }
1975 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001976 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001977
1978 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001979 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001980 case OR_Success:
1981 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001982 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001983 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1984 // C++ [over.ics.user]p1:
1985 // If the user-defined conversion is specified by a
1986 // constructor (12.3.1), the initial standard conversion
1987 // sequence converts the source type to the type required by
1988 // the argument of the constructor.
1989 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001990 QualType ThisType = Constructor->getThisType(Context);
John McCall0d1da222010-01-12 00:44:57 +00001991 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian55824512009-11-06 00:23:08 +00001992 User.EllipsisConversion = true;
1993 else {
1994 User.Before = Best->Conversions[0].Standard;
1995 User.EllipsisConversion = false;
1996 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001997 User.ConversionFunction = Constructor;
1998 User.After.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00001999 User.After.setFromType(
2000 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002001 User.After.setAllToTypes(ToType);
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002002 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002003 } else if (CXXConversionDecl *Conversion
2004 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2005 // C++ [over.ics.user]p1:
2006 //
2007 // [...] If the user-defined conversion is specified by a
2008 // conversion function (12.3.2), the initial standard
2009 // conversion sequence converts the source type to the
2010 // implicit object parameter of the conversion function.
2011 User.Before = Best->Conversions[0].Standard;
2012 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002013 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002014
2015 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00002016 // The second standard conversion sequence converts the
2017 // result of the user-defined conversion to the target type
2018 // for the sequence. Since an implicit conversion sequence
2019 // is an initialization, the special rules for
2020 // initialization by user-defined conversion apply when
2021 // selecting the best user-defined conversion for a
2022 // user-defined conversion sequence (see 13.3.3 and
2023 // 13.3.3.1).
2024 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002025 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002026 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002027 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002028 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002029 }
Mike Stump11289f42009-09-09 15:08:12 +00002030
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002031 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002032 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00002033 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002034 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002035 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002036
2037 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002038 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002039 }
2040
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002041 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002042}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002043
2044bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002045Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002046 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002047 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002048 OverloadingResult OvResult =
2049 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002050 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002051 if (OvResult == OR_Ambiguous)
2052 Diag(From->getSourceRange().getBegin(),
2053 diag::err_typecheck_ambiguous_condition)
2054 << From->getType() << ToType << From->getSourceRange();
2055 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2056 Diag(From->getSourceRange().getBegin(),
2057 diag::err_typecheck_nonviable_condition)
2058 << From->getType() << ToType << From->getSourceRange();
2059 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002060 return false;
John McCallad907772010-01-12 07:18:19 +00002061 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002062 return true;
2063}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002064
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002065/// CompareImplicitConversionSequences - Compare two implicit
2066/// conversion sequences to determine whether one is better than the
2067/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00002068ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002069Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
2070 const ImplicitConversionSequence& ICS2)
2071{
2072 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2073 // conversion sequences (as defined in 13.3.3.1)
2074 // -- a standard conversion sequence (13.3.3.1.1) is a better
2075 // conversion sequence than a user-defined conversion sequence or
2076 // an ellipsis conversion sequence, and
2077 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2078 // conversion sequence than an ellipsis conversion sequence
2079 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002080 //
John McCall0d1da222010-01-12 00:44:57 +00002081 // C++0x [over.best.ics]p10:
2082 // For the purpose of ranking implicit conversion sequences as
2083 // described in 13.3.3.2, the ambiguous conversion sequence is
2084 // treated as a user-defined sequence that is indistinguishable
2085 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002086 if (ICS1.getKindRank() < ICS2.getKindRank())
2087 return ImplicitConversionSequence::Better;
2088 else if (ICS2.getKindRank() < ICS1.getKindRank())
2089 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002090
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002091 // The following checks require both conversion sequences to be of
2092 // the same kind.
2093 if (ICS1.getKind() != ICS2.getKind())
2094 return ImplicitConversionSequence::Indistinguishable;
2095
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002096 // Two implicit conversion sequences of the same form are
2097 // indistinguishable conversion sequences unless one of the
2098 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002099 if (ICS1.isStandard())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002100 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002101 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002102 // User-defined conversion sequence U1 is a better conversion
2103 // sequence than another user-defined conversion sequence U2 if
2104 // they contain the same user-defined conversion function or
2105 // constructor and if the second standard conversion sequence of
2106 // U1 is better than the second standard conversion sequence of
2107 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002108 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002109 ICS2.UserDefined.ConversionFunction)
2110 return CompareStandardConversionSequences(ICS1.UserDefined.After,
2111 ICS2.UserDefined.After);
2112 }
2113
2114 return ImplicitConversionSequence::Indistinguishable;
2115}
2116
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002117static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2118 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2119 Qualifiers Quals;
2120 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2121 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2122 }
2123
2124 return Context.hasSameUnqualifiedType(T1, T2);
2125}
2126
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002127// Per 13.3.3.2p3, compare the given standard conversion sequences to
2128// determine if one is a proper subset of the other.
2129static ImplicitConversionSequence::CompareKind
2130compareStandardConversionSubsets(ASTContext &Context,
2131 const StandardConversionSequence& SCS1,
2132 const StandardConversionSequence& SCS2) {
2133 ImplicitConversionSequence::CompareKind Result
2134 = ImplicitConversionSequence::Indistinguishable;
2135
Douglas Gregore87561a2010-05-23 22:10:15 +00002136 // the identity conversion sequence is considered to be a subsequence of
2137 // any non-identity conversion sequence
2138 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2139 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2140 return ImplicitConversionSequence::Better;
2141 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2142 return ImplicitConversionSequence::Worse;
2143 }
2144
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002145 if (SCS1.Second != SCS2.Second) {
2146 if (SCS1.Second == ICK_Identity)
2147 Result = ImplicitConversionSequence::Better;
2148 else if (SCS2.Second == ICK_Identity)
2149 Result = ImplicitConversionSequence::Worse;
2150 else
2151 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002152 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002153 return ImplicitConversionSequence::Indistinguishable;
2154
2155 if (SCS1.Third == SCS2.Third) {
2156 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2157 : ImplicitConversionSequence::Indistinguishable;
2158 }
2159
2160 if (SCS1.Third == ICK_Identity)
2161 return Result == ImplicitConversionSequence::Worse
2162 ? ImplicitConversionSequence::Indistinguishable
2163 : ImplicitConversionSequence::Better;
2164
2165 if (SCS2.Third == ICK_Identity)
2166 return Result == ImplicitConversionSequence::Better
2167 ? ImplicitConversionSequence::Indistinguishable
2168 : ImplicitConversionSequence::Worse;
2169
2170 return ImplicitConversionSequence::Indistinguishable;
2171}
2172
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002173/// CompareStandardConversionSequences - Compare two standard
2174/// conversion sequences to determine whether one is better than the
2175/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002176ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002177Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
2178 const StandardConversionSequence& SCS2)
2179{
2180 // Standard conversion sequence S1 is a better conversion sequence
2181 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2182
2183 // -- S1 is a proper subsequence of S2 (comparing the conversion
2184 // sequences in the canonical form defined by 13.3.3.1.1,
2185 // excluding any Lvalue Transformation; the identity conversion
2186 // sequence is considered to be a subsequence of any
2187 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002188 if (ImplicitConversionSequence::CompareKind CK
2189 = compareStandardConversionSubsets(Context, SCS1, SCS2))
2190 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002191
2192 // -- the rank of S1 is better than the rank of S2 (by the rules
2193 // defined below), or, if not that,
2194 ImplicitConversionRank Rank1 = SCS1.getRank();
2195 ImplicitConversionRank Rank2 = SCS2.getRank();
2196 if (Rank1 < Rank2)
2197 return ImplicitConversionSequence::Better;
2198 else if (Rank2 < Rank1)
2199 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002200
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002201 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2202 // are indistinguishable unless one of the following rules
2203 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002204
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002205 // A conversion that is not a conversion of a pointer, or
2206 // pointer to member, to bool is better than another conversion
2207 // that is such a conversion.
2208 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2209 return SCS2.isPointerConversionToBool()
2210 ? ImplicitConversionSequence::Better
2211 : ImplicitConversionSequence::Worse;
2212
Douglas Gregor5c407d92008-10-23 00:40:37 +00002213 // C++ [over.ics.rank]p4b2:
2214 //
2215 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002216 // conversion of B* to A* is better than conversion of B* to
2217 // void*, and conversion of A* to void* is better than conversion
2218 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002219 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00002220 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00002221 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00002222 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002223 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2224 // Exactly one of the conversion sequences is a conversion to
2225 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002226 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2227 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002228 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2229 // Neither conversion sequence converts to a void pointer; compare
2230 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002231 if (ImplicitConversionSequence::CompareKind DerivedCK
2232 = CompareDerivedToBaseConversions(SCS1, SCS2))
2233 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002234 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2235 // Both conversion sequences are conversions to void
2236 // pointers. Compare the source types to determine if there's an
2237 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002238 QualType FromType1 = SCS1.getFromType();
2239 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002240
2241 // Adjust the types we're converting from via the array-to-pointer
2242 // conversion, if we need to.
2243 if (SCS1.First == ICK_Array_To_Pointer)
2244 FromType1 = Context.getArrayDecayedType(FromType1);
2245 if (SCS2.First == ICK_Array_To_Pointer)
2246 FromType2 = Context.getArrayDecayedType(FromType2);
2247
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002248 QualType FromPointee1
2249 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2250 QualType FromPointee2
2251 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002252
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002253 if (IsDerivedFrom(FromPointee2, FromPointee1))
2254 return ImplicitConversionSequence::Better;
2255 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2256 return ImplicitConversionSequence::Worse;
2257
2258 // Objective-C++: If one interface is more specific than the
2259 // other, it is the better one.
John McCall8b07ec22010-05-15 11:32:37 +00002260 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2261 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002262 if (FromIface1 && FromIface1) {
2263 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2264 return ImplicitConversionSequence::Better;
2265 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2266 return ImplicitConversionSequence::Worse;
2267 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002268 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002269
2270 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2271 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002272 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002273 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002274 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002275
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002276 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00002277 // C++0x [over.ics.rank]p3b4:
2278 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2279 // implicit object parameter of a non-static member function declared
2280 // without a ref-qualifier, and S1 binds an rvalue reference to an
2281 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00002282 // FIXME: We don't know if we're dealing with the implicit object parameter,
2283 // or if the member function in this case has a ref qualifier.
2284 // (Of course, we don't have ref qualifiers yet.)
2285 if (SCS1.RRefBinding != SCS2.RRefBinding)
2286 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2287 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00002288
2289 // C++ [over.ics.rank]p3b4:
2290 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2291 // which the references refer are the same type except for
2292 // top-level cv-qualifiers, and the type to which the reference
2293 // initialized by S2 refers is more cv-qualified than the type
2294 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002295 QualType T1 = SCS1.getToType(2);
2296 QualType T2 = SCS2.getToType(2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002297 T1 = Context.getCanonicalType(T1);
2298 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002299 Qualifiers T1Quals, T2Quals;
2300 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2301 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2302 if (UnqualT1 == UnqualT2) {
2303 // If the type is an array type, promote the element qualifiers to the type
2304 // for comparison.
2305 if (isa<ArrayType>(T1) && T1Quals)
2306 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2307 if (isa<ArrayType>(T2) && T2Quals)
2308 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002309 if (T2.isMoreQualifiedThan(T1))
2310 return ImplicitConversionSequence::Better;
2311 else if (T1.isMoreQualifiedThan(T2))
2312 return ImplicitConversionSequence::Worse;
2313 }
2314 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002315
2316 return ImplicitConversionSequence::Indistinguishable;
2317}
2318
2319/// CompareQualificationConversions - Compares two standard conversion
2320/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002321/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2322ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002323Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00002324 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002325 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002326 // -- S1 and S2 differ only in their qualification conversion and
2327 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2328 // cv-qualification signature of type T1 is a proper subset of
2329 // the cv-qualification signature of type T2, and S1 is not the
2330 // deprecated string literal array-to-pointer conversion (4.2).
2331 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2332 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2333 return ImplicitConversionSequence::Indistinguishable;
2334
2335 // FIXME: the example in the standard doesn't use a qualification
2336 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002337 QualType T1 = SCS1.getToType(2);
2338 QualType T2 = SCS2.getToType(2);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002339 T1 = Context.getCanonicalType(T1);
2340 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002341 Qualifiers T1Quals, T2Quals;
2342 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2343 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002344
2345 // If the types are the same, we won't learn anything by unwrapped
2346 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002347 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002348 return ImplicitConversionSequence::Indistinguishable;
2349
Chandler Carruth607f38e2009-12-29 07:16:59 +00002350 // If the type is an array type, promote the element qualifiers to the type
2351 // for comparison.
2352 if (isa<ArrayType>(T1) && T1Quals)
2353 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2354 if (isa<ArrayType>(T2) && T2Quals)
2355 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2356
Mike Stump11289f42009-09-09 15:08:12 +00002357 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002358 = ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002359 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002360 // Within each iteration of the loop, we check the qualifiers to
2361 // determine if this still looks like a qualification
2362 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002363 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002364 // until there are no more pointers or pointers-to-members left
2365 // to unwrap. This essentially mimics what
2366 // IsQualificationConversion does, but here we're checking for a
2367 // strict subset of qualifiers.
2368 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2369 // The qualifiers are the same, so this doesn't tell us anything
2370 // about how the sequences rank.
2371 ;
2372 else if (T2.isMoreQualifiedThan(T1)) {
2373 // T1 has fewer qualifiers, so it could be the better sequence.
2374 if (Result == ImplicitConversionSequence::Worse)
2375 // Neither has qualifiers that are a subset of the other's
2376 // qualifiers.
2377 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002378
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002379 Result = ImplicitConversionSequence::Better;
2380 } else if (T1.isMoreQualifiedThan(T2)) {
2381 // T2 has fewer qualifiers, so it could be the better sequence.
2382 if (Result == ImplicitConversionSequence::Better)
2383 // Neither has qualifiers that are a subset of the other's
2384 // qualifiers.
2385 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002386
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002387 Result = ImplicitConversionSequence::Worse;
2388 } else {
2389 // Qualifiers are disjoint.
2390 return ImplicitConversionSequence::Indistinguishable;
2391 }
2392
2393 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002394 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002395 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002396 }
2397
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002398 // Check that the winning standard conversion sequence isn't using
2399 // the deprecated string literal array to pointer conversion.
2400 switch (Result) {
2401 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002402 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002403 Result = ImplicitConversionSequence::Indistinguishable;
2404 break;
2405
2406 case ImplicitConversionSequence::Indistinguishable:
2407 break;
2408
2409 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002410 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002411 Result = ImplicitConversionSequence::Indistinguishable;
2412 break;
2413 }
2414
2415 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002416}
2417
Douglas Gregor5c407d92008-10-23 00:40:37 +00002418/// CompareDerivedToBaseConversions - Compares two standard conversion
2419/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002420/// various kinds of derived-to-base conversions (C++
2421/// [over.ics.rank]p4b3). As part of these checks, we also look at
2422/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002423ImplicitConversionSequence::CompareKind
2424Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2425 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002426 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002427 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002428 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002429 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002430
2431 // Adjust the types we're converting from via the array-to-pointer
2432 // conversion, if we need to.
2433 if (SCS1.First == ICK_Array_To_Pointer)
2434 FromType1 = Context.getArrayDecayedType(FromType1);
2435 if (SCS2.First == ICK_Array_To_Pointer)
2436 FromType2 = Context.getArrayDecayedType(FromType2);
2437
2438 // Canonicalize all of the types.
2439 FromType1 = Context.getCanonicalType(FromType1);
2440 ToType1 = Context.getCanonicalType(ToType1);
2441 FromType2 = Context.getCanonicalType(FromType2);
2442 ToType2 = Context.getCanonicalType(ToType2);
2443
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002444 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002445 //
2446 // If class B is derived directly or indirectly from class A and
2447 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002448 //
2449 // For Objective-C, we let A, B, and C also be Objective-C
2450 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002451
2452 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002453 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002454 SCS2.Second == ICK_Pointer_Conversion &&
2455 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2456 FromType1->isPointerType() && FromType2->isPointerType() &&
2457 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002458 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002459 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002460 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002461 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002462 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002463 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002464 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002465 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002466
John McCall8b07ec22010-05-15 11:32:37 +00002467 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2468 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2469 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2470 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002471
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002472 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002473 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2474 if (IsDerivedFrom(ToPointee1, ToPointee2))
2475 return ImplicitConversionSequence::Better;
2476 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2477 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002478
2479 if (ToIface1 && ToIface2) {
2480 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2481 return ImplicitConversionSequence::Better;
2482 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2483 return ImplicitConversionSequence::Worse;
2484 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002485 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002486
2487 // -- conversion of B* to A* is better than conversion of C* to A*,
2488 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2489 if (IsDerivedFrom(FromPointee2, FromPointee1))
2490 return ImplicitConversionSequence::Better;
2491 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2492 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002493
Douglas Gregor237f96c2008-11-26 23:31:11 +00002494 if (FromIface1 && FromIface2) {
2495 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2496 return ImplicitConversionSequence::Better;
2497 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2498 return ImplicitConversionSequence::Worse;
2499 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002500 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002501 }
2502
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002503 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002504 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2505 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2506 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2507 const MemberPointerType * FromMemPointer1 =
2508 FromType1->getAs<MemberPointerType>();
2509 const MemberPointerType * ToMemPointer1 =
2510 ToType1->getAs<MemberPointerType>();
2511 const MemberPointerType * FromMemPointer2 =
2512 FromType2->getAs<MemberPointerType>();
2513 const MemberPointerType * ToMemPointer2 =
2514 ToType2->getAs<MemberPointerType>();
2515 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2516 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2517 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2518 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2519 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2520 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2521 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2522 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002523 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002524 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2525 if (IsDerivedFrom(ToPointee1, ToPointee2))
2526 return ImplicitConversionSequence::Worse;
2527 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2528 return ImplicitConversionSequence::Better;
2529 }
2530 // conversion of B::* to C::* is better than conversion of A::* to C::*
2531 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2532 if (IsDerivedFrom(FromPointee1, FromPointee2))
2533 return ImplicitConversionSequence::Better;
2534 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2535 return ImplicitConversionSequence::Worse;
2536 }
2537 }
2538
Douglas Gregor5ab11652010-04-17 22:01:05 +00002539 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002540 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002541 // -- binding of an expression of type C to a reference of type
2542 // B& is better than binding an expression of type C to a
2543 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002544 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2545 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002546 if (IsDerivedFrom(ToType1, ToType2))
2547 return ImplicitConversionSequence::Better;
2548 else if (IsDerivedFrom(ToType2, ToType1))
2549 return ImplicitConversionSequence::Worse;
2550 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002551
Douglas Gregor2fe98832008-11-03 19:09:14 +00002552 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002553 // -- binding of an expression of type B to a reference of type
2554 // A& is better than binding an expression of type C to a
2555 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002556 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2557 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002558 if (IsDerivedFrom(FromType2, FromType1))
2559 return ImplicitConversionSequence::Better;
2560 else if (IsDerivedFrom(FromType1, FromType2))
2561 return ImplicitConversionSequence::Worse;
2562 }
2563 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002564
Douglas Gregor5c407d92008-10-23 00:40:37 +00002565 return ImplicitConversionSequence::Indistinguishable;
2566}
2567
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002568/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2569/// determine whether they are reference-related,
2570/// reference-compatible, reference-compatible with added
2571/// qualification, or incompatible, for use in C++ initialization by
2572/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2573/// type, and the first type (T1) is the pointee type of the reference
2574/// type being initialized.
2575Sema::ReferenceCompareResult
2576Sema::CompareReferenceRelationship(SourceLocation Loc,
2577 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002578 bool &DerivedToBase,
2579 bool &ObjCConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002580 assert(!OrigT1->isReferenceType() &&
2581 "T1 must be the pointee type of the reference type");
2582 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2583
2584 QualType T1 = Context.getCanonicalType(OrigT1);
2585 QualType T2 = Context.getCanonicalType(OrigT2);
2586 Qualifiers T1Quals, T2Quals;
2587 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2588 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2589
2590 // C++ [dcl.init.ref]p4:
2591 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2592 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2593 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002594 DerivedToBase = false;
2595 ObjCConversion = false;
2596 if (UnqualT1 == UnqualT2) {
2597 // Nothing to do.
2598 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002599 IsDerivedFrom(UnqualT2, UnqualT1))
2600 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002601 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2602 UnqualT2->isObjCObjectOrInterfaceType() &&
2603 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2604 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002605 else
2606 return Ref_Incompatible;
2607
2608 // At this point, we know that T1 and T2 are reference-related (at
2609 // least).
2610
2611 // If the type is an array type, promote the element qualifiers to the type
2612 // for comparison.
2613 if (isa<ArrayType>(T1) && T1Quals)
2614 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2615 if (isa<ArrayType>(T2) && T2Quals)
2616 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2617
2618 // C++ [dcl.init.ref]p4:
2619 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2620 // reference-related to T2 and cv1 is the same cv-qualification
2621 // as, or greater cv-qualification than, cv2. For purposes of
2622 // overload resolution, cases for which cv1 is greater
2623 // cv-qualification than cv2 are identified as
2624 // reference-compatible with added qualification (see 13.3.3.2).
2625 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2626 return Ref_Compatible;
2627 else if (T1.isMoreQualifiedThan(T2))
2628 return Ref_Compatible_With_Added_Qualification;
2629 else
2630 return Ref_Related;
2631}
2632
Douglas Gregor836a7e82010-08-11 02:15:33 +00002633/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00002634/// with DeclType. Return true if something definite is found.
2635static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00002636FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2637 QualType DeclType, SourceLocation DeclLoc,
2638 Expr *Init, QualType T2, bool AllowRvalues,
2639 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002640 assert(T2->isRecordType() && "Can only find conversions of record types.");
2641 CXXRecordDecl *T2RecordDecl
2642 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2643
Douglas Gregor836a7e82010-08-11 02:15:33 +00002644 QualType ToType
2645 = AllowRvalues? DeclType->getAs<ReferenceType>()->getPointeeType()
2646 : DeclType;
2647
Sebastian Redld92badf2010-06-30 18:13:39 +00002648 OverloadCandidateSet CandidateSet(DeclLoc);
2649 const UnresolvedSetImpl *Conversions
2650 = T2RecordDecl->getVisibleConversionFunctions();
2651 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2652 E = Conversions->end(); I != E; ++I) {
2653 NamedDecl *D = *I;
2654 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2655 if (isa<UsingShadowDecl>(D))
2656 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2657
2658 FunctionTemplateDecl *ConvTemplate
2659 = dyn_cast<FunctionTemplateDecl>(D);
2660 CXXConversionDecl *Conv;
2661 if (ConvTemplate)
2662 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2663 else
2664 Conv = cast<CXXConversionDecl>(D);
2665
Douglas Gregor836a7e82010-08-11 02:15:33 +00002666 // If this is an explicit conversion, and we're not allowed to consider
2667 // explicit conversions, skip it.
2668 if (!AllowExplicit && Conv->isExplicit())
2669 continue;
2670
2671 if (AllowRvalues) {
2672 bool DerivedToBase = false;
2673 bool ObjCConversion = false;
2674 if (!ConvTemplate &&
2675 S.CompareReferenceRelationship(DeclLoc,
2676 Conv->getConversionType().getNonReferenceType().getUnqualifiedType(),
2677 DeclType.getNonReferenceType().getUnqualifiedType(),
2678 DerivedToBase, ObjCConversion)
2679 == Sema::Ref_Incompatible)
2680 continue;
2681 } else {
2682 // If the conversion function doesn't return a reference type,
2683 // it can't be considered for this conversion. An rvalue reference
2684 // is only acceptable if its referencee is a function type.
2685
2686 const ReferenceType *RefType =
2687 Conv->getConversionType()->getAs<ReferenceType>();
2688 if (!RefType ||
2689 (!RefType->isLValueReferenceType() &&
2690 !RefType->getPointeeType()->isFunctionType()))
2691 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00002692 }
Douglas Gregor836a7e82010-08-11 02:15:33 +00002693
2694 if (ConvTemplate)
2695 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2696 Init, ToType, CandidateSet);
2697 else
2698 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2699 ToType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00002700 }
2701
2702 OverloadCandidateSet::iterator Best;
2703 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2704 case OR_Success:
2705 // C++ [over.ics.ref]p1:
2706 //
2707 // [...] If the parameter binds directly to the result of
2708 // applying a conversion function to the argument
2709 // expression, the implicit conversion sequence is a
2710 // user-defined conversion sequence (13.3.3.1.2), with the
2711 // second standard conversion sequence either an identity
2712 // conversion or, if the conversion function returns an
2713 // entity of a type that is a derived class of the parameter
2714 // type, a derived-to-base Conversion.
2715 if (!Best->FinalConversion.DirectBinding)
2716 return false;
2717
2718 ICS.setUserDefined();
2719 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2720 ICS.UserDefined.After = Best->FinalConversion;
2721 ICS.UserDefined.ConversionFunction = Best->Function;
2722 ICS.UserDefined.EllipsisConversion = false;
2723 assert(ICS.UserDefined.After.ReferenceBinding &&
2724 ICS.UserDefined.After.DirectBinding &&
2725 "Expected a direct reference binding!");
2726 return true;
2727
2728 case OR_Ambiguous:
2729 ICS.setAmbiguous();
2730 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2731 Cand != CandidateSet.end(); ++Cand)
2732 if (Cand->Viable)
2733 ICS.Ambiguous.addConversion(Cand->Function);
2734 return true;
2735
2736 case OR_No_Viable_Function:
2737 case OR_Deleted:
2738 // There was no suitable conversion, or we found a deleted
2739 // conversion; continue with other checks.
2740 return false;
2741 }
Eric Christopheraba9fb22010-06-30 18:36:32 +00002742
2743 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002744}
2745
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002746/// \brief Compute an implicit conversion sequence for reference
2747/// initialization.
2748static ImplicitConversionSequence
2749TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2750 SourceLocation DeclLoc,
2751 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002752 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002753 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2754
2755 // Most paths end in a failed conversion.
2756 ImplicitConversionSequence ICS;
2757 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2758
2759 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2760 QualType T2 = Init->getType();
2761
2762 // If the initializer is the address of an overloaded function, try
2763 // to resolve the overloaded function. If all goes well, T2 is the
2764 // type of the resulting function.
2765 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2766 DeclAccessPair Found;
2767 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2768 false, Found))
2769 T2 = Fn->getType();
2770 }
2771
2772 // Compute some basic properties of the types and the initializer.
2773 bool isRValRef = DeclType->isRValueReferenceType();
2774 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002775 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002776 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002777 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002778 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
2779 ObjCConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002780
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002781
Sebastian Redld92badf2010-06-30 18:13:39 +00002782 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00002783 // A reference to type "cv1 T1" is initialized by an expression
2784 // of type "cv2 T2" as follows:
2785
Sebastian Redld92badf2010-06-30 18:13:39 +00002786 // -- If reference is an lvalue reference and the initializer expression
2787 // The next bullet point (T1 is a function) is pretty much equivalent to this
2788 // one, so it's handled here.
2789 if (!isRValRef || T1->isFunctionType()) {
2790 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2791 // reference-compatible with "cv2 T2," or
2792 //
2793 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2794 if (InitCategory.isLValue() &&
2795 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002796 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00002797 // When a parameter of reference type binds directly (8.5.3)
2798 // to an argument expression, the implicit conversion sequence
2799 // is the identity conversion, unless the argument expression
2800 // has a type that is a derived class of the parameter type,
2801 // in which case the implicit conversion sequence is a
2802 // derived-to-base Conversion (13.3.3.1).
2803 ICS.setStandard();
2804 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002805 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2806 : ObjCConversion? ICK_Compatible_Conversion
2807 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00002808 ICS.Standard.Third = ICK_Identity;
2809 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2810 ICS.Standard.setToType(0, T2);
2811 ICS.Standard.setToType(1, T1);
2812 ICS.Standard.setToType(2, T1);
2813 ICS.Standard.ReferenceBinding = true;
2814 ICS.Standard.DirectBinding = true;
2815 ICS.Standard.RRefBinding = isRValRef;
2816 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002817
Sebastian Redld92badf2010-06-30 18:13:39 +00002818 // Nothing more to do: the inaccessibility/ambiguity check for
2819 // derived-to-base conversions is suppressed when we're
2820 // computing the implicit conversion sequence (C++
2821 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002822 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00002823 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002824
Sebastian Redld92badf2010-06-30 18:13:39 +00002825 // -- has a class type (i.e., T2 is a class type), where T1 is
2826 // not reference-related to T2, and can be implicitly
2827 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2828 // is reference-compatible with "cv3 T3" 92) (this
2829 // conversion is selected by enumerating the applicable
2830 // conversion functions (13.3.1.6) and choosing the best
2831 // one through overload resolution (13.3)),
2832 if (!SuppressUserConversions && T2->isRecordType() &&
2833 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2834 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00002835 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2836 Init, T2, /*AllowRvalues=*/false,
2837 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00002838 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002839 }
2840 }
2841
Sebastian Redld92badf2010-06-30 18:13:39 +00002842 // -- Otherwise, the reference shall be an lvalue reference to a
2843 // non-volatile const type (i.e., cv1 shall be const), or the reference
2844 // shall be an rvalue reference and the initializer expression shall be
2845 // an rvalue or have a function type.
Douglas Gregor870f3742010-04-18 09:22:00 +00002846 //
2847 // We actually handle one oddity of C++ [over.ics.ref] at this
2848 // point, which is that, due to p2 (which short-circuits reference
2849 // binding by only attempting a simple conversion for non-direct
2850 // bindings) and p3's strange wording, we allow a const volatile
2851 // reference to bind to an rvalue. Hence the check for the presence
2852 // of "const" rather than checking for "const" being the only
2853 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00002854 // This is also the point where rvalue references and lvalue inits no longer
2855 // go together.
2856 if ((!isRValRef && !T1.isConstQualified()) ||
2857 (isRValRef && InitCategory.isLValue()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002858 return ICS;
2859
Sebastian Redld92badf2010-06-30 18:13:39 +00002860 // -- If T1 is a function type, then
2861 // -- if T2 is the same type as T1, the reference is bound to the
2862 // initializer expression lvalue;
2863 // -- if T2 is a class type and the initializer expression can be
2864 // implicitly converted to an lvalue of type T1 [...], the
2865 // reference is bound to the function lvalue that is the result
2866 // of the conversion;
2867 // This is the same as for the lvalue case above, so it was handled there.
2868 // -- otherwise, the program is ill-formed.
2869 // This is the one difference to the lvalue case.
2870 if (T1->isFunctionType())
2871 return ICS;
2872
2873 // -- Otherwise, if T2 is a class type and
Douglas Gregorf93df192010-04-18 08:46:23 +00002874 // -- the initializer expression is an rvalue and "cv1 T1"
2875 // is reference-compatible with "cv2 T2," or
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002876 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002877 // -- T1 is not reference-related to T2 and the initializer
2878 // expression can be implicitly converted to an rvalue
2879 // of type "cv3 T3" (this conversion is selected by
2880 // enumerating the applicable conversion functions
2881 // (13.3.1.6) and choosing the best one through overload
2882 // resolution (13.3)),
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002883 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002884 // then the reference is bound to the initializer
2885 // expression rvalue in the first case and to the object
2886 // that is the result of the conversion in the second case
2887 // (or, in either case, to the appropriate base class
2888 // subobject of the object).
Douglas Gregor836a7e82010-08-11 02:15:33 +00002889 if (T2->isRecordType()) {
2890 // First case: "cv1 T1" is reference-compatible with "cv2 T2". This is a
2891 // direct binding in C++0x but not in C++03.
2892 if (InitCategory.isRValue() &&
2893 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2894 ICS.setStandard();
2895 ICS.Standard.First = ICK_Identity;
2896 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2897 : ObjCConversion? ICK_Compatible_Conversion
2898 : ICK_Identity;
2899 ICS.Standard.Third = ICK_Identity;
2900 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2901 ICS.Standard.setToType(0, T2);
2902 ICS.Standard.setToType(1, T1);
2903 ICS.Standard.setToType(2, T1);
2904 ICS.Standard.ReferenceBinding = true;
2905 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
2906 ICS.Standard.RRefBinding = isRValRef;
2907 ICS.Standard.CopyConstructor = 0;
2908 return ICS;
2909 }
2910
2911 // Second case: not reference-related.
2912 if (RefRelationship == Sema::Ref_Incompatible &&
2913 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2914 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2915 Init, T2, /*AllowRvalues=*/true,
2916 AllowExplicit))
2917 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002918 }
Douglas Gregor836a7e82010-08-11 02:15:33 +00002919
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002920 // -- Otherwise, a temporary of type "cv1 T1" is created and
2921 // initialized from the initializer expression using the
2922 // rules for a non-reference copy initialization (8.5). The
2923 // reference is then bound to the temporary. If T1 is
2924 // reference-related to T2, cv1 must be the same
2925 // cv-qualification as, or greater cv-qualification than,
2926 // cv2; otherwise, the program is ill-formed.
2927 if (RefRelationship == Sema::Ref_Related) {
2928 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2929 // we would be reference-compatible or reference-compatible with
2930 // added qualification. But that wasn't the case, so the reference
2931 // initialization fails.
2932 return ICS;
2933 }
2934
2935 // If at least one of the types is a class type, the types are not
2936 // related, and we aren't allowed any user conversions, the
2937 // reference binding fails. This case is important for breaking
2938 // recursion, since TryImplicitConversion below will attempt to
2939 // create a temporary through the use of a copy constructor.
2940 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2941 (T1->isRecordType() || T2->isRecordType()))
2942 return ICS;
2943
2944 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002945 // When a parameter of reference type is not bound directly to
2946 // an argument expression, the conversion sequence is the one
2947 // required to convert the argument expression to the
2948 // underlying type of the reference according to
2949 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2950 // to copy-initializing a temporary of the underlying type with
2951 // the argument expression. Any difference in top-level
2952 // cv-qualification is subsumed by the initialization itself
2953 // and does not constitute a conversion.
2954 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2955 /*AllowExplicit=*/false,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002956 /*InOverloadResolution=*/false);
2957
2958 // Of course, that's still a reference binding.
2959 if (ICS.isStandard()) {
2960 ICS.Standard.ReferenceBinding = true;
2961 ICS.Standard.RRefBinding = isRValRef;
2962 } else if (ICS.isUserDefined()) {
2963 ICS.UserDefined.After.ReferenceBinding = true;
2964 ICS.UserDefined.After.RRefBinding = isRValRef;
2965 }
2966 return ICS;
2967}
2968
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002969/// TryCopyInitialization - Try to copy-initialize a value of type
2970/// ToType from the expression From. Return the implicit conversion
2971/// sequence required to pass this argument, which may be a bad
2972/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002973/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00002974/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002975static ImplicitConversionSequence
2976TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00002977 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002978 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002979 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002980 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002981 /*FIXME:*/From->getLocStart(),
2982 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002983 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002984
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002985 return S.TryImplicitConversion(From, ToType,
2986 SuppressUserConversions,
2987 /*AllowExplicit=*/false,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002988 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002989}
2990
Douglas Gregor436424c2008-11-18 23:14:02 +00002991/// TryObjectArgumentInitialization - Try to initialize the object
2992/// parameter of the given member function (@c Method) from the
2993/// expression @p From.
2994ImplicitConversionSequence
John McCall47000992010-01-14 03:28:57 +00002995Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall6e9f8f62009-12-03 04:06:58 +00002996 CXXMethodDecl *Method,
2997 CXXRecordDecl *ActingContext) {
2998 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002999 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3000 // const volatile object.
3001 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3002 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
3003 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003004
3005 // Set up the conversion sequence as a "bad" conversion, to allow us
3006 // to exit early.
3007 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003008
3009 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003010 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003011 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003012 FromType = PT->getPointeeType();
3013
3014 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003015
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003016 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00003017 // where X is the class of which the function is a member
3018 // (C++ [over.match.funcs]p4). However, when finding an implicit
3019 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00003020 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003021 // (C++ [over.match.funcs]p5). We perform a simplified version of
3022 // reference binding here, that allows class rvalues to bind to
3023 // non-constant references.
3024
3025 // First check the qualifiers. We don't care about lvalue-vs-rvalue
3026 // with the implicit object parameter (C++ [over.match.funcs]p5).
3027 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003028 if (ImplicitParamType.getCVRQualifiers()
3029 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003030 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003031 ICS.setBad(BadConversionSequence::bad_qualifiers,
3032 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003033 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003034 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003035
3036 // Check that we have either the same type or a derived type. It
3037 // affects the conversion rank.
3038 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003039 ImplicitConversionKind SecondKind;
3040 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3041 SecondKind = ICK_Identity;
3042 } else if (IsDerivedFrom(FromType, ClassType))
3043 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003044 else {
John McCall65eb8792010-02-25 01:37:24 +00003045 ICS.setBad(BadConversionSequence::unrelated_class,
3046 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003047 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003048 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003049
3050 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003051 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003052 ICS.Standard.setAsIdentityConversion();
3053 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003054 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003055 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003056 ICS.Standard.ReferenceBinding = true;
3057 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00003058 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003059 return ICS;
3060}
3061
3062/// PerformObjectArgumentInitialization - Perform initialization of
3063/// the implicit object parameter for the given Method with the given
3064/// expression.
3065bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003066Sema::PerformObjectArgumentInitialization(Expr *&From,
3067 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003068 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003069 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003070 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003071 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003072 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003073
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003074 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003075 FromRecordType = PT->getPointeeType();
3076 DestType = Method->getThisType(Context);
3077 } else {
3078 FromRecordType = From->getType();
3079 DestType = ImplicitParamRecordType;
3080 }
3081
John McCall6e9f8f62009-12-03 04:06:58 +00003082 // Note that we always use the true parent context when performing
3083 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003084 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00003085 = TryObjectArgumentInitialization(From->getType(), Method,
3086 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00003087 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00003088 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003089 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003090 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003091
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003092 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00003093 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00003094
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003095 if (!Context.hasSameType(From->getType(), DestType))
Anders Carlsson0c509ee2010-04-24 16:57:13 +00003096 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003097 From->getType()->isPointerType() ?
3098 ImplicitCastExpr::RValue : ImplicitCastExpr::LValue);
Douglas Gregor436424c2008-11-18 23:14:02 +00003099 return false;
3100}
3101
Douglas Gregor5fb53972009-01-14 15:45:31 +00003102/// TryContextuallyConvertToBool - Attempt to contextually convert the
3103/// expression From to bool (C++0x [conv]p3).
3104ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003105 // FIXME: This is pretty broken.
Mike Stump11289f42009-09-09 15:08:12 +00003106 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003107 // FIXME: Are these flags correct?
3108 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003109 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00003110 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003111}
3112
3113/// PerformContextuallyConvertToBool - Perform a contextual conversion
3114/// of the expression From to bool (C++0x [conv]p3).
3115bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
3116 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00003117 if (!ICS.isBad())
3118 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003119
Fariborz Jahanian76197412009-11-18 18:26:29 +00003120 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003121 return Diag(From->getSourceRange().getBegin(),
3122 diag::err_typecheck_bool_condition)
3123 << From->getType() << From->getSourceRange();
3124 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003125}
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003126
3127/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3128/// expression From to 'id'.
3129ImplicitConversionSequence Sema::TryContextuallyConvertToObjCId(Expr *From) {
John McCall8b07ec22010-05-15 11:32:37 +00003130 QualType Ty = Context.getObjCIdType();
3131 return TryImplicitConversion(From, Ty,
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003132 // FIXME: Are these flags correct?
3133 /*SuppressUserConversions=*/false,
3134 /*AllowExplicit=*/true,
3135 /*InOverloadResolution=*/false);
3136}
3137
3138/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3139/// of the expression From to 'id'.
3140bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCall8b07ec22010-05-15 11:32:37 +00003141 QualType Ty = Context.getObjCIdType();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003142 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(From);
3143 if (!ICS.isBad())
3144 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3145 return true;
3146}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003147
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003148/// \brief Attempt to convert the given expression to an integral or
3149/// enumeration type.
3150///
3151/// This routine will attempt to convert an expression of class type to an
3152/// integral or enumeration type, if that class type only has a single
3153/// conversion to an integral or enumeration type.
3154///
Douglas Gregor4799d032010-06-30 00:20:43 +00003155/// \param Loc The source location of the construct that requires the
3156/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003157///
Douglas Gregor4799d032010-06-30 00:20:43 +00003158/// \param FromE The expression we're converting from.
3159///
3160/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3161/// have integral or enumeration type.
3162///
3163/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3164/// incomplete class type.
3165///
3166/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3167/// explicit conversion function (because no implicit conversion functions
3168/// were available). This is a recovery mode.
3169///
3170/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3171/// showing which conversion was picked.
3172///
3173/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3174/// conversion function that could convert to integral or enumeration type.
3175///
3176/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3177/// usable conversion function.
3178///
3179/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3180/// function, which may be an extension in this case.
3181///
3182/// \returns The expression, converted to an integral or enumeration type if
3183/// successful.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003184Sema::OwningExprResult
3185Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, ExprArg FromE,
3186 const PartialDiagnostic &NotIntDiag,
3187 const PartialDiagnostic &IncompleteDiag,
3188 const PartialDiagnostic &ExplicitConvDiag,
3189 const PartialDiagnostic &ExplicitConvNote,
3190 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003191 const PartialDiagnostic &AmbigNote,
3192 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003193 Expr *From = static_cast<Expr *>(FromE.get());
3194
3195 // We can't perform any more checking for type-dependent expressions.
3196 if (From->isTypeDependent())
3197 return move(FromE);
3198
3199 // If the expression already has integral or enumeration type, we're golden.
3200 QualType T = From->getType();
3201 if (T->isIntegralOrEnumerationType())
3202 return move(FromE);
3203
3204 // FIXME: Check for missing '()' if T is a function type?
3205
3206 // If we don't have a class type in C++, there's no way we can get an
3207 // expression of integral or enumeration type.
3208 const RecordType *RecordTy = T->getAs<RecordType>();
3209 if (!RecordTy || !getLangOptions().CPlusPlus) {
3210 Diag(Loc, NotIntDiag)
3211 << T << From->getSourceRange();
Douglas Gregor5823da32010-06-29 23:25:20 +00003212 return move(FromE);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003213 }
3214
3215 // We must have a complete class type.
3216 if (RequireCompleteType(Loc, T, IncompleteDiag))
Douglas Gregor4799d032010-06-30 00:20:43 +00003217 return move(FromE);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003218
3219 // Look for a conversion to an integral or enumeration type.
3220 UnresolvedSet<4> ViableConversions;
3221 UnresolvedSet<4> ExplicitConversions;
3222 const UnresolvedSetImpl *Conversions
3223 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3224
3225 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3226 E = Conversions->end();
3227 I != E;
3228 ++I) {
3229 if (CXXConversionDecl *Conversion
3230 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3231 if (Conversion->getConversionType().getNonReferenceType()
3232 ->isIntegralOrEnumerationType()) {
3233 if (Conversion->isExplicit())
3234 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3235 else
3236 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3237 }
3238 }
3239
3240 switch (ViableConversions.size()) {
3241 case 0:
3242 if (ExplicitConversions.size() == 1) {
3243 DeclAccessPair Found = ExplicitConversions[0];
3244 CXXConversionDecl *Conversion
3245 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3246
3247 // The user probably meant to invoke the given explicit
3248 // conversion; use it.
3249 QualType ConvTy
3250 = Conversion->getConversionType().getNonReferenceType();
3251 std::string TypeStr;
3252 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3253
3254 Diag(Loc, ExplicitConvDiag)
3255 << T << ConvTy
3256 << FixItHint::CreateInsertion(From->getLocStart(),
3257 "static_cast<" + TypeStr + ">(")
3258 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3259 ")");
3260 Diag(Conversion->getLocation(), ExplicitConvNote)
3261 << ConvTy->isEnumeralType() << ConvTy;
3262
3263 // If we aren't in a SFINAE context, build a call to the
3264 // explicit conversion function.
3265 if (isSFINAEContext())
3266 return ExprError();
3267
3268 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
3269 From = BuildCXXMemberCallExpr(FromE.takeAs<Expr>(), Found, Conversion);
3270 FromE = Owned(From);
3271 }
3272
3273 // We'll complain below about a non-integral condition type.
3274 break;
3275
3276 case 1: {
3277 // Apply this conversion.
3278 DeclAccessPair Found = ViableConversions[0];
3279 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor4799d032010-06-30 00:20:43 +00003280
3281 CXXConversionDecl *Conversion
3282 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3283 QualType ConvTy
3284 = Conversion->getConversionType().getNonReferenceType();
3285 if (ConvDiag.getDiagID()) {
3286 if (isSFINAEContext())
3287 return ExprError();
3288
3289 Diag(Loc, ConvDiag)
3290 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3291 }
3292
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003293 From = BuildCXXMemberCallExpr(FromE.takeAs<Expr>(), Found,
3294 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
3295 FromE = Owned(From);
3296 break;
3297 }
3298
3299 default:
3300 Diag(Loc, AmbigDiag)
3301 << T << From->getSourceRange();
3302 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3303 CXXConversionDecl *Conv
3304 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3305 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3306 Diag(Conv->getLocation(), AmbigNote)
3307 << ConvTy->isEnumeralType() << ConvTy;
3308 }
Douglas Gregor5823da32010-06-29 23:25:20 +00003309 return move(FromE);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003310 }
3311
Douglas Gregor5823da32010-06-29 23:25:20 +00003312 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003313 Diag(Loc, NotIntDiag)
3314 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003315
3316 return move(FromE);
3317}
3318
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003319/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003320/// candidate functions, using the given function call arguments. If
3321/// @p SuppressUserConversions, then don't allow user-defined
3322/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003323///
3324/// \para PartialOverloading true if we are performing "partial" overloading
3325/// based on an incomplete set of function arguments. This feature is used by
3326/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003327void
3328Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003329 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003330 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003331 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003332 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003333 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003334 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003335 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003336 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003337 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003338 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003339
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003340 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003341 if (!isa<CXXConstructorDecl>(Method)) {
3342 // If we get here, it's because we're calling a member function
3343 // that is named without a member access expression (e.g.,
3344 // "this->f") that was either written explicitly or created
3345 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003346 // function, e.g., X::f(). We use an empty type for the implied
3347 // object argument (C++ [over.call.func]p3), and the acting context
3348 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003349 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00003350 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003351 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003352 return;
3353 }
3354 // We treat a constructor like a non-member function, since its object
3355 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003356 }
3357
Douglas Gregorff7028a2009-11-13 23:59:09 +00003358 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003359 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003360
Douglas Gregor27381f32009-11-23 12:27:39 +00003361 // Overload resolution is always an unevaluated context.
3362 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3363
Douglas Gregorffe14e32009-11-14 01:20:54 +00003364 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3365 // C++ [class.copy]p3:
3366 // A member function template is never instantiated to perform the copy
3367 // of a class object to an object of its class type.
3368 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3369 if (NumArgs == 1 &&
3370 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003371 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3372 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003373 return;
3374 }
3375
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003376 // Add this candidate
3377 CandidateSet.push_back(OverloadCandidate());
3378 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003379 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003380 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003381 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003382 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003383 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003384
3385 unsigned NumArgsInProto = Proto->getNumArgs();
3386
3387 // (C++ 13.3.2p2): A candidate function having fewer than m
3388 // parameters is viable only if it has an ellipsis in its parameter
3389 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00003390 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3391 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003392 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003393 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003394 return;
3395 }
3396
3397 // (C++ 13.3.2p2): A candidate function having more than m parameters
3398 // is viable only if the (m+1)st parameter has a default argument
3399 // (8.3.6). For the purposes of overload resolution, the
3400 // parameter list is truncated on the right, so that there are
3401 // exactly m parameters.
3402 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003403 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003404 // Not enough arguments.
3405 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003406 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003407 return;
3408 }
3409
3410 // Determine the implicit conversion sequences for each of the
3411 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003412 Candidate.Conversions.resize(NumArgs);
3413 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3414 if (ArgIdx < NumArgsInProto) {
3415 // (C++ 13.3.2p3): for F to be a viable function, there shall
3416 // exist for each argument an implicit conversion sequence
3417 // (13.3.3.1) that converts that argument to the corresponding
3418 // parameter of F.
3419 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003420 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003421 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00003422 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003423 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003424 if (Candidate.Conversions[ArgIdx].isBad()) {
3425 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003426 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003427 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003428 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003429 } else {
3430 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3431 // argument for which there is no corresponding parameter is
3432 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003433 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003434 }
3435 }
3436}
3437
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003438/// \brief Add all of the function declarations in the given function set to
3439/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003440void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003441 Expr **Args, unsigned NumArgs,
3442 OverloadCandidateSet& CandidateSet,
3443 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003444 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003445 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3446 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003447 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003448 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003449 cast<CXXMethodDecl>(FD)->getParent(),
3450 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003451 CandidateSet, SuppressUserConversions);
3452 else
John McCalla0296f72010-03-19 07:35:19 +00003453 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003454 SuppressUserConversions);
3455 } else {
John McCalla0296f72010-03-19 07:35:19 +00003456 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003457 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3458 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003459 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003460 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003461 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003462 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003463 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003464 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003465 else
John McCalla0296f72010-03-19 07:35:19 +00003466 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003467 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003468 Args, NumArgs, CandidateSet,
3469 SuppressUserConversions);
3470 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003471 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003472}
3473
John McCallf0f1cf02009-11-17 07:50:12 +00003474/// AddMethodCandidate - Adds a named decl (which is some kind of
3475/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003476void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003477 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00003478 Expr **Args, unsigned NumArgs,
3479 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003480 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003481 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003482 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003483
3484 if (isa<UsingShadowDecl>(Decl))
3485 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3486
3487 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3488 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3489 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003490 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3491 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003492 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003493 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003494 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003495 } else {
John McCalla0296f72010-03-19 07:35:19 +00003496 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00003497 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003498 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003499 }
3500}
3501
Douglas Gregor436424c2008-11-18 23:14:02 +00003502/// AddMethodCandidate - Adds the given C++ member function to the set
3503/// of candidate functions, using the given function call arguments
3504/// and the object argument (@c Object). For example, in a call
3505/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3506/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3507/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003508/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003509void
John McCalla0296f72010-03-19 07:35:19 +00003510Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003511 CXXRecordDecl *ActingContext, QualType ObjectType,
3512 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003513 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003514 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003515 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003516 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003517 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003518 assert(!isa<CXXConstructorDecl>(Method) &&
3519 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003520
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003521 if (!CandidateSet.isNewCandidate(Method))
3522 return;
3523
Douglas Gregor27381f32009-11-23 12:27:39 +00003524 // Overload resolution is always an unevaluated context.
3525 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3526
Douglas Gregor436424c2008-11-18 23:14:02 +00003527 // Add this candidate
3528 CandidateSet.push_back(OverloadCandidate());
3529 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003530 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003531 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003532 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003533 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003534
3535 unsigned NumArgsInProto = Proto->getNumArgs();
3536
3537 // (C++ 13.3.2p2): A candidate function having fewer than m
3538 // parameters is viable only if it has an ellipsis in its parameter
3539 // list (8.3.5).
3540 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3541 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003542 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003543 return;
3544 }
3545
3546 // (C++ 13.3.2p2): A candidate function having more than m parameters
3547 // is viable only if the (m+1)st parameter has a default argument
3548 // (8.3.6). For the purposes of overload resolution, the
3549 // parameter list is truncated on the right, so that there are
3550 // exactly m parameters.
3551 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3552 if (NumArgs < MinRequiredArgs) {
3553 // Not enough arguments.
3554 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003555 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003556 return;
3557 }
3558
3559 Candidate.Viable = true;
3560 Candidate.Conversions.resize(NumArgs + 1);
3561
John McCall6e9f8f62009-12-03 04:06:58 +00003562 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003563 // The implicit object argument is ignored.
3564 Candidate.IgnoreObjectArgument = true;
3565 else {
3566 // Determine the implicit conversion sequence for the object
3567 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00003568 Candidate.Conversions[0]
3569 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003570 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003571 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003572 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003573 return;
3574 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003575 }
3576
3577 // Determine the implicit conversion sequences for each of the
3578 // arguments.
3579 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3580 if (ArgIdx < NumArgsInProto) {
3581 // (C++ 13.3.2p3): for F to be a viable function, there shall
3582 // exist for each argument an implicit conversion sequence
3583 // (13.3.3.1) that converts that argument to the corresponding
3584 // parameter of F.
3585 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003586 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003587 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003588 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003589 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003590 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003591 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003592 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003593 break;
3594 }
3595 } else {
3596 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3597 // argument for which there is no corresponding parameter is
3598 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003599 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003600 }
3601 }
3602}
Douglas Gregor3626a5c2010-05-08 17:41:32 +00003603
Douglas Gregor97628d62009-08-21 00:16:32 +00003604/// \brief Add a C++ member function template as a candidate to the candidate
3605/// set, using template argument deduction to produce an appropriate member
3606/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003607void
Douglas Gregor97628d62009-08-21 00:16:32 +00003608Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003609 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003610 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003611 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003612 QualType ObjectType,
3613 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003614 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003615 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003616 if (!CandidateSet.isNewCandidate(MethodTmpl))
3617 return;
3618
Douglas Gregor97628d62009-08-21 00:16:32 +00003619 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003620 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003621 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003622 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003623 // candidate functions in the usual way.113) A given name can refer to one
3624 // or more function templates and also to a set of overloaded non-template
3625 // functions. In such a case, the candidate functions generated from each
3626 // function template are combined with the set of non-template candidate
3627 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003628 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003629 FunctionDecl *Specialization = 0;
3630 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003631 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003632 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003633 CandidateSet.push_back(OverloadCandidate());
3634 OverloadCandidate &Candidate = CandidateSet.back();
3635 Candidate.FoundDecl = FoundDecl;
3636 Candidate.Function = MethodTmpl->getTemplatedDecl();
3637 Candidate.Viable = false;
3638 Candidate.FailureKind = ovl_fail_bad_deduction;
3639 Candidate.IsSurrogate = false;
3640 Candidate.IgnoreObjectArgument = false;
3641 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3642 Info);
3643 return;
3644 }
Mike Stump11289f42009-09-09 15:08:12 +00003645
Douglas Gregor97628d62009-08-21 00:16:32 +00003646 // Add the function template specialization produced by template argument
3647 // deduction as a candidate.
3648 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003649 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003650 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003651 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003652 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003653 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003654}
3655
Douglas Gregor05155d82009-08-21 23:19:43 +00003656/// \brief Add a C++ function template specialization as a candidate
3657/// in the candidate set, using template argument deduction to produce
3658/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003659void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003660Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003661 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003662 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003663 Expr **Args, unsigned NumArgs,
3664 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003665 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003666 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3667 return;
3668
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003669 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003670 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003671 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003672 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003673 // candidate functions in the usual way.113) A given name can refer to one
3674 // or more function templates and also to a set of overloaded non-template
3675 // functions. In such a case, the candidate functions generated from each
3676 // function template are combined with the set of non-template candidate
3677 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003678 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003679 FunctionDecl *Specialization = 0;
3680 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003681 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003682 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003683 CandidateSet.push_back(OverloadCandidate());
3684 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003685 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003686 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3687 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003688 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003689 Candidate.IsSurrogate = false;
3690 Candidate.IgnoreObjectArgument = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003691 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3692 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003693 return;
3694 }
Mike Stump11289f42009-09-09 15:08:12 +00003695
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003696 // Add the function template specialization produced by template argument
3697 // deduction as a candidate.
3698 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003699 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003700 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003701}
Mike Stump11289f42009-09-09 15:08:12 +00003702
Douglas Gregora1f013e2008-11-07 22:36:19 +00003703/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003704/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003705/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003706/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003707/// (which may or may not be the same type as the type that the
3708/// conversion function produces).
3709void
3710Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003711 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003712 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003713 Expr *From, QualType ToType,
3714 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003715 assert(!Conversion->getDescribedFunctionTemplate() &&
3716 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003717 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003718 if (!CandidateSet.isNewCandidate(Conversion))
3719 return;
3720
Douglas Gregor27381f32009-11-23 12:27:39 +00003721 // Overload resolution is always an unevaluated context.
3722 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3723
Douglas Gregora1f013e2008-11-07 22:36:19 +00003724 // Add this candidate
3725 CandidateSet.push_back(OverloadCandidate());
3726 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003727 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003728 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003729 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003730 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003731 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003732 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003733 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003734
Douglas Gregor436424c2008-11-18 23:14:02 +00003735 // Determine the implicit conversion sequence for the implicit
3736 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00003737 Candidate.Viable = true;
3738 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00003739 Candidate.Conversions[0]
3740 = TryObjectArgumentInitialization(From->getType(), Conversion,
3741 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00003742 // Conversion functions to a different type in the base class is visible in
3743 // the derived class. So, a derived to base conversion should not participate
3744 // in overload resolution.
3745 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
3746 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00003747 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003748 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003749 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003750 return;
3751 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003752
3753 // We won't go through a user-define type conversion function to convert a
3754 // derived to base as such conversions are given Conversion Rank. They only
3755 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3756 QualType FromCanon
3757 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3758 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3759 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3760 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003761 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003762 return;
3763 }
3764
Douglas Gregora1f013e2008-11-07 22:36:19 +00003765 // To determine what the conversion from the result of calling the
3766 // conversion function to the type we're eventually trying to
3767 // convert to (ToType), we need to synthesize a call to the
3768 // conversion function and attempt copy initialization from it. This
3769 // makes sure that we get the right semantics with respect to
3770 // lvalues/rvalues and the type. Fortunately, we can allocate this
3771 // call on the stack and we don't need its arguments to be
3772 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003773 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003774 From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00003775 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
3776 Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00003777 CastExpr::CK_FunctionToPointerDecay,
John McCallcf142162010-08-07 06:22:56 +00003778 &ConversionRef, ImplicitCastExpr::RValue);
Mike Stump11289f42009-09-09 15:08:12 +00003779
3780 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003781 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3782 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00003783 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003784 Conversion->getConversionType().getNonLValueExprType(Context),
Douglas Gregore8f080122009-11-17 21:16:22 +00003785 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003786 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003787 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003788 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003789 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003790
John McCall0d1da222010-01-12 00:44:57 +00003791 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003792 case ImplicitConversionSequence::StandardConversion:
3793 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003794
3795 // C++ [over.ics.user]p3:
3796 // If the user-defined conversion is specified by a specialization of a
3797 // conversion function template, the second standard conversion sequence
3798 // shall have exact match rank.
3799 if (Conversion->getPrimaryTemplate() &&
3800 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3801 Candidate.Viable = false;
3802 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3803 }
3804
Douglas Gregora1f013e2008-11-07 22:36:19 +00003805 break;
3806
3807 case ImplicitConversionSequence::BadConversion:
3808 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003809 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003810 break;
3811
3812 default:
Mike Stump11289f42009-09-09 15:08:12 +00003813 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003814 "Can only end up with a standard conversion sequence or failure");
3815 }
3816}
3817
Douglas Gregor05155d82009-08-21 23:19:43 +00003818/// \brief Adds a conversion function template specialization
3819/// candidate to the overload set, using template argument deduction
3820/// to deduce the template arguments of the conversion function
3821/// template from the type that we are converting to (C++
3822/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003823void
Douglas Gregor05155d82009-08-21 23:19:43 +00003824Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003825 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003826 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003827 Expr *From, QualType ToType,
3828 OverloadCandidateSet &CandidateSet) {
3829 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3830 "Only conversion function templates permitted here");
3831
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003832 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3833 return;
3834
John McCallbc077cf2010-02-08 23:07:23 +00003835 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003836 CXXConversionDecl *Specialization = 0;
3837 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003838 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003839 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003840 CandidateSet.push_back(OverloadCandidate());
3841 OverloadCandidate &Candidate = CandidateSet.back();
3842 Candidate.FoundDecl = FoundDecl;
3843 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3844 Candidate.Viable = false;
3845 Candidate.FailureKind = ovl_fail_bad_deduction;
3846 Candidate.IsSurrogate = false;
3847 Candidate.IgnoreObjectArgument = false;
3848 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3849 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00003850 return;
3851 }
Mike Stump11289f42009-09-09 15:08:12 +00003852
Douglas Gregor05155d82009-08-21 23:19:43 +00003853 // Add the conversion function template specialization produced by
3854 // template argument deduction as a candidate.
3855 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003856 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00003857 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003858}
3859
Douglas Gregorab7897a2008-11-19 22:57:39 +00003860/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3861/// converts the given @c Object to a function pointer via the
3862/// conversion function @c Conversion, and then attempts to call it
3863/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3864/// the type of function that we'll eventually be calling.
3865void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003866 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003867 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003868 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00003869 QualType ObjectType,
3870 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00003871 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003872 if (!CandidateSet.isNewCandidate(Conversion))
3873 return;
3874
Douglas Gregor27381f32009-11-23 12:27:39 +00003875 // Overload resolution is always an unevaluated context.
3876 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3877
Douglas Gregorab7897a2008-11-19 22:57:39 +00003878 CandidateSet.push_back(OverloadCandidate());
3879 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003880 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003881 Candidate.Function = 0;
3882 Candidate.Surrogate = Conversion;
3883 Candidate.Viable = true;
3884 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003885 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003886 Candidate.Conversions.resize(NumArgs + 1);
3887
3888 // Determine the implicit conversion sequence for the implicit
3889 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003890 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00003891 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003892 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003893 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003894 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00003895 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003896 return;
3897 }
3898
3899 // The first conversion is actually a user-defined conversion whose
3900 // first conversion is ObjectInit's standard conversion (which is
3901 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00003902 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003903 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003904 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003905 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00003906 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00003907 = Candidate.Conversions[0].UserDefined.Before;
3908 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3909
Mike Stump11289f42009-09-09 15:08:12 +00003910 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00003911 unsigned NumArgsInProto = Proto->getNumArgs();
3912
3913 // (C++ 13.3.2p2): A candidate function having fewer than m
3914 // parameters is viable only if it has an ellipsis in its parameter
3915 // list (8.3.5).
3916 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3917 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003918 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003919 return;
3920 }
3921
3922 // Function types don't have any default arguments, so just check if
3923 // we have enough arguments.
3924 if (NumArgs < NumArgsInProto) {
3925 // Not enough arguments.
3926 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003927 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003928 return;
3929 }
3930
3931 // Determine the implicit conversion sequences for each of the
3932 // arguments.
3933 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3934 if (ArgIdx < NumArgsInProto) {
3935 // (C++ 13.3.2p3): for F to be a viable function, there shall
3936 // exist for each argument an implicit conversion sequence
3937 // (13.3.3.1) that converts that argument to the corresponding
3938 // parameter of F.
3939 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003940 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003941 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003942 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00003943 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00003944 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003945 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003946 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003947 break;
3948 }
3949 } else {
3950 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3951 // argument for which there is no corresponding parameter is
3952 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003953 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003954 }
3955 }
3956}
3957
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003958/// \brief Add overload candidates for overloaded operators that are
3959/// member functions.
3960///
3961/// Add the overloaded operator candidates that are member functions
3962/// for the operator Op that was used in an operator expression such
3963/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3964/// CandidateSet will store the added overload candidates. (C++
3965/// [over.match.oper]).
3966void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3967 SourceLocation OpLoc,
3968 Expr **Args, unsigned NumArgs,
3969 OverloadCandidateSet& CandidateSet,
3970 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003971 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3972
3973 // C++ [over.match.oper]p3:
3974 // For a unary operator @ with an operand of a type whose
3975 // cv-unqualified version is T1, and for a binary operator @ with
3976 // a left operand of a type whose cv-unqualified version is T1 and
3977 // a right operand of a type whose cv-unqualified version is T2,
3978 // three sets of candidate functions, designated member
3979 // candidates, non-member candidates and built-in candidates, are
3980 // constructed as follows:
3981 QualType T1 = Args[0]->getType();
3982 QualType T2;
3983 if (NumArgs > 1)
3984 T2 = Args[1]->getType();
3985
3986 // -- If T1 is a class type, the set of member candidates is the
3987 // result of the qualified lookup of T1::operator@
3988 // (13.3.1.1.1); otherwise, the set of member candidates is
3989 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003990 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003991 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003992 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003993 return;
Mike Stump11289f42009-09-09 15:08:12 +00003994
John McCall27b18f82009-11-17 02:14:36 +00003995 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3996 LookupQualifiedName(Operators, T1Rec->getDecl());
3997 Operators.suppressDiagnostics();
3998
Mike Stump11289f42009-09-09 15:08:12 +00003999 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004000 OperEnd = Operators.end();
4001 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004002 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004003 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00004004 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004005 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004006 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004007}
4008
Douglas Gregora11693b2008-11-12 17:17:38 +00004009/// AddBuiltinCandidate - Add a candidate for a built-in
4010/// operator. ResultTy and ParamTys are the result and parameter types
4011/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004012/// arguments being passed to the candidate. IsAssignmentOperator
4013/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004014/// operator. NumContextualBoolArguments is the number of arguments
4015/// (at the beginning of the argument list) that will be contextually
4016/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004017void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004018 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004019 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004020 bool IsAssignmentOperator,
4021 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004022 // Overload resolution is always an unevaluated context.
4023 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
4024
Douglas Gregora11693b2008-11-12 17:17:38 +00004025 // Add this candidate
4026 CandidateSet.push_back(OverloadCandidate());
4027 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004028 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004029 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004030 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004031 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004032 Candidate.BuiltinTypes.ResultTy = ResultTy;
4033 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4034 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4035
4036 // Determine the implicit conversion sequences for each of the
4037 // arguments.
4038 Candidate.Viable = true;
4039 Candidate.Conversions.resize(NumArgs);
4040 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004041 // C++ [over.match.oper]p4:
4042 // For the built-in assignment operators, conversions of the
4043 // left operand are restricted as follows:
4044 // -- no temporaries are introduced to hold the left operand, and
4045 // -- no user-defined conversions are applied to the left
4046 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004047 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004048 //
4049 // We block these conversions by turning off user-defined
4050 // conversions, since that is the only way that initialization of
4051 // a reference to a non-class type can occur from something that
4052 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004053 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004054 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004055 "Contextual conversion to bool requires bool type");
4056 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
4057 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004058 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004059 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004060 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00004061 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004062 }
John McCall0d1da222010-01-12 00:44:57 +00004063 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004064 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004065 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004066 break;
4067 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004068 }
4069}
4070
4071/// BuiltinCandidateTypeSet - A set of types that will be used for the
4072/// candidate operator functions for built-in operators (C++
4073/// [over.built]). The types are separated into pointer types and
4074/// enumeration types.
4075class BuiltinCandidateTypeSet {
4076 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004077 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004078
4079 /// PointerTypes - The set of pointer types that will be used in the
4080 /// built-in candidates.
4081 TypeSet PointerTypes;
4082
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004083 /// MemberPointerTypes - The set of member pointer types that will be
4084 /// used in the built-in candidates.
4085 TypeSet MemberPointerTypes;
4086
Douglas Gregora11693b2008-11-12 17:17:38 +00004087 /// EnumerationTypes - The set of enumeration types that will be
4088 /// used in the built-in candidates.
4089 TypeSet EnumerationTypes;
4090
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004091 /// \brief The set of vector types that will be used in the built-in
4092 /// candidates.
4093 TypeSet VectorTypes;
4094
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004095 /// Sema - The semantic analysis instance where we are building the
4096 /// candidate type set.
4097 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004098
Douglas Gregora11693b2008-11-12 17:17:38 +00004099 /// Context - The AST context in which we will build the type sets.
4100 ASTContext &Context;
4101
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004102 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4103 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004104 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004105
4106public:
4107 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004108 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004109
Mike Stump11289f42009-09-09 15:08:12 +00004110 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004111 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004112
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004113 void AddTypesConvertedFrom(QualType Ty,
4114 SourceLocation Loc,
4115 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004116 bool AllowExplicitConversions,
4117 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004118
4119 /// pointer_begin - First pointer type found;
4120 iterator pointer_begin() { return PointerTypes.begin(); }
4121
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004122 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004123 iterator pointer_end() { return PointerTypes.end(); }
4124
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004125 /// member_pointer_begin - First member pointer type found;
4126 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4127
4128 /// member_pointer_end - Past the last member pointer type found;
4129 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4130
Douglas Gregora11693b2008-11-12 17:17:38 +00004131 /// enumeration_begin - First enumeration type found;
4132 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4133
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004134 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004135 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004136
4137 iterator vector_begin() { return VectorTypes.begin(); }
4138 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregora11693b2008-11-12 17:17:38 +00004139};
4140
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004141/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004142/// the set of pointer types along with any more-qualified variants of
4143/// that type. For example, if @p Ty is "int const *", this routine
4144/// will add "int const *", "int const volatile *", "int const
4145/// restrict *", and "int const volatile restrict *" to the set of
4146/// pointer types. Returns true if the add of @p Ty itself succeeded,
4147/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004148///
4149/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004150bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004151BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4152 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004153
Douglas Gregora11693b2008-11-12 17:17:38 +00004154 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004155 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004156 return false;
4157
John McCall8ccfcb52009-09-24 19:53:00 +00004158 const PointerType *PointerTy = Ty->getAs<PointerType>();
4159 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00004160
John McCall8ccfcb52009-09-24 19:53:00 +00004161 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004162 // Don't add qualified variants of arrays. For one, they're not allowed
4163 // (the qualifier would sink to the element type), and for another, the
4164 // only overload situation where it matters is subscript or pointer +- int,
4165 // and those shouldn't have qualifier variants anyway.
4166 if (PointeeTy->isArrayType())
4167 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004168 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00004169 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00004170 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004171 bool hasVolatile = VisibleQuals.hasVolatile();
4172 bool hasRestrict = VisibleQuals.hasRestrict();
4173
John McCall8ccfcb52009-09-24 19:53:00 +00004174 // Iterate through all strict supersets of BaseCVR.
4175 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4176 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004177 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4178 // in the types.
4179 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4180 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00004181 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4182 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00004183 }
4184
4185 return true;
4186}
4187
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004188/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4189/// to the set of pointer types along with any more-qualified variants of
4190/// that type. For example, if @p Ty is "int const *", this routine
4191/// will add "int const *", "int const volatile *", "int const
4192/// restrict *", and "int const volatile restrict *" to the set of
4193/// pointer types. Returns true if the add of @p Ty itself succeeded,
4194/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004195///
4196/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004197bool
4198BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4199 QualType Ty) {
4200 // Insert this type.
4201 if (!MemberPointerTypes.insert(Ty))
4202 return false;
4203
John McCall8ccfcb52009-09-24 19:53:00 +00004204 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4205 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004206
John McCall8ccfcb52009-09-24 19:53:00 +00004207 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004208 // Don't add qualified variants of arrays. For one, they're not allowed
4209 // (the qualifier would sink to the element type), and for another, the
4210 // only overload situation where it matters is subscript or pointer +- int,
4211 // and those shouldn't have qualifier variants anyway.
4212 if (PointeeTy->isArrayType())
4213 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004214 const Type *ClassTy = PointerTy->getClass();
4215
4216 // Iterate through all strict supersets of the pointee type's CVR
4217 // qualifiers.
4218 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4219 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4220 if ((CVR | BaseCVR) != CVR) continue;
4221
4222 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4223 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004224 }
4225
4226 return true;
4227}
4228
Douglas Gregora11693b2008-11-12 17:17:38 +00004229/// AddTypesConvertedFrom - Add each of the types to which the type @p
4230/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004231/// primarily interested in pointer types and enumeration types. We also
4232/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004233/// AllowUserConversions is true if we should look at the conversion
4234/// functions of a class type, and AllowExplicitConversions if we
4235/// should also include the explicit conversion functions of a class
4236/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004237void
Douglas Gregor5fb53972009-01-14 15:45:31 +00004238BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004239 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004240 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004241 bool AllowExplicitConversions,
4242 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004243 // Only deal with canonical types.
4244 Ty = Context.getCanonicalType(Ty);
4245
4246 // Look through reference types; they aren't part of the type of an
4247 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004248 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00004249 Ty = RefTy->getPointeeType();
4250
4251 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004252 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00004253
Sebastian Redl65ae2002009-11-05 16:36:20 +00004254 // If we're dealing with an array type, decay to the pointer.
4255 if (Ty->isArrayType())
4256 Ty = SemaRef.Context.getArrayDecayedType(Ty);
4257
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004258 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004259 QualType PointeeTy = PointerTy->getPointeeType();
4260
4261 // Insert our type, and its more-qualified variants, into the set
4262 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004263 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00004264 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004265 } else if (Ty->isMemberPointerType()) {
4266 // Member pointers are far easier, since the pointee can't be converted.
4267 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4268 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00004269 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00004270 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004271 } else if (Ty->isVectorType()) {
4272 VectorTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004273 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004274 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004275 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004276 // No conversion functions in incomplete types.
4277 return;
4278 }
Mike Stump11289f42009-09-09 15:08:12 +00004279
Douglas Gregora11693b2008-11-12 17:17:38 +00004280 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00004281 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00004282 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00004283 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004284 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004285 NamedDecl *D = I.getDecl();
4286 if (isa<UsingShadowDecl>(D))
4287 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004288
Mike Stump11289f42009-09-09 15:08:12 +00004289 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00004290 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00004291 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00004292 continue;
4293
John McCallda4458e2010-03-31 01:36:47 +00004294 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004295 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004296 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004297 VisibleQuals);
4298 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004299 }
4300 }
4301 }
4302}
4303
Douglas Gregor84605ae2009-08-24 13:43:27 +00004304/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4305/// the volatile- and non-volatile-qualified assignment operators for the
4306/// given type to the candidate set.
4307static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4308 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004309 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004310 unsigned NumArgs,
4311 OverloadCandidateSet &CandidateSet) {
4312 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004313
Douglas Gregor84605ae2009-08-24 13:43:27 +00004314 // T& operator=(T&, T)
4315 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4316 ParamTypes[1] = T;
4317 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4318 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004319
Douglas Gregor84605ae2009-08-24 13:43:27 +00004320 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4321 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004322 ParamTypes[0]
4323 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004324 ParamTypes[1] = T;
4325 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004326 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004327 }
4328}
Mike Stump11289f42009-09-09 15:08:12 +00004329
Sebastian Redl1054fae2009-10-25 17:03:50 +00004330/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4331/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004332static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4333 Qualifiers VRQuals;
4334 const RecordType *TyRec;
4335 if (const MemberPointerType *RHSMPType =
4336 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004337 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004338 else
4339 TyRec = ArgExpr->getType()->getAs<RecordType>();
4340 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004341 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004342 VRQuals.addVolatile();
4343 VRQuals.addRestrict();
4344 return VRQuals;
4345 }
4346
4347 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004348 if (!ClassDecl->hasDefinition())
4349 return VRQuals;
4350
John McCallad371252010-01-20 00:46:10 +00004351 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004352 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004353
John McCallad371252010-01-20 00:46:10 +00004354 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004355 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004356 NamedDecl *D = I.getDecl();
4357 if (isa<UsingShadowDecl>(D))
4358 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4359 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004360 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4361 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4362 CanTy = ResTypeRef->getPointeeType();
4363 // Need to go down the pointer/mempointer chain and add qualifiers
4364 // as see them.
4365 bool done = false;
4366 while (!done) {
4367 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4368 CanTy = ResTypePtr->getPointeeType();
4369 else if (const MemberPointerType *ResTypeMPtr =
4370 CanTy->getAs<MemberPointerType>())
4371 CanTy = ResTypeMPtr->getPointeeType();
4372 else
4373 done = true;
4374 if (CanTy.isVolatileQualified())
4375 VRQuals.addVolatile();
4376 if (CanTy.isRestrictQualified())
4377 VRQuals.addRestrict();
4378 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4379 return VRQuals;
4380 }
4381 }
4382 }
4383 return VRQuals;
4384}
4385
Douglas Gregord08452f2008-11-19 15:42:04 +00004386/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4387/// operator overloads to the candidate set (C++ [over.built]), based
4388/// on the operator @p Op and the arguments given. For example, if the
4389/// operator is a binary '+', this routine might add "int
4390/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00004391void
Mike Stump11289f42009-09-09 15:08:12 +00004392Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004393 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00004394 Expr **Args, unsigned NumArgs,
4395 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004396 // The set of "promoted arithmetic types", which are the arithmetic
4397 // types are that preserved by promotion (C++ [over.built]p2). Note
4398 // that the first few of these types are the promoted integral
4399 // types; these types need to be first.
4400 // FIXME: What about complex?
4401 const unsigned FirstIntegralType = 0;
4402 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00004403 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00004404 LastPromotedIntegralType = 13;
4405 const unsigned FirstPromotedArithmeticType = 7,
4406 LastPromotedArithmeticType = 16;
4407 const unsigned NumArithmeticTypes = 16;
4408 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00004409 Context.BoolTy, Context.CharTy, Context.WCharTy,
4410// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00004411 Context.SignedCharTy, Context.ShortTy,
4412 Context.UnsignedCharTy, Context.UnsignedShortTy,
4413 Context.IntTy, Context.LongTy, Context.LongLongTy,
4414 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
4415 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
4416 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00004417 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
4418 "Invalid first promoted integral type");
4419 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4420 == Context.UnsignedLongLongTy &&
4421 "Invalid last promoted integral type");
4422 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
4423 "Invalid first promoted arithmetic type");
4424 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4425 == Context.LongDoubleTy &&
4426 "Invalid last promoted arithmetic type");
4427
Douglas Gregora11693b2008-11-12 17:17:38 +00004428 // Find all of the types that the arguments can convert to, but only
4429 // if the operator we're looking at has built-in operator candidates
4430 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004431 Qualifiers VisibleTypeConversionsQuals;
4432 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004433 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4434 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4435
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004436 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004437 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4438 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4439 OpLoc,
4440 true,
4441 (Op == OO_Exclaim ||
4442 Op == OO_AmpAmp ||
4443 Op == OO_PipePipe),
4444 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004445
4446 bool isComparison = false;
4447 switch (Op) {
4448 case OO_None:
4449 case NUM_OVERLOADED_OPERATORS:
4450 assert(false && "Expected an overloaded operator");
4451 break;
4452
Douglas Gregord08452f2008-11-19 15:42:04 +00004453 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00004454 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00004455 goto UnaryStar;
4456 else
4457 goto BinaryStar;
4458 break;
4459
4460 case OO_Plus: // '+' is either unary or binary
4461 if (NumArgs == 1)
4462 goto UnaryPlus;
4463 else
4464 goto BinaryPlus;
4465 break;
4466
4467 case OO_Minus: // '-' is either unary or binary
4468 if (NumArgs == 1)
4469 goto UnaryMinus;
4470 else
4471 goto BinaryMinus;
4472 break;
4473
4474 case OO_Amp: // '&' is either unary or binary
4475 if (NumArgs == 1)
4476 goto UnaryAmp;
4477 else
4478 goto BinaryAmp;
4479
4480 case OO_PlusPlus:
4481 case OO_MinusMinus:
4482 // C++ [over.built]p3:
4483 //
4484 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4485 // is either volatile or empty, there exist candidate operator
4486 // functions of the form
4487 //
4488 // VQ T& operator++(VQ T&);
4489 // T operator++(VQ T&, int);
4490 //
4491 // C++ [over.built]p4:
4492 //
4493 // For every pair (T, VQ), where T is an arithmetic type other
4494 // than bool, and VQ is either volatile or empty, there exist
4495 // candidate operator functions of the form
4496 //
4497 // VQ T& operator--(VQ T&);
4498 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00004499 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004500 Arith < NumArithmeticTypes; ++Arith) {
4501 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00004502 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004503 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00004504
4505 // Non-volatile version.
4506 if (NumArgs == 1)
4507 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4508 else
4509 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004510 // heuristic to reduce number of builtin candidates in the set.
4511 // Add volatile version only if there are conversions to a volatile type.
4512 if (VisibleTypeConversionsQuals.hasVolatile()) {
4513 // Volatile version
4514 ParamTypes[0]
4515 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4516 if (NumArgs == 1)
4517 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4518 else
4519 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4520 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004521 }
4522
4523 // C++ [over.built]p5:
4524 //
4525 // For every pair (T, VQ), where T is a cv-qualified or
4526 // cv-unqualified object type, and VQ is either volatile or
4527 // empty, there exist candidate operator functions of the form
4528 //
4529 // T*VQ& operator++(T*VQ&);
4530 // T*VQ& operator--(T*VQ&);
4531 // T* operator++(T*VQ&, int);
4532 // T* operator--(T*VQ&, int);
4533 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4534 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4535 // Skip pointer types that aren't pointers to object types.
Eli Friedmana170cd62010-08-05 02:49:48 +00004536 if (!(*Ptr)->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00004537 continue;
4538
Mike Stump11289f42009-09-09 15:08:12 +00004539 QualType ParamTypes[2] = {
4540 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00004541 };
Mike Stump11289f42009-09-09 15:08:12 +00004542
Douglas Gregord08452f2008-11-19 15:42:04 +00004543 // Without volatile
4544 if (NumArgs == 1)
4545 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4546 else
4547 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4548
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004549 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4550 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004551 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00004552 ParamTypes[0]
4553 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00004554 if (NumArgs == 1)
4555 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4556 else
4557 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4558 }
4559 }
4560 break;
4561
4562 UnaryStar:
4563 // C++ [over.built]p6:
4564 // For every cv-qualified or cv-unqualified object type T, there
4565 // exist candidate operator functions of the form
4566 //
4567 // T& operator*(T*);
4568 //
4569 // C++ [over.built]p7:
4570 // For every function type T, there exist candidate operator
4571 // functions of the form
4572 // T& operator*(T*);
4573 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4574 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4575 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004576 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004577 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00004578 &ParamTy, Args, 1, CandidateSet);
4579 }
4580 break;
4581
4582 UnaryPlus:
4583 // C++ [over.built]p8:
4584 // For every type T, there exist candidate operator functions of
4585 // the form
4586 //
4587 // T* operator+(T*);
4588 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4589 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4590 QualType ParamTy = *Ptr;
4591 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4592 }
Mike Stump11289f42009-09-09 15:08:12 +00004593
Douglas Gregord08452f2008-11-19 15:42:04 +00004594 // Fall through
4595
4596 UnaryMinus:
4597 // C++ [over.built]p9:
4598 // For every promoted arithmetic type T, there exist candidate
4599 // operator functions of the form
4600 //
4601 // T operator+(T);
4602 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00004603 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004604 Arith < LastPromotedArithmeticType; ++Arith) {
4605 QualType ArithTy = ArithmeticTypes[Arith];
4606 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4607 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004608
4609 // Extension: We also add these operators for vector types.
4610 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4611 VecEnd = CandidateTypes.vector_end();
4612 Vec != VecEnd; ++Vec) {
4613 QualType VecTy = *Vec;
4614 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4615 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004616 break;
4617
4618 case OO_Tilde:
4619 // C++ [over.built]p10:
4620 // For every promoted integral type T, there exist candidate
4621 // operator functions of the form
4622 //
4623 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00004624 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004625 Int < LastPromotedIntegralType; ++Int) {
4626 QualType IntTy = ArithmeticTypes[Int];
4627 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4628 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004629
4630 // Extension: We also add this operator for vector types.
4631 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4632 VecEnd = CandidateTypes.vector_end();
4633 Vec != VecEnd; ++Vec) {
4634 QualType VecTy = *Vec;
4635 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4636 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004637 break;
4638
Douglas Gregora11693b2008-11-12 17:17:38 +00004639 case OO_New:
4640 case OO_Delete:
4641 case OO_Array_New:
4642 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00004643 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00004644 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00004645 break;
4646
4647 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00004648 UnaryAmp:
4649 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00004650 // C++ [over.match.oper]p3:
4651 // -- For the operator ',', the unary operator '&', or the
4652 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00004653 break;
4654
Douglas Gregor84605ae2009-08-24 13:43:27 +00004655 case OO_EqualEqual:
4656 case OO_ExclaimEqual:
4657 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00004658 // For every pointer to member type T, there exist candidate operator
4659 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00004660 //
4661 // bool operator==(T,T);
4662 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00004663 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00004664 MemPtr = CandidateTypes.member_pointer_begin(),
4665 MemPtrEnd = CandidateTypes.member_pointer_end();
4666 MemPtr != MemPtrEnd;
4667 ++MemPtr) {
4668 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4669 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4670 }
Mike Stump11289f42009-09-09 15:08:12 +00004671
Douglas Gregor84605ae2009-08-24 13:43:27 +00004672 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004673
Douglas Gregora11693b2008-11-12 17:17:38 +00004674 case OO_Less:
4675 case OO_Greater:
4676 case OO_LessEqual:
4677 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004678 // C++ [over.built]p15:
4679 //
4680 // For every pointer or enumeration type T, there exist
4681 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004682 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004683 // bool operator<(T, T);
4684 // bool operator>(T, T);
4685 // bool operator<=(T, T);
4686 // bool operator>=(T, T);
4687 // bool operator==(T, T);
4688 // bool operator!=(T, T);
4689 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4690 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4691 QualType ParamTypes[2] = { *Ptr, *Ptr };
4692 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4693 }
Mike Stump11289f42009-09-09 15:08:12 +00004694 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00004695 = CandidateTypes.enumeration_begin();
4696 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4697 QualType ParamTypes[2] = { *Enum, *Enum };
4698 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4699 }
4700
4701 // Fall through.
4702 isComparison = true;
4703
Douglas Gregord08452f2008-11-19 15:42:04 +00004704 BinaryPlus:
4705 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00004706 if (!isComparison) {
4707 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4708
4709 // C++ [over.built]p13:
4710 //
4711 // For every cv-qualified or cv-unqualified object type T
4712 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004713 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004714 // T* operator+(T*, ptrdiff_t);
4715 // T& operator[](T*, ptrdiff_t); [BELOW]
4716 // T* operator-(T*, ptrdiff_t);
4717 // T* operator+(ptrdiff_t, T*);
4718 // T& operator[](ptrdiff_t, T*); [BELOW]
4719 //
4720 // C++ [over.built]p14:
4721 //
4722 // For every T, where T is a pointer to object type, there
4723 // exist candidate operator functions of the form
4724 //
4725 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00004726 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00004727 = CandidateTypes.pointer_begin();
4728 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4729 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4730
4731 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4732 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4733
4734 if (Op == OO_Plus) {
4735 // T* operator+(ptrdiff_t, T*);
4736 ParamTypes[0] = ParamTypes[1];
4737 ParamTypes[1] = *Ptr;
4738 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4739 } else {
4740 // ptrdiff_t operator-(T, T);
4741 ParamTypes[1] = *Ptr;
4742 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4743 Args, 2, CandidateSet);
4744 }
4745 }
4746 }
4747 // Fall through
4748
Douglas Gregora11693b2008-11-12 17:17:38 +00004749 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00004750 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00004751 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00004752 // C++ [over.built]p12:
4753 //
4754 // For every pair of promoted arithmetic types L and R, there
4755 // exist candidate operator functions of the form
4756 //
4757 // LR operator*(L, R);
4758 // LR operator/(L, R);
4759 // LR operator+(L, R);
4760 // LR operator-(L, R);
4761 // bool operator<(L, R);
4762 // bool operator>(L, R);
4763 // bool operator<=(L, R);
4764 // bool operator>=(L, R);
4765 // bool operator==(L, R);
4766 // bool operator!=(L, R);
4767 //
4768 // where LR is the result of the usual arithmetic conversions
4769 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004770 //
4771 // C++ [over.built]p24:
4772 //
4773 // For every pair of promoted arithmetic types L and R, there exist
4774 // candidate operator functions of the form
4775 //
4776 // LR operator?(bool, L, R);
4777 //
4778 // where LR is the result of the usual arithmetic conversions
4779 // between types L and R.
4780 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004781 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004782 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004783 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004784 Right < LastPromotedArithmeticType; ++Right) {
4785 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004786 QualType Result
4787 = isComparison
4788 ? Context.BoolTy
4789 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004790 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4791 }
4792 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004793
4794 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
4795 // conditional operator for vector types.
4796 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4797 Vec1End = CandidateTypes.vector_end();
4798 Vec1 != Vec1End; ++Vec1)
4799 for (BuiltinCandidateTypeSet::iterator
4800 Vec2 = CandidateTypes.vector_begin(),
4801 Vec2End = CandidateTypes.vector_end();
4802 Vec2 != Vec2End; ++Vec2) {
4803 QualType LandR[2] = { *Vec1, *Vec2 };
4804 QualType Result;
4805 if (isComparison)
4806 Result = Context.BoolTy;
4807 else {
4808 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
4809 Result = *Vec1;
4810 else
4811 Result = *Vec2;
4812 }
4813
4814 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4815 }
4816
Douglas Gregora11693b2008-11-12 17:17:38 +00004817 break;
4818
4819 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00004820 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00004821 case OO_Caret:
4822 case OO_Pipe:
4823 case OO_LessLess:
4824 case OO_GreaterGreater:
4825 // C++ [over.built]p17:
4826 //
4827 // For every pair of promoted integral types L and R, there
4828 // exist candidate operator functions of the form
4829 //
4830 // LR operator%(L, R);
4831 // LR operator&(L, R);
4832 // LR operator^(L, R);
4833 // LR operator|(L, R);
4834 // L operator<<(L, R);
4835 // L operator>>(L, R);
4836 //
4837 // where LR is the result of the usual arithmetic conversions
4838 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00004839 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004840 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004841 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004842 Right < LastPromotedIntegralType; ++Right) {
4843 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4844 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4845 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004846 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004847 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4848 }
4849 }
4850 break;
4851
4852 case OO_Equal:
4853 // C++ [over.built]p20:
4854 //
4855 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00004856 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00004857 // empty, there exist candidate operator functions of the form
4858 //
4859 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004860 for (BuiltinCandidateTypeSet::iterator
4861 Enum = CandidateTypes.enumeration_begin(),
4862 EnumEnd = CandidateTypes.enumeration_end();
4863 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00004864 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004865 CandidateSet);
4866 for (BuiltinCandidateTypeSet::iterator
4867 MemPtr = CandidateTypes.member_pointer_begin(),
4868 MemPtrEnd = CandidateTypes.member_pointer_end();
4869 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00004870 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004871 CandidateSet);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004872
4873 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00004874
4875 case OO_PlusEqual:
4876 case OO_MinusEqual:
4877 // C++ [over.built]p19:
4878 //
4879 // For every pair (T, VQ), where T is any type and VQ is either
4880 // volatile or empty, there exist candidate operator functions
4881 // of the form
4882 //
4883 // T*VQ& operator=(T*VQ&, T*);
4884 //
4885 // C++ [over.built]p21:
4886 //
4887 // For every pair (T, VQ), where T is a cv-qualified or
4888 // cv-unqualified object type and VQ is either volatile or
4889 // empty, there exist candidate operator functions of the form
4890 //
4891 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4892 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4893 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4894 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4895 QualType ParamTypes[2];
4896 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4897
4898 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004899 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004900 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4901 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004902
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004903 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4904 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004905 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00004906 ParamTypes[0]
4907 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00004908 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4909 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00004910 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004911 }
4912 // Fall through.
4913
4914 case OO_StarEqual:
4915 case OO_SlashEqual:
4916 // C++ [over.built]p18:
4917 //
4918 // For every triple (L, VQ, R), where L is an arithmetic type,
4919 // VQ is either volatile or empty, and R is a promoted
4920 // arithmetic type, there exist candidate operator functions of
4921 // the form
4922 //
4923 // VQ L& operator=(VQ L&, R);
4924 // VQ L& operator*=(VQ L&, R);
4925 // VQ L& operator/=(VQ L&, R);
4926 // VQ L& operator+=(VQ L&, R);
4927 // VQ L& operator-=(VQ L&, R);
4928 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004929 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004930 Right < LastPromotedArithmeticType; ++Right) {
4931 QualType ParamTypes[2];
4932 ParamTypes[1] = ArithmeticTypes[Right];
4933
4934 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004935 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004936 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4937 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004938
4939 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004940 if (VisibleTypeConversionsQuals.hasVolatile()) {
4941 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4942 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4943 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4944 /*IsAssigmentOperator=*/Op == OO_Equal);
4945 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004946 }
4947 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004948
4949 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
4950 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4951 Vec1End = CandidateTypes.vector_end();
4952 Vec1 != Vec1End; ++Vec1)
4953 for (BuiltinCandidateTypeSet::iterator
4954 Vec2 = CandidateTypes.vector_begin(),
4955 Vec2End = CandidateTypes.vector_end();
4956 Vec2 != Vec2End; ++Vec2) {
4957 QualType ParamTypes[2];
4958 ParamTypes[1] = *Vec2;
4959 // Add this built-in operator as a candidate (VQ is empty).
4960 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
4961 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4962 /*IsAssigmentOperator=*/Op == OO_Equal);
4963
4964 // Add this built-in operator as a candidate (VQ is 'volatile').
4965 if (VisibleTypeConversionsQuals.hasVolatile()) {
4966 ParamTypes[0] = Context.getVolatileType(*Vec1);
4967 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4968 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4969 /*IsAssigmentOperator=*/Op == OO_Equal);
4970 }
4971 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004972 break;
4973
4974 case OO_PercentEqual:
4975 case OO_LessLessEqual:
4976 case OO_GreaterGreaterEqual:
4977 case OO_AmpEqual:
4978 case OO_CaretEqual:
4979 case OO_PipeEqual:
4980 // C++ [over.built]p22:
4981 //
4982 // For every triple (L, VQ, R), where L is an integral type, VQ
4983 // is either volatile or empty, and R is a promoted integral
4984 // type, there exist candidate operator functions of the form
4985 //
4986 // VQ L& operator%=(VQ L&, R);
4987 // VQ L& operator<<=(VQ L&, R);
4988 // VQ L& operator>>=(VQ L&, R);
4989 // VQ L& operator&=(VQ L&, R);
4990 // VQ L& operator^=(VQ L&, R);
4991 // VQ L& operator|=(VQ L&, R);
4992 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004993 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004994 Right < LastPromotedIntegralType; ++Right) {
4995 QualType ParamTypes[2];
4996 ParamTypes[1] = ArithmeticTypes[Right];
4997
4998 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004999 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00005000 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00005001 if (VisibleTypeConversionsQuals.hasVolatile()) {
5002 // Add this built-in operator as a candidate (VQ is 'volatile').
5003 ParamTypes[0] = ArithmeticTypes[Left];
5004 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
5005 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5006 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5007 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005008 }
5009 }
5010 break;
5011
Douglas Gregord08452f2008-11-19 15:42:04 +00005012 case OO_Exclaim: {
5013 // C++ [over.operator]p23:
5014 //
5015 // There also exist candidate operator functions of the form
5016 //
Mike Stump11289f42009-09-09 15:08:12 +00005017 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00005018 // bool operator&&(bool, bool); [BELOW]
5019 // bool operator||(bool, bool); [BELOW]
5020 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00005021 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5022 /*IsAssignmentOperator=*/false,
5023 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00005024 break;
5025 }
5026
Douglas Gregora11693b2008-11-12 17:17:38 +00005027 case OO_AmpAmp:
5028 case OO_PipePipe: {
5029 // C++ [over.operator]p23:
5030 //
5031 // There also exist candidate operator functions of the form
5032 //
Douglas Gregord08452f2008-11-19 15:42:04 +00005033 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00005034 // bool operator&&(bool, bool);
5035 // bool operator||(bool, bool);
5036 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00005037 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5038 /*IsAssignmentOperator=*/false,
5039 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00005040 break;
5041 }
5042
5043 case OO_Subscript:
5044 // C++ [over.built]p13:
5045 //
5046 // For every cv-qualified or cv-unqualified object type T there
5047 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00005048 //
Douglas Gregora11693b2008-11-12 17:17:38 +00005049 // T* operator+(T*, ptrdiff_t); [ABOVE]
5050 // T& operator[](T*, ptrdiff_t);
5051 // T* operator-(T*, ptrdiff_t); [ABOVE]
5052 // T* operator+(ptrdiff_t, T*); [ABOVE]
5053 // T& operator[](ptrdiff_t, T*);
5054 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
5055 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5056 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005057 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005058 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00005059
5060 // T& operator[](T*, ptrdiff_t)
5061 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5062
5063 // T& operator[](ptrdiff_t, T*);
5064 ParamTypes[0] = ParamTypes[1];
5065 ParamTypes[1] = *Ptr;
5066 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005067 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005068 break;
5069
5070 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005071 // C++ [over.built]p11:
5072 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5073 // C1 is the same type as C2 or is a derived class of C2, T is an object
5074 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5075 // there exist candidate operator functions of the form
5076 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5077 // where CV12 is the union of CV1 and CV2.
5078 {
5079 for (BuiltinCandidateTypeSet::iterator Ptr =
5080 CandidateTypes.pointer_begin();
5081 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5082 QualType C1Ty = (*Ptr);
5083 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005084 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005085 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005086 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005087 if (!isa<RecordType>(C1))
5088 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005089 // heuristic to reduce number of builtin candidates in the set.
5090 // Add volatile/restrict version only if there are conversions to a
5091 // volatile/restrict type.
5092 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5093 continue;
5094 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5095 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005096 }
5097 for (BuiltinCandidateTypeSet::iterator
5098 MemPtr = CandidateTypes.member_pointer_begin(),
5099 MemPtrEnd = CandidateTypes.member_pointer_end();
5100 MemPtr != MemPtrEnd; ++MemPtr) {
5101 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5102 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00005103 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005104 if (C1 != C2 && !IsDerivedFrom(C1, C2))
5105 break;
5106 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5107 // build CV12 T&
5108 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005109 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5110 T.isVolatileQualified())
5111 continue;
5112 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5113 T.isRestrictQualified())
5114 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005115 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005116 QualType ResultTy = Context.getLValueReferenceType(T);
5117 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5118 }
5119 }
5120 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005121 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005122
5123 case OO_Conditional:
5124 // Note that we don't consider the first argument, since it has been
5125 // contextually converted to bool long ago. The candidates below are
5126 // therefore added as binary.
5127 //
5128 // C++ [over.built]p24:
5129 // For every type T, where T is a pointer or pointer-to-member type,
5130 // there exist candidate operator functions of the form
5131 //
5132 // T operator?(bool, T, T);
5133 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00005134 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
5135 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
5136 QualType ParamTypes[2] = { *Ptr, *Ptr };
5137 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5138 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005139 for (BuiltinCandidateTypeSet::iterator Ptr =
5140 CandidateTypes.member_pointer_begin(),
5141 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
5142 QualType ParamTypes[2] = { *Ptr, *Ptr };
5143 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5144 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005145 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00005146 }
5147}
5148
Douglas Gregore254f902009-02-04 00:32:51 +00005149/// \brief Add function candidates found via argument-dependent lookup
5150/// to the set of overloading candidates.
5151///
5152/// This routine performs argument-dependent name lookup based on the
5153/// given function name (which may also be an operator name) and adds
5154/// all of the overload candidates found by ADL to the overload
5155/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00005156void
Douglas Gregore254f902009-02-04 00:32:51 +00005157Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00005158 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00005159 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00005160 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005161 OverloadCandidateSet& CandidateSet,
5162 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00005163 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00005164
John McCall91f61fc2010-01-26 06:04:06 +00005165 // FIXME: This approach for uniquing ADL results (and removing
5166 // redundant candidates from the set) relies on pointer-equality,
5167 // which means we need to key off the canonical decl. However,
5168 // always going back to the canonical decl might not get us the
5169 // right set of default arguments. What default arguments are
5170 // we supposed to consider on ADL candidates, anyway?
5171
Douglas Gregorcabea402009-09-22 15:41:20 +00005172 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00005173 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00005174
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005175 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005176 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5177 CandEnd = CandidateSet.end();
5178 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00005179 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00005180 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00005181 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00005182 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00005183 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005184
5185 // For each of the ADL candidates we found, add it to the overload
5186 // set.
John McCall8fe68082010-01-26 07:16:45 +00005187 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00005188 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00005189 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00005190 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00005191 continue;
5192
John McCalla0296f72010-03-19 07:35:19 +00005193 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005194 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005195 } else
John McCall4c4c1df2010-01-26 03:27:55 +00005196 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00005197 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00005198 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00005199 }
Douglas Gregore254f902009-02-04 00:32:51 +00005200}
5201
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005202/// isBetterOverloadCandidate - Determines whether the first overload
5203/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00005204bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005205Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCallbc077cf2010-02-08 23:07:23 +00005206 const OverloadCandidate& Cand2,
5207 SourceLocation Loc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005208 // Define viable functions to be better candidates than non-viable
5209 // functions.
5210 if (!Cand2.Viable)
5211 return Cand1.Viable;
5212 else if (!Cand1.Viable)
5213 return false;
5214
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005215 // C++ [over.match.best]p1:
5216 //
5217 // -- if F is a static member function, ICS1(F) is defined such
5218 // that ICS1(F) is neither better nor worse than ICS1(G) for
5219 // any function G, and, symmetrically, ICS1(G) is neither
5220 // better nor worse than ICS1(F).
5221 unsigned StartArg = 0;
5222 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5223 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005224
Douglas Gregord3cb3562009-07-07 23:38:56 +00005225 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005226 // A viable function F1 is defined to be a better function than another
5227 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00005228 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005229 unsigned NumArgs = Cand1.Conversions.size();
5230 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5231 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005232 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005233 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
5234 Cand2.Conversions[ArgIdx])) {
5235 case ImplicitConversionSequence::Better:
5236 // Cand1 has a better conversion sequence.
5237 HasBetterConversion = true;
5238 break;
5239
5240 case ImplicitConversionSequence::Worse:
5241 // Cand1 can't be better than Cand2.
5242 return false;
5243
5244 case ImplicitConversionSequence::Indistinguishable:
5245 // Do nothing.
5246 break;
5247 }
5248 }
5249
Mike Stump11289f42009-09-09 15:08:12 +00005250 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00005251 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005252 if (HasBetterConversion)
5253 return true;
5254
Mike Stump11289f42009-09-09 15:08:12 +00005255 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00005256 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00005257 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00005258 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5259 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005260
5261 // -- F1 and F2 are function template specializations, and the function
5262 // template for F1 is more specialized than the template for F2
5263 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00005264 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00005265 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5266 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00005267 if (FunctionTemplateDecl *BetterTemplate
5268 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5269 Cand2.Function->getPrimaryTemplate(),
John McCallbc077cf2010-02-08 23:07:23 +00005270 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00005271 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5272 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00005273 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005274
Douglas Gregora1f013e2008-11-07 22:36:19 +00005275 // -- the context is an initialization by user-defined conversion
5276 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5277 // from the return type of F1 to the destination type (i.e.,
5278 // the type of the entity being initialized) is a better
5279 // conversion sequence than the standard conversion sequence
5280 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00005281 if (Cand1.Function && Cand2.Function &&
5282 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00005283 isa<CXXConversionDecl>(Cand2.Function)) {
5284 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
5285 Cand2.FinalConversion)) {
5286 case ImplicitConversionSequence::Better:
5287 // Cand1 has a better conversion sequence.
5288 return true;
5289
5290 case ImplicitConversionSequence::Worse:
5291 // Cand1 can't be better than Cand2.
5292 return false;
5293
5294 case ImplicitConversionSequence::Indistinguishable:
5295 // Do nothing
5296 break;
5297 }
5298 }
5299
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005300 return false;
5301}
5302
Mike Stump11289f42009-09-09 15:08:12 +00005303/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005304/// within an overload candidate set.
5305///
5306/// \param CandidateSet the set of candidate functions.
5307///
5308/// \param Loc the location of the function name (or operator symbol) for
5309/// which overload resolution occurs.
5310///
Mike Stump11289f42009-09-09 15:08:12 +00005311/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005312/// function, Best points to the candidate function found.
5313///
5314/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005315OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
5316 SourceLocation Loc,
5317 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005318 // Find the best viable function.
5319 Best = CandidateSet.end();
5320 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5321 Cand != CandidateSet.end(); ++Cand) {
5322 if (Cand->Viable) {
John McCallbc077cf2010-02-08 23:07:23 +00005323 if (Best == CandidateSet.end() ||
5324 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005325 Best = Cand;
5326 }
5327 }
5328
5329 // If we didn't find any viable functions, abort.
5330 if (Best == CandidateSet.end())
5331 return OR_No_Viable_Function;
5332
5333 // Make sure that this function is better than every other viable
5334 // function. If not, we have an ambiguity.
5335 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5336 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00005337 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005338 Cand != Best &&
John McCallbc077cf2010-02-08 23:07:23 +00005339 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005340 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005341 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005342 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005343 }
Mike Stump11289f42009-09-09 15:08:12 +00005344
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005345 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00005346 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005347 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005348 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00005349 return OR_Deleted;
5350
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005351 // C++ [basic.def.odr]p2:
5352 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00005353 // when referred to from a potentially-evaluated expression. [Note: this
5354 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005355 // (clause 13), user-defined conversions (12.3.2), allocation function for
5356 // placement new (5.3.4), as well as non-default initialization (8.5).
5357 if (Best->Function)
5358 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005359 return OR_Success;
5360}
5361
John McCall53262c92010-01-12 02:15:36 +00005362namespace {
5363
5364enum OverloadCandidateKind {
5365 oc_function,
5366 oc_method,
5367 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005368 oc_function_template,
5369 oc_method_template,
5370 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00005371 oc_implicit_default_constructor,
5372 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005373 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00005374};
5375
John McCalle1ac8d12010-01-13 00:25:19 +00005376OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5377 FunctionDecl *Fn,
5378 std::string &Description) {
5379 bool isTemplate = false;
5380
5381 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5382 isTemplate = true;
5383 Description = S.getTemplateArgumentBindingsText(
5384 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5385 }
John McCallfd0b2f82010-01-06 09:43:14 +00005386
5387 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00005388 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005389 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005390
John McCall53262c92010-01-12 02:15:36 +00005391 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5392 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005393 }
5394
5395 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5396 // This actually gets spelled 'candidate function' for now, but
5397 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00005398 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005399 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00005400
5401 assert(Meth->isCopyAssignment()
5402 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00005403 return oc_implicit_copy_assignment;
5404 }
5405
John McCalle1ac8d12010-01-13 00:25:19 +00005406 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00005407}
5408
5409} // end anonymous namespace
5410
5411// Notes the location of an overload candidate.
5412void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00005413 std::string FnDesc;
5414 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5415 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5416 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00005417}
5418
John McCall0d1da222010-01-12 00:44:57 +00005419/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5420/// "lead" diagnostic; it will be given two arguments, the source and
5421/// target types of the conversion.
5422void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
5423 SourceLocation CaretLoc,
5424 const PartialDiagnostic &PDiag) {
5425 Diag(CaretLoc, PDiag)
5426 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
5427 for (AmbiguousConversionSequence::const_iterator
5428 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
5429 NoteOverloadCandidate(*I);
5430 }
John McCall12f97bc2010-01-08 04:41:39 +00005431}
5432
John McCall0d1da222010-01-12 00:44:57 +00005433namespace {
5434
John McCall6a61b522010-01-13 09:16:55 +00005435void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5436 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5437 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00005438 assert(Cand->Function && "for now, candidate must be a function");
5439 FunctionDecl *Fn = Cand->Function;
5440
5441 // There's a conversion slot for the object argument if this is a
5442 // non-constructor method. Note that 'I' corresponds the
5443 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00005444 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00005445 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00005446 if (I == 0)
5447 isObjectArgument = true;
5448 else
5449 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00005450 }
5451
John McCalle1ac8d12010-01-13 00:25:19 +00005452 std::string FnDesc;
5453 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5454
John McCall6a61b522010-01-13 09:16:55 +00005455 Expr *FromExpr = Conv.Bad.FromExpr;
5456 QualType FromTy = Conv.Bad.getFromType();
5457 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00005458
John McCallfb7ad0f2010-02-02 02:42:52 +00005459 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00005460 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00005461 Expr *E = FromExpr->IgnoreParens();
5462 if (isa<UnaryOperator>(E))
5463 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00005464 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00005465
5466 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5467 << (unsigned) FnKind << FnDesc
5468 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5469 << ToTy << Name << I+1;
5470 return;
5471 }
5472
John McCall6d174642010-01-23 08:10:49 +00005473 // Do some hand-waving analysis to see if the non-viability is due
5474 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00005475 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5476 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5477 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5478 CToTy = RT->getPointeeType();
5479 else {
5480 // TODO: detect and diagnose the full richness of const mismatches.
5481 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5482 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5483 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5484 }
5485
5486 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5487 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5488 // It is dumb that we have to do this here.
5489 while (isa<ArrayType>(CFromTy))
5490 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5491 while (isa<ArrayType>(CToTy))
5492 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5493
5494 Qualifiers FromQs = CFromTy.getQualifiers();
5495 Qualifiers ToQs = CToTy.getQualifiers();
5496
5497 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5498 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5499 << (unsigned) FnKind << FnDesc
5500 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5501 << FromTy
5502 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5503 << (unsigned) isObjectArgument << I+1;
5504 return;
5505 }
5506
5507 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5508 assert(CVR && "unexpected qualifiers mismatch");
5509
5510 if (isObjectArgument) {
5511 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5512 << (unsigned) FnKind << FnDesc
5513 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5514 << FromTy << (CVR - 1);
5515 } else {
5516 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5517 << (unsigned) FnKind << FnDesc
5518 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5519 << FromTy << (CVR - 1) << I+1;
5520 }
5521 return;
5522 }
5523
John McCall6d174642010-01-23 08:10:49 +00005524 // Diagnose references or pointers to incomplete types differently,
5525 // since it's far from impossible that the incompleteness triggered
5526 // the failure.
5527 QualType TempFromTy = FromTy.getNonReferenceType();
5528 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5529 TempFromTy = PTy->getPointeeType();
5530 if (TempFromTy->isIncompleteType()) {
5531 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5532 << (unsigned) FnKind << FnDesc
5533 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5534 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5535 return;
5536 }
5537
Douglas Gregor56f2e342010-06-30 23:01:39 +00005538 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005539 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00005540 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
5541 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
5542 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5543 FromPtrTy->getPointeeType()) &&
5544 !FromPtrTy->getPointeeType()->isIncompleteType() &&
5545 !ToPtrTy->getPointeeType()->isIncompleteType() &&
5546 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
5547 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005548 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00005549 }
5550 } else if (const ObjCObjectPointerType *FromPtrTy
5551 = FromTy->getAs<ObjCObjectPointerType>()) {
5552 if (const ObjCObjectPointerType *ToPtrTy
5553 = ToTy->getAs<ObjCObjectPointerType>())
5554 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
5555 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
5556 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5557 FromPtrTy->getPointeeType()) &&
5558 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005559 BaseToDerivedConversion = 2;
5560 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
5561 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
5562 !FromTy->isIncompleteType() &&
5563 !ToRefTy->getPointeeType()->isIncompleteType() &&
5564 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
5565 BaseToDerivedConversion = 3;
5566 }
5567
5568 if (BaseToDerivedConversion) {
Douglas Gregor56f2e342010-06-30 23:01:39 +00005569 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005570 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00005571 << (unsigned) FnKind << FnDesc
5572 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005573 << (BaseToDerivedConversion - 1)
Douglas Gregor56f2e342010-06-30 23:01:39 +00005574 << FromTy << ToTy << I+1;
5575 return;
5576 }
5577
John McCall47000992010-01-14 03:28:57 +00005578 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00005579 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5580 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00005581 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00005582 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00005583}
5584
5585void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5586 unsigned NumFormalArgs) {
5587 // TODO: treat calls to a missing default constructor as a special case
5588
5589 FunctionDecl *Fn = Cand->Function;
5590 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5591
5592 unsigned MinParams = Fn->getMinRequiredArguments();
5593
5594 // at least / at most / exactly
Douglas Gregor02eb4832010-05-08 18:13:28 +00005595 // FIXME: variadic templates "at most" should account for parameter packs
John McCall6a61b522010-01-13 09:16:55 +00005596 unsigned mode, modeCount;
5597 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005598 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5599 (Cand->FailureKind == ovl_fail_bad_deduction &&
5600 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCall6a61b522010-01-13 09:16:55 +00005601 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5602 mode = 0; // "at least"
5603 else
5604 mode = 2; // "exactly"
5605 modeCount = MinParams;
5606 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005607 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5608 (Cand->FailureKind == ovl_fail_bad_deduction &&
5609 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00005610 if (MinParams != FnTy->getNumArgs())
5611 mode = 1; // "at most"
5612 else
5613 mode = 2; // "exactly"
5614 modeCount = FnTy->getNumArgs();
5615 }
5616
5617 std::string Description;
5618 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5619
5620 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregor02eb4832010-05-08 18:13:28 +00005621 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5622 << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00005623}
5624
John McCall8b9ed552010-02-01 18:53:26 +00005625/// Diagnose a failed template-argument deduction.
5626void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5627 Expr **Args, unsigned NumArgs) {
5628 FunctionDecl *Fn = Cand->Function; // pattern
5629
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005630 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005631 NamedDecl *ParamD;
5632 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5633 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5634 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00005635 switch (Cand->DeductionFailure.Result) {
5636 case Sema::TDK_Success:
5637 llvm_unreachable("TDK_success while diagnosing bad deduction");
5638
5639 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00005640 assert(ParamD && "no parameter found for incomplete deduction result");
5641 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5642 << ParamD->getDeclName();
5643 return;
5644 }
5645
John McCall42d7d192010-08-05 09:05:08 +00005646 case Sema::TDK_Underqualified: {
5647 assert(ParamD && "no parameter found for bad qualifiers deduction result");
5648 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
5649
5650 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
5651
5652 // Param will have been canonicalized, but it should just be a
5653 // qualified version of ParamD, so move the qualifiers to that.
5654 QualifierCollector Qs(S.Context);
5655 Qs.strip(Param);
5656 QualType NonCanonParam = Qs.apply(TParam->getTypeForDecl());
5657 assert(S.Context.hasSameType(Param, NonCanonParam));
5658
5659 // Arg has also been canonicalized, but there's nothing we can do
5660 // about that. It also doesn't matter as much, because it won't
5661 // have any template parameters in it (because deduction isn't
5662 // done on dependent types).
5663 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
5664
5665 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
5666 << ParamD->getDeclName() << Arg << NonCanonParam;
5667 return;
5668 }
5669
5670 case Sema::TDK_Inconsistent: {
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005671 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005672 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005673 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005674 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005675 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005676 which = 1;
5677 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005678 which = 2;
5679 }
5680
5681 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5682 << which << ParamD->getDeclName()
5683 << *Cand->DeductionFailure.getFirstArg()
5684 << *Cand->DeductionFailure.getSecondArg();
5685 return;
5686 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00005687
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005688 case Sema::TDK_InvalidExplicitArguments:
5689 assert(ParamD && "no parameter found for invalid explicit arguments");
5690 if (ParamD->getDeclName())
5691 S.Diag(Fn->getLocation(),
5692 diag::note_ovl_candidate_explicit_arg_mismatch_named)
5693 << ParamD->getDeclName();
5694 else {
5695 int index = 0;
5696 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5697 index = TTP->getIndex();
5698 else if (NonTypeTemplateParmDecl *NTTP
5699 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5700 index = NTTP->getIndex();
5701 else
5702 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
5703 S.Diag(Fn->getLocation(),
5704 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
5705 << (index + 1);
5706 }
5707 return;
5708
Douglas Gregor02eb4832010-05-08 18:13:28 +00005709 case Sema::TDK_TooManyArguments:
5710 case Sema::TDK_TooFewArguments:
5711 DiagnoseArityMismatch(S, Cand, NumArgs);
5712 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00005713
5714 case Sema::TDK_InstantiationDepth:
5715 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
5716 return;
5717
5718 case Sema::TDK_SubstitutionFailure: {
5719 std::string ArgString;
5720 if (TemplateArgumentList *Args
5721 = Cand->DeductionFailure.getTemplateArgumentList())
5722 ArgString = S.getTemplateArgumentBindingsText(
5723 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
5724 *Args);
5725 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
5726 << ArgString;
5727 return;
5728 }
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005729
John McCall8b9ed552010-02-01 18:53:26 +00005730 // TODO: diagnose these individually, then kill off
5731 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00005732 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00005733 case Sema::TDK_FailedOverloadResolution:
5734 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
5735 return;
5736 }
5737}
5738
5739/// Generates a 'note' diagnostic for an overload candidate. We've
5740/// already generated a primary error at the call site.
5741///
5742/// It really does need to be a single diagnostic with its caret
5743/// pointed at the candidate declaration. Yes, this creates some
5744/// major challenges of technical writing. Yes, this makes pointing
5745/// out problems with specific arguments quite awkward. It's still
5746/// better than generating twenty screens of text for every failed
5747/// overload.
5748///
5749/// It would be great to be able to express per-candidate problems
5750/// more richly for those diagnostic clients that cared, but we'd
5751/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00005752void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
5753 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00005754 FunctionDecl *Fn = Cand->Function;
5755
John McCall12f97bc2010-01-08 04:41:39 +00005756 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00005757 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00005758 std::string FnDesc;
5759 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00005760
5761 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00005762 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00005763 return;
John McCall12f97bc2010-01-08 04:41:39 +00005764 }
5765
John McCalle1ac8d12010-01-13 00:25:19 +00005766 // We don't really have anything else to say about viable candidates.
5767 if (Cand->Viable) {
5768 S.NoteOverloadCandidate(Fn);
5769 return;
5770 }
John McCall0d1da222010-01-12 00:44:57 +00005771
John McCall6a61b522010-01-13 09:16:55 +00005772 switch (Cand->FailureKind) {
5773 case ovl_fail_too_many_arguments:
5774 case ovl_fail_too_few_arguments:
5775 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00005776
John McCall6a61b522010-01-13 09:16:55 +00005777 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00005778 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5779
John McCallfe796dd2010-01-23 05:17:32 +00005780 case ovl_fail_trivial_conversion:
5781 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005782 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00005783 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005784
John McCall65eb8792010-02-25 01:37:24 +00005785 case ovl_fail_bad_conversion: {
5786 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5787 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00005788 if (Cand->Conversions[I].isBad())
5789 return DiagnoseBadConversion(S, Cand, I);
5790
5791 // FIXME: this currently happens when we're called from SemaInit
5792 // when user-conversion overload fails. Figure out how to handle
5793 // those conditions and diagnose them well.
5794 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005795 }
John McCall65eb8792010-02-25 01:37:24 +00005796 }
John McCalld3224162010-01-08 00:58:21 +00005797}
5798
5799void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5800 // Desugar the type of the surrogate down to a function type,
5801 // retaining as many typedefs as possible while still showing
5802 // the function type (and, therefore, its parameter types).
5803 QualType FnType = Cand->Surrogate->getConversionType();
5804 bool isLValueReference = false;
5805 bool isRValueReference = false;
5806 bool isPointer = false;
5807 if (const LValueReferenceType *FnTypeRef =
5808 FnType->getAs<LValueReferenceType>()) {
5809 FnType = FnTypeRef->getPointeeType();
5810 isLValueReference = true;
5811 } else if (const RValueReferenceType *FnTypeRef =
5812 FnType->getAs<RValueReferenceType>()) {
5813 FnType = FnTypeRef->getPointeeType();
5814 isRValueReference = true;
5815 }
5816 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5817 FnType = FnTypePtr->getPointeeType();
5818 isPointer = true;
5819 }
5820 // Desugar down to a function type.
5821 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5822 // Reconstruct the pointer/reference as appropriate.
5823 if (isPointer) FnType = S.Context.getPointerType(FnType);
5824 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5825 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5826
5827 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5828 << FnType;
5829}
5830
5831void NoteBuiltinOperatorCandidate(Sema &S,
5832 const char *Opc,
5833 SourceLocation OpLoc,
5834 OverloadCandidate *Cand) {
5835 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5836 std::string TypeStr("operator");
5837 TypeStr += Opc;
5838 TypeStr += "(";
5839 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5840 if (Cand->Conversions.size() == 1) {
5841 TypeStr += ")";
5842 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5843 } else {
5844 TypeStr += ", ";
5845 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5846 TypeStr += ")";
5847 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5848 }
5849}
5850
5851void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5852 OverloadCandidate *Cand) {
5853 unsigned NoOperands = Cand->Conversions.size();
5854 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5855 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00005856 if (ICS.isBad()) break; // all meaningless after first invalid
5857 if (!ICS.isAmbiguous()) continue;
5858
5859 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00005860 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00005861 }
5862}
5863
John McCall3712d9e2010-01-15 23:32:50 +00005864SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5865 if (Cand->Function)
5866 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00005867 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00005868 return Cand->Surrogate->getLocation();
5869 return SourceLocation();
5870}
5871
John McCallad2587a2010-01-12 00:48:53 +00005872struct CompareOverloadCandidatesForDisplay {
5873 Sema &S;
5874 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00005875
5876 bool operator()(const OverloadCandidate *L,
5877 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00005878 // Fast-path this check.
5879 if (L == R) return false;
5880
John McCall12f97bc2010-01-08 04:41:39 +00005881 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00005882 if (L->Viable) {
5883 if (!R->Viable) return true;
5884
5885 // TODO: introduce a tri-valued comparison for overload
5886 // candidates. Would be more worthwhile if we had a sort
5887 // that could exploit it.
John McCallbc077cf2010-02-08 23:07:23 +00005888 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5889 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00005890 } else if (R->Viable)
5891 return false;
John McCall12f97bc2010-01-08 04:41:39 +00005892
John McCall3712d9e2010-01-15 23:32:50 +00005893 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00005894
John McCall3712d9e2010-01-15 23:32:50 +00005895 // Criteria by which we can sort non-viable candidates:
5896 if (!L->Viable) {
5897 // 1. Arity mismatches come after other candidates.
5898 if (L->FailureKind == ovl_fail_too_many_arguments ||
5899 L->FailureKind == ovl_fail_too_few_arguments)
5900 return false;
5901 if (R->FailureKind == ovl_fail_too_many_arguments ||
5902 R->FailureKind == ovl_fail_too_few_arguments)
5903 return true;
John McCall12f97bc2010-01-08 04:41:39 +00005904
John McCallfe796dd2010-01-23 05:17:32 +00005905 // 2. Bad conversions come first and are ordered by the number
5906 // of bad conversions and quality of good conversions.
5907 if (L->FailureKind == ovl_fail_bad_conversion) {
5908 if (R->FailureKind != ovl_fail_bad_conversion)
5909 return true;
5910
5911 // If there's any ordering between the defined conversions...
5912 // FIXME: this might not be transitive.
5913 assert(L->Conversions.size() == R->Conversions.size());
5914
5915 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00005916 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5917 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCallfe796dd2010-01-23 05:17:32 +00005918 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5919 R->Conversions[I])) {
5920 case ImplicitConversionSequence::Better:
5921 leftBetter++;
5922 break;
5923
5924 case ImplicitConversionSequence::Worse:
5925 leftBetter--;
5926 break;
5927
5928 case ImplicitConversionSequence::Indistinguishable:
5929 break;
5930 }
5931 }
5932 if (leftBetter > 0) return true;
5933 if (leftBetter < 0) return false;
5934
5935 } else if (R->FailureKind == ovl_fail_bad_conversion)
5936 return false;
5937
John McCall3712d9e2010-01-15 23:32:50 +00005938 // TODO: others?
5939 }
5940
5941 // Sort everything else by location.
5942 SourceLocation LLoc = GetLocationForCandidate(L);
5943 SourceLocation RLoc = GetLocationForCandidate(R);
5944
5945 // Put candidates without locations (e.g. builtins) at the end.
5946 if (LLoc.isInvalid()) return false;
5947 if (RLoc.isInvalid()) return true;
5948
5949 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00005950 }
5951};
5952
John McCallfe796dd2010-01-23 05:17:32 +00005953/// CompleteNonViableCandidate - Normally, overload resolution only
5954/// computes up to the first
5955void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5956 Expr **Args, unsigned NumArgs) {
5957 assert(!Cand->Viable);
5958
5959 // Don't do anything on failures other than bad conversion.
5960 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5961
5962 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00005963 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00005964 unsigned ConvCount = Cand->Conversions.size();
5965 while (true) {
5966 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5967 ConvIdx++;
5968 if (Cand->Conversions[ConvIdx - 1].isBad())
5969 break;
5970 }
5971
5972 if (ConvIdx == ConvCount)
5973 return;
5974
John McCall65eb8792010-02-25 01:37:24 +00005975 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
5976 "remaining conversion is initialized?");
5977
Douglas Gregoradc7a702010-04-16 17:45:54 +00005978 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00005979 // operation somehow.
5980 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00005981
5982 const FunctionProtoType* Proto;
5983 unsigned ArgIdx = ConvIdx;
5984
5985 if (Cand->IsSurrogate) {
5986 QualType ConvType
5987 = Cand->Surrogate->getConversionType().getNonReferenceType();
5988 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5989 ConvType = ConvPtrType->getPointeeType();
5990 Proto = ConvType->getAs<FunctionProtoType>();
5991 ArgIdx--;
5992 } else if (Cand->Function) {
5993 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
5994 if (isa<CXXMethodDecl>(Cand->Function) &&
5995 !isa<CXXConstructorDecl>(Cand->Function))
5996 ArgIdx--;
5997 } else {
5998 // Builtin binary operator with a bad first conversion.
5999 assert(ConvCount <= 3);
6000 for (; ConvIdx != ConvCount; ++ConvIdx)
6001 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006002 = TryCopyInitialization(S, Args[ConvIdx],
6003 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6004 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006005 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00006006 return;
6007 }
6008
6009 // Fill in the rest of the conversions.
6010 unsigned NumArgsInProto = Proto->getNumArgs();
6011 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6012 if (ArgIdx < NumArgsInProto)
6013 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006014 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6015 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006016 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00006017 else
6018 Cand->Conversions[ConvIdx].setEllipsis();
6019 }
6020}
6021
John McCalld3224162010-01-08 00:58:21 +00006022} // end anonymous namespace
6023
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006024/// PrintOverloadCandidates - When overload resolution fails, prints
6025/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00006026/// set.
Mike Stump11289f42009-09-09 15:08:12 +00006027void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006028Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00006029 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00006030 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006031 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00006032 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00006033 // Sort the candidates by viability and position. Sorting directly would
6034 // be prohibitive, so we make a set of pointers and sort those.
6035 llvm::SmallVector<OverloadCandidate*, 32> Cands;
6036 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
6037 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6038 LastCand = CandidateSet.end();
John McCallfe796dd2010-01-23 05:17:32 +00006039 Cand != LastCand; ++Cand) {
6040 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00006041 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00006042 else if (OCD == OCD_AllCandidates) {
6043 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006044 if (Cand->Function || Cand->IsSurrogate)
6045 Cands.push_back(Cand);
6046 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6047 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00006048 }
6049 }
6050
John McCallad2587a2010-01-12 00:48:53 +00006051 std::sort(Cands.begin(), Cands.end(),
6052 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00006053
John McCall0d1da222010-01-12 00:44:57 +00006054 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00006055
John McCall12f97bc2010-01-08 04:41:39 +00006056 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006057 const Diagnostic::OverloadsShown ShowOverloads = Diags.getShowOverloads();
6058 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00006059 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6060 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00006061
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006062 // Set an arbitrary limit on the number of candidate functions we'll spam
6063 // the user with. FIXME: This limit should depend on details of the
6064 // candidate list.
6065 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6066 break;
6067 }
6068 ++CandsShown;
6069
John McCalld3224162010-01-08 00:58:21 +00006070 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00006071 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00006072 else if (Cand->IsSurrogate)
6073 NoteSurrogateCandidate(*this, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006074 else {
6075 assert(Cand->Viable &&
6076 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00006077 // Generally we only see ambiguities including viable builtin
6078 // operators if overload resolution got screwed up by an
6079 // ambiguous user-defined conversion.
6080 //
6081 // FIXME: It's quite possible for different conversions to see
6082 // different ambiguities, though.
6083 if (!ReportedAmbiguousConversions) {
6084 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
6085 ReportedAmbiguousConversions = true;
6086 }
John McCalld3224162010-01-08 00:58:21 +00006087
John McCall0d1da222010-01-12 00:44:57 +00006088 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00006089 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00006090 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006091 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006092
6093 if (I != E)
Jeffrey Yasskin5d474d02010-06-11 06:58:43 +00006094 Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006095}
6096
John McCalla0296f72010-03-19 07:35:19 +00006097static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00006098 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00006099 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006100
John McCalla0296f72010-03-19 07:35:19 +00006101 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006102}
6103
Douglas Gregorcd695e52008-11-10 20:40:00 +00006104/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6105/// an overloaded function (C++ [over.over]), where @p From is an
6106/// expression with overloaded function type and @p ToType is the type
6107/// we're trying to resolve to. For example:
6108///
6109/// @code
6110/// int f(double);
6111/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00006112///
Douglas Gregorcd695e52008-11-10 20:40:00 +00006113/// int (*pfd)(double) = f; // selects f(double)
6114/// @endcode
6115///
6116/// This routine returns the resulting FunctionDecl if it could be
6117/// resolved, and NULL otherwise. When @p Complain is true, this
6118/// routine will emit diagnostics if there is an error.
6119FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006120Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00006121 bool Complain,
6122 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006123 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006124 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006125 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00006126 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006127 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00006128 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006129 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006130 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006131 FunctionType = MemTypePtr->getPointeeType();
6132 IsMember = true;
6133 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006134
Douglas Gregorcd695e52008-11-10 20:40:00 +00006135 // C++ [over.over]p1:
6136 // [...] [Note: any redundant set of parentheses surrounding the
6137 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00006138 // C++ [over.over]p1:
6139 // [...] The overloaded function name can be preceded by the &
6140 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00006141 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
6142 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6143 if (OvlExpr->hasExplicitTemplateArgs()) {
6144 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6145 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregorcd695e52008-11-10 20:40:00 +00006146 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00006147
6148 // We expect a pointer or reference to function, or a function pointer.
6149 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6150 if (!FunctionType->isFunctionType()) {
6151 if (Complain)
6152 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6153 << OvlExpr->getName() << ToType;
6154
6155 return 0;
6156 }
6157
6158 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006159
Douglas Gregorcd695e52008-11-10 20:40:00 +00006160 // Look through all of the overloaded functions, searching for one
6161 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00006162 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006163 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
6164
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006165 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00006166 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6167 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006168 // Look through any using declarations to find the underlying function.
6169 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6170
Douglas Gregorcd695e52008-11-10 20:40:00 +00006171 // C++ [over.over]p3:
6172 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00006173 // targets of type "pointer-to-function" or "reference-to-function."
6174 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006175 // type "pointer-to-member-function."
6176 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00006177
Mike Stump11289f42009-09-09 15:08:12 +00006178 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006179 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00006180 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006181 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00006182 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006183 // static when converting to member pointer.
6184 if (Method->isStatic() == IsMember)
6185 continue;
6186 } else if (IsMember)
6187 continue;
Mike Stump11289f42009-09-09 15:08:12 +00006188
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006189 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006190 // If the name is a function template, template argument deduction is
6191 // done (14.8.2.2), and if the argument deduction succeeds, the
6192 // resulting template argument list is used to generate a single
6193 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006194 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006195 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00006196 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006197 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00006198 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00006199 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00006200 FunctionType, Specialization, Info)) {
6201 // FIXME: make a note of the failed deduction for diagnostics.
6202 (void)Result;
6203 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006204 // FIXME: If the match isn't exact, shouldn't we just drop this as
6205 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00006206 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00006207 == Context.getCanonicalType(Specialization->getType()));
John McCalla0296f72010-03-19 07:35:19 +00006208 Matches.push_back(std::make_pair(I.getPair(),
6209 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor9b146582009-07-08 20:55:45 +00006210 }
John McCalld14a8642009-11-21 08:51:07 +00006211
6212 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00006213 }
Mike Stump11289f42009-09-09 15:08:12 +00006214
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006215 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006216 // Skip non-static functions when converting to pointer, and static
6217 // when converting to member pointer.
6218 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00006219 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00006220
6221 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00006222 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00006223 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006224 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006225 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00006226
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006227 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00006228 QualType ResultTy;
6229 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6230 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6231 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00006232 Matches.push_back(std::make_pair(I.getPair(),
6233 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006234 FoundNonTemplateFunction = true;
6235 }
Mike Stump11289f42009-09-09 15:08:12 +00006236 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006237 }
6238
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006239 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00006240 if (Matches.empty()) {
6241 if (Complain) {
6242 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6243 << OvlExpr->getName() << FunctionType;
6244 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6245 E = OvlExpr->decls_end();
6246 I != E; ++I)
6247 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6248 NoteOverloadCandidate(F);
6249 }
6250
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006251 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00006252 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006253 FunctionDecl *Result = Matches[0].second;
John McCall16df1e52010-03-30 21:47:33 +00006254 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006255 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCall58cc69d2010-01-27 01:50:18 +00006256 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00006257 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006258 return Result;
6259 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006260
6261 // C++ [over.over]p4:
6262 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00006263 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006264 // [...] and any given function template specialization F1 is
6265 // eliminated if the set contains a second function template
6266 // specialization whose function template is more specialized
6267 // than the function template of F1 according to the partial
6268 // ordering rules of 14.5.5.2.
6269
6270 // The algorithm specified above is quadratic. We instead use a
6271 // two-pass algorithm (similar to the one used to identify the
6272 // best viable function in an overload set) that identifies the
6273 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00006274
6275 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6276 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6277 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00006278
6279 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00006280 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006281 TPOC_Other, From->getLocStart(),
6282 PDiag(),
6283 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006284 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00006285 PDiag(diag::note_ovl_candidate)
6286 << (unsigned) oc_function_template);
John McCalla0296f72010-03-19 07:35:19 +00006287 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCall58cc69d2010-01-27 01:50:18 +00006288 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00006289 FoundResult = Matches[Result - MatchesCopy.begin()].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00006290 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00006291 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall4fa0d5f2010-05-06 18:15:07 +00006292 DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc());
6293 }
John McCall58cc69d2010-01-27 01:50:18 +00006294 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006295 }
Mike Stump11289f42009-09-09 15:08:12 +00006296
Douglas Gregorfae1d712009-09-26 03:56:17 +00006297 // [...] any function template specializations in the set are
6298 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00006299 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00006300 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00006301 ++I;
6302 else {
John McCalla0296f72010-03-19 07:35:19 +00006303 Matches[I] = Matches[--N];
6304 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00006305 }
6306 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00006307
Mike Stump11289f42009-09-09 15:08:12 +00006308 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006309 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00006310 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006311 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00006312 FoundResult = Matches[0].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00006313 if (Complain) {
John McCalla0296f72010-03-19 07:35:19 +00006314 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
John McCall4fa0d5f2010-05-06 18:15:07 +00006315 DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc());
6316 }
John McCalla0296f72010-03-19 07:35:19 +00006317 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006318 }
Mike Stump11289f42009-09-09 15:08:12 +00006319
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006320 // FIXME: We should probably return the same thing that BestViableFunction
6321 // returns (even if we issue the diagnostics here).
6322 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006323 << Matches[0].second->getDeclName();
6324 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6325 NoteOverloadCandidate(Matches[I].second);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006326 return 0;
6327}
6328
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006329/// \brief Given an expression that refers to an overloaded function, try to
6330/// resolve that overloaded function expression down to a single function.
6331///
6332/// This routine can only resolve template-ids that refer to a single function
6333/// template, where that template-id refers to a single template whose template
6334/// arguments are either provided by the template-id or have defaults,
6335/// as described in C++0x [temp.arg.explicit]p3.
6336FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6337 // C++ [over.over]p1:
6338 // [...] [Note: any redundant set of parentheses surrounding the
6339 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006340 // C++ [over.over]p1:
6341 // [...] The overloaded function name can be preceded by the &
6342 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00006343
6344 if (From->getType() != Context.OverloadTy)
6345 return 0;
6346
6347 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006348
6349 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00006350 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006351 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00006352
6353 TemplateArgumentListInfo ExplicitTemplateArgs;
6354 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006355
6356 // Look through all of the overloaded functions, searching for one
6357 // whose type matches exactly.
6358 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00006359 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6360 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006361 // C++0x [temp.arg.explicit]p3:
6362 // [...] In contexts where deduction is done and fails, or in contexts
6363 // where deduction is not done, if a template argument list is
6364 // specified and it, along with any default template arguments,
6365 // identifies a single function template specialization, then the
6366 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00006367 FunctionTemplateDecl *FunctionTemplate
6368 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006369
6370 // C++ [over.over]p2:
6371 // If the name is a function template, template argument deduction is
6372 // done (14.8.2.2), and if the argument deduction succeeds, the
6373 // resulting template argument list is used to generate a single
6374 // function template specialization, which is added to the set of
6375 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006376 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006377 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006378 if (TemplateDeductionResult Result
6379 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6380 Specialization, Info)) {
6381 // FIXME: make a note of the failed deduction for diagnostics.
6382 (void)Result;
6383 continue;
6384 }
6385
6386 // Multiple matches; we can't resolve to a single declaration.
6387 if (Matched)
6388 return 0;
6389
6390 Matched = Specialization;
6391 }
6392
6393 return Matched;
6394}
6395
Douglas Gregorcabea402009-09-22 15:41:20 +00006396/// \brief Add a single candidate to the overload set.
6397static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00006398 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00006399 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006400 Expr **Args, unsigned NumArgs,
6401 OverloadCandidateSet &CandidateSet,
6402 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00006403 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00006404 if (isa<UsingShadowDecl>(Callee))
6405 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6406
Douglas Gregorcabea402009-09-22 15:41:20 +00006407 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00006408 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00006409 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006410 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006411 return;
John McCalld14a8642009-11-21 08:51:07 +00006412 }
6413
6414 if (FunctionTemplateDecl *FuncTemplate
6415 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00006416 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6417 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006418 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00006419 return;
6420 }
6421
6422 assert(false && "unhandled case in overloaded call candidate");
6423
6424 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00006425}
6426
6427/// \brief Add the overload candidates named by callee and/or found by argument
6428/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00006429void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00006430 Expr **Args, unsigned NumArgs,
6431 OverloadCandidateSet &CandidateSet,
6432 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00006433
6434#ifndef NDEBUG
6435 // Verify that ArgumentDependentLookup is consistent with the rules
6436 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00006437 //
Douglas Gregorcabea402009-09-22 15:41:20 +00006438 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6439 // and let Y be the lookup set produced by argument dependent
6440 // lookup (defined as follows). If X contains
6441 //
6442 // -- a declaration of a class member, or
6443 //
6444 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00006445 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00006446 //
6447 // -- a declaration that is neither a function or a function
6448 // template
6449 //
6450 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00006451
John McCall57500772009-12-16 12:17:52 +00006452 if (ULE->requiresADL()) {
6453 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6454 E = ULE->decls_end(); I != E; ++I) {
6455 assert(!(*I)->getDeclContext()->isRecord());
6456 assert(isa<UsingShadowDecl>(*I) ||
6457 !(*I)->getDeclContext()->isFunctionOrMethod());
6458 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00006459 }
6460 }
6461#endif
6462
John McCall57500772009-12-16 12:17:52 +00006463 // It would be nice to avoid this copy.
6464 TemplateArgumentListInfo TABuffer;
6465 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6466 if (ULE->hasExplicitTemplateArgs()) {
6467 ULE->copyTemplateArgumentsInto(TABuffer);
6468 ExplicitTemplateArgs = &TABuffer;
6469 }
6470
6471 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6472 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00006473 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006474 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00006475 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00006476
John McCall57500772009-12-16 12:17:52 +00006477 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00006478 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6479 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006480 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006481 CandidateSet,
6482 PartialOverloading);
6483}
John McCalld681c392009-12-16 08:11:27 +00006484
6485/// Attempts to recover from a call where no functions were found.
6486///
6487/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00006488static Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006489BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00006490 UnresolvedLookupExpr *ULE,
6491 SourceLocation LParenLoc,
6492 Expr **Args, unsigned NumArgs,
6493 SourceLocation *CommaLocs,
6494 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00006495
6496 CXXScopeSpec SS;
6497 if (ULE->getQualifier()) {
6498 SS.setScopeRep(ULE->getQualifier());
6499 SS.setRange(ULE->getQualifierRange());
6500 }
6501
John McCall57500772009-12-16 12:17:52 +00006502 TemplateArgumentListInfo TABuffer;
6503 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6504 if (ULE->hasExplicitTemplateArgs()) {
6505 ULE->copyTemplateArgumentsInto(TABuffer);
6506 ExplicitTemplateArgs = &TABuffer;
6507 }
6508
John McCalld681c392009-12-16 08:11:27 +00006509 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6510 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00006511 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
Douglas Gregorb412e172010-07-25 18:17:45 +00006512 return SemaRef.ExprError();
John McCalld681c392009-12-16 08:11:27 +00006513
John McCall57500772009-12-16 12:17:52 +00006514 assert(!R.empty() && "lookup results empty despite recovery");
6515
6516 // Build an implicit member call if appropriate. Just drop the
6517 // casts and such from the call, we don't really care.
6518 Sema::OwningExprResult NewFn = SemaRef.ExprError();
6519 if ((*R.begin())->isCXXClassMember())
6520 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6521 else if (ExplicitTemplateArgs)
6522 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6523 else
6524 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6525
6526 if (NewFn.isInvalid())
Douglas Gregorb412e172010-07-25 18:17:45 +00006527 return SemaRef.ExprError();
John McCall57500772009-12-16 12:17:52 +00006528
6529 // This shouldn't cause an infinite loop because we're giving it
6530 // an expression with non-empty lookup results, which should never
6531 // end up here.
6532 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
6533 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
6534 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006535}
Douglas Gregor4038cf42010-06-08 17:35:15 +00006536
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006537/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00006538/// (which eventually refers to the declaration Func) and the call
6539/// arguments Args/NumArgs, attempt to resolve the function call down
6540/// to a specific function. If overload resolution succeeds, returns
6541/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00006542/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006543/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00006544Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006545Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00006546 SourceLocation LParenLoc,
6547 Expr **Args, unsigned NumArgs,
6548 SourceLocation *CommaLocs,
6549 SourceLocation RParenLoc) {
6550#ifndef NDEBUG
6551 if (ULE->requiresADL()) {
6552 // To do ADL, we must have found an unqualified name.
6553 assert(!ULE->getQualifier() && "qualified name with ADL");
6554
6555 // We don't perform ADL for implicit declarations of builtins.
6556 // Verify that this was correctly set up.
6557 FunctionDecl *F;
6558 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6559 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6560 F->getBuiltinID() && F->isImplicit())
6561 assert(0 && "performing ADL for builtin");
6562
6563 // We don't perform ADL in C.
6564 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6565 }
6566#endif
6567
John McCallbc077cf2010-02-08 23:07:23 +00006568 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00006569
John McCall57500772009-12-16 12:17:52 +00006570 // Add the functions denoted by the callee to the set of candidate
6571 // functions, including those from argument-dependent lookup.
6572 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00006573
6574 // If we found nothing, try to recover.
6575 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6576 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00006577 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006578 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall57500772009-12-16 12:17:52 +00006579 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006580
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006581 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006582 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00006583 case OR_Success: {
6584 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00006585 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006586 DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00006587 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00006588 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6589 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006590
6591 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00006592 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006593 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00006594 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006595 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006596 break;
6597
6598 case OR_Ambiguous:
6599 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00006600 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006601 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006602 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006603
6604 case OR_Deleted:
6605 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6606 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00006607 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00006608 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006609 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006610 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006611 }
6612
Douglas Gregorb412e172010-07-25 18:17:45 +00006613 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00006614 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006615}
6616
John McCall4c4c1df2010-01-26 03:27:55 +00006617static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00006618 return Functions.size() > 1 ||
6619 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6620}
6621
Douglas Gregor084d8552009-03-13 23:49:33 +00006622/// \brief Create a unary operation that may resolve to an overloaded
6623/// operator.
6624///
6625/// \param OpLoc The location of the operator itself (e.g., '*').
6626///
6627/// \param OpcIn The UnaryOperator::Opcode that describes this
6628/// operator.
6629///
6630/// \param Functions The set of non-member functions that will be
6631/// considered by overload resolution. The caller needs to build this
6632/// set based on the context using, e.g.,
6633/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6634/// set should not contain any member functions; those will be added
6635/// by CreateOverloadedUnaryOp().
6636///
6637/// \param input The input argument.
John McCall4c4c1df2010-01-26 03:27:55 +00006638Sema::OwningExprResult
6639Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6640 const UnresolvedSetImpl &Fns,
6641 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006642 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
6643 Expr *Input = (Expr *)input.get();
6644
6645 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6646 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6647 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006648 // TODO: provide better source location info.
6649 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006650
6651 Expr *Args[2] = { Input, 0 };
6652 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00006653
Douglas Gregor084d8552009-03-13 23:49:33 +00006654 // For post-increment and post-decrement, add the implicit '0' as
6655 // the second argument, so that we know this is a post-increment or
6656 // post-decrement.
6657 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
6658 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00006659 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00006660 SourceLocation());
6661 NumArgs = 2;
6662 }
6663
6664 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00006665 if (Fns.empty())
6666 return Owned(new (Context) UnaryOperator(input.takeAs<Expr>(),
6667 Opc,
6668 Context.DependentTy,
6669 OpLoc));
6670
John McCall58cc69d2010-01-27 01:50:18 +00006671 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006672 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006673 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006674 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006675 /*ADL*/ true, IsOverloaded(Fns),
6676 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00006677 input.release();
6678 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6679 &Args[0], NumArgs,
6680 Context.DependentTy,
6681 OpLoc));
6682 }
6683
6684 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006685 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006686
6687 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006688 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00006689
6690 // Add operator candidates that are member functions.
6691 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6692
John McCall4c4c1df2010-01-26 03:27:55 +00006693 // Add candidates from ADL.
6694 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00006695 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00006696 /*ExplicitTemplateArgs*/ 0,
6697 CandidateSet);
6698
Douglas Gregor084d8552009-03-13 23:49:33 +00006699 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006700 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00006701
6702 // Perform overload resolution.
6703 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006704 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006705 case OR_Success: {
6706 // We found a built-in operator or an overloaded operator.
6707 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00006708
Douglas Gregor084d8552009-03-13 23:49:33 +00006709 if (FnDecl) {
6710 // We matched an overloaded operator. Build a call to that
6711 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00006712
Douglas Gregor084d8552009-03-13 23:49:33 +00006713 // Convert the arguments.
6714 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00006715 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006716
John McCall16df1e52010-03-30 21:47:33 +00006717 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6718 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00006719 return ExprError();
6720 } else {
6721 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00006722 OwningExprResult InputInit
6723 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006724 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00006725 SourceLocation(),
6726 move(input));
6727 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00006728 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006729
Douglas Gregore6600372009-12-23 17:40:29 +00006730 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006731 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00006732 }
6733
John McCall4fa0d5f2010-05-06 18:15:07 +00006734 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6735
Douglas Gregor084d8552009-03-13 23:49:33 +00006736 // Determine the result type
Douglas Gregor603d81b2010-07-13 08:18:22 +00006737 QualType ResultTy = FnDecl->getCallResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006738
Douglas Gregor084d8552009-03-13 23:49:33 +00006739 // Build the actual expression node.
6740 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6741 SourceLocation());
6742 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00006743
Douglas Gregor084d8552009-03-13 23:49:33 +00006744 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00006745 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006746 ExprOwningPtr<CallExpr> TheCall(this,
6747 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00006748 Args, NumArgs, ResultTy, OpLoc));
John McCall4fa0d5f2010-05-06 18:15:07 +00006749
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006750 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6751 FnDecl))
6752 return ExprError();
6753
6754 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00006755 } else {
6756 // We matched a built-in operator. Convert the arguments, then
6757 // break out so that we will build the appropriate built-in
6758 // operator node.
6759 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006760 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00006761 return ExprError();
6762
6763 break;
6764 }
6765 }
6766
6767 case OR_No_Viable_Function:
6768 // No viable function; fall through to handling this as a
6769 // built-in operator, which will produce an error message for us.
6770 break;
6771
6772 case OR_Ambiguous:
6773 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6774 << UnaryOperator::getOpcodeStr(Opc)
6775 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006776 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006777 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006778 return ExprError();
6779
6780 case OR_Deleted:
6781 Diag(OpLoc, diag::err_ovl_deleted_oper)
6782 << Best->Function->isDeleted()
6783 << UnaryOperator::getOpcodeStr(Opc)
6784 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006785 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00006786 return ExprError();
6787 }
6788
6789 // Either we found no viable overloaded operator or we matched a
6790 // built-in operator. In either case, fall through to trying to
6791 // build a built-in operation.
6792 input.release();
6793 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
6794}
6795
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006796/// \brief Create a binary operation that may resolve to an overloaded
6797/// operator.
6798///
6799/// \param OpLoc The location of the operator itself (e.g., '+').
6800///
6801/// \param OpcIn The BinaryOperator::Opcode that describes this
6802/// operator.
6803///
6804/// \param Functions The set of non-member functions that will be
6805/// considered by overload resolution. The caller needs to build this
6806/// set based on the context using, e.g.,
6807/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6808/// set should not contain any member functions; those will be added
6809/// by CreateOverloadedBinOp().
6810///
6811/// \param LHS Left-hand argument.
6812/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00006813Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006814Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006815 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00006816 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006817 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006818 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00006819 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006820
6821 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6822 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6823 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6824
6825 // If either side is type-dependent, create an appropriate dependent
6826 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00006827 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00006828 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006829 // If there are no functions to store, just build a dependent
6830 // BinaryOperator or CompoundAssignment.
6831 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
6832 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6833 Context.DependentTy, OpLoc));
6834
6835 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6836 Context.DependentTy,
6837 Context.DependentTy,
6838 Context.DependentTy,
6839 OpLoc));
6840 }
John McCall4c4c1df2010-01-26 03:27:55 +00006841
6842 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00006843 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006844 // TODO: provide better source location info in DNLoc component.
6845 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00006846 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006847 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006848 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006849 /*ADL*/ true, IsOverloaded(Fns),
6850 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006851 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00006852 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006853 Context.DependentTy,
6854 OpLoc));
6855 }
6856
6857 // If this is the .* operator, which is not overloadable, just
6858 // create a built-in binary operator.
6859 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00006860 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006861
Sebastian Redl6a96bf72009-11-18 23:10:33 +00006862 // If this is the assignment operator, we only perform overload resolution
6863 // if the left-hand side is a class or enumeration type. This is actually
6864 // a hack. The standard requires that we do overload resolution between the
6865 // various built-in candidates, but as DR507 points out, this can lead to
6866 // problems. So we do it this way, which pretty much follows what GCC does.
6867 // Note that we go the traditional code path for compound assignment forms.
6868 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00006869 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006870
Douglas Gregor084d8552009-03-13 23:49:33 +00006871 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006872 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006873
6874 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006875 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006876
6877 // Add operator candidates that are member functions.
6878 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6879
John McCall4c4c1df2010-01-26 03:27:55 +00006880 // Add candidates from ADL.
6881 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6882 Args, 2,
6883 /*ExplicitTemplateArgs*/ 0,
6884 CandidateSet);
6885
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006886 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006887 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006888
6889 // Perform overload resolution.
6890 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006891 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00006892 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006893 // We found a built-in operator or an overloaded operator.
6894 FunctionDecl *FnDecl = Best->Function;
6895
6896 if (FnDecl) {
6897 // We matched an overloaded operator. Build a call to that
6898 // operator.
6899
6900 // Convert the arguments.
6901 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00006902 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00006903 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006904
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006905 OwningExprResult Arg1
6906 = PerformCopyInitialization(
6907 InitializedEntity::InitializeParameter(
6908 FnDecl->getParamDecl(0)),
6909 SourceLocation(),
6910 Owned(Args[1]));
6911 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006912 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006913
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006914 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006915 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006916 return ExprError();
6917
6918 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006919 } else {
6920 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006921 OwningExprResult Arg0
6922 = PerformCopyInitialization(
6923 InitializedEntity::InitializeParameter(
6924 FnDecl->getParamDecl(0)),
6925 SourceLocation(),
6926 Owned(Args[0]));
6927 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006928 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006929
6930 OwningExprResult Arg1
6931 = PerformCopyInitialization(
6932 InitializedEntity::InitializeParameter(
6933 FnDecl->getParamDecl(1)),
6934 SourceLocation(),
6935 Owned(Args[1]));
6936 if (Arg1.isInvalid())
6937 return ExprError();
6938 Args[0] = LHS = Arg0.takeAs<Expr>();
6939 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006940 }
6941
John McCall4fa0d5f2010-05-06 18:15:07 +00006942 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6943
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006944 // Determine the result type
6945 QualType ResultTy
Douglas Gregor603d81b2010-07-13 08:18:22 +00006946 = FnDecl->getType()->getAs<FunctionType>()
6947 ->getCallResultType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006948
6949 // Build the actual expression node.
6950 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00006951 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006952 UsualUnaryConversions(FnExpr);
6953
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006954 ExprOwningPtr<CXXOperatorCallExpr>
6955 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6956 Args, 2, ResultTy,
6957 OpLoc));
6958
6959 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6960 FnDecl))
6961 return ExprError();
6962
6963 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006964 } else {
6965 // We matched a built-in operator. Convert the arguments, then
6966 // break out so that we will build the appropriate built-in
6967 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00006968 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006969 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00006970 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006971 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006972 return ExprError();
6973
6974 break;
6975 }
6976 }
6977
Douglas Gregor66950a32009-09-30 21:46:01 +00006978 case OR_No_Viable_Function: {
6979 // C++ [over.match.oper]p9:
6980 // If the operator is the operator , [...] and there are no
6981 // viable functions, then the operator is assumed to be the
6982 // built-in operator and interpreted according to clause 5.
6983 if (Opc == BinaryOperator::Comma)
6984 break;
6985
Sebastian Redl027de2a2009-05-21 11:50:50 +00006986 // For class as left operand for assignment or compound assigment operator
6987 // do not fall through to handling in built-in, but report that no overloaded
6988 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00006989 OwningExprResult Result = ExprError();
6990 if (Args[0]->getType()->isRecordType() &&
6991 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00006992 Diag(OpLoc, diag::err_ovl_no_viable_oper)
6993 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006994 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00006995 } else {
6996 // No viable function; try to create a built-in operation, which will
6997 // produce an error. Then, show the non-viable candidates.
6998 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00006999 }
Douglas Gregor66950a32009-09-30 21:46:01 +00007000 assert(Result.isInvalid() &&
7001 "C++ binary operator overloading is missing candidates!");
7002 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00007003 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00007004 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00007005 return move(Result);
7006 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007007
7008 case OR_Ambiguous:
7009 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
7010 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007011 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007012 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00007013 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007014 return ExprError();
7015
7016 case OR_Deleted:
7017 Diag(OpLoc, diag::err_ovl_deleted_oper)
7018 << Best->Function->isDeleted()
7019 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007020 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007021 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007022 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00007023 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007024
Douglas Gregor66950a32009-09-30 21:46:01 +00007025 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00007026 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007027}
7028
Sebastian Redladba46e2009-10-29 20:17:01 +00007029Action::OwningExprResult
7030Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7031 SourceLocation RLoc,
7032 ExprArg Base, ExprArg Idx) {
7033 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
7034 static_cast<Expr*>(Idx.get()) };
7035 DeclarationName OpName =
7036 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7037
7038 // If either side is type-dependent, create an appropriate dependent
7039 // expression.
7040 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7041
John McCall58cc69d2010-01-27 01:50:18 +00007042 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007043 // CHECKME: no 'operator' keyword?
7044 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7045 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00007046 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00007047 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007048 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007049 /*ADL*/ true, /*Overloaded*/ false,
7050 UnresolvedSetIterator(),
7051 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00007052 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00007053
7054 Base.release();
7055 Idx.release();
7056 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7057 Args, 2,
7058 Context.DependentTy,
7059 RLoc));
7060 }
7061
7062 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007063 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007064
7065 // Subscript can only be overloaded as a member function.
7066
7067 // Add operator candidates that are member functions.
7068 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7069
7070 // Add builtin operator candidates.
7071 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7072
7073 // Perform overload resolution.
7074 OverloadCandidateSet::iterator Best;
7075 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
7076 case OR_Success: {
7077 // We found a built-in operator or an overloaded operator.
7078 FunctionDecl *FnDecl = Best->Function;
7079
7080 if (FnDecl) {
7081 // We matched an overloaded operator. Build a call to that
7082 // operator.
7083
John McCalla0296f72010-03-19 07:35:19 +00007084 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007085 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00007086
Sebastian Redladba46e2009-10-29 20:17:01 +00007087 // Convert the arguments.
7088 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007089 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007090 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00007091 return ExprError();
7092
Anders Carlssona68e51e2010-01-29 18:37:50 +00007093 // Convert the arguments.
7094 OwningExprResult InputInit
7095 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7096 FnDecl->getParamDecl(0)),
7097 SourceLocation(),
7098 Owned(Args[1]));
7099 if (InputInit.isInvalid())
7100 return ExprError();
7101
7102 Args[1] = InputInit.takeAs<Expr>();
7103
Sebastian Redladba46e2009-10-29 20:17:01 +00007104 // Determine the result type
7105 QualType ResultTy
Douglas Gregor603d81b2010-07-13 08:18:22 +00007106 = FnDecl->getType()->getAs<FunctionType>()
7107 ->getCallResultType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00007108
7109 // Build the actual expression node.
7110 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7111 LLoc);
7112 UsualUnaryConversions(FnExpr);
7113
7114 Base.release();
7115 Idx.release();
7116 ExprOwningPtr<CXXOperatorCallExpr>
7117 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7118 FnExpr, Args, 2,
7119 ResultTy, RLoc));
7120
7121 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
7122 FnDecl))
7123 return ExprError();
7124
7125 return MaybeBindToTemporary(TheCall.release());
7126 } else {
7127 // We matched a built-in operator. Convert the arguments, then
7128 // break out so that we will build the appropriate built-in
7129 // operator node.
7130 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007131 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00007132 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007133 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00007134 return ExprError();
7135
7136 break;
7137 }
7138 }
7139
7140 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00007141 if (CandidateSet.empty())
7142 Diag(LLoc, diag::err_ovl_no_oper)
7143 << Args[0]->getType() << /*subscript*/ 0
7144 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7145 else
7146 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7147 << Args[0]->getType()
7148 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007149 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00007150 "[]", LLoc);
7151 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00007152 }
7153
7154 case OR_Ambiguous:
7155 Diag(LLoc, diag::err_ovl_ambiguous_oper)
7156 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007157 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00007158 "[]", LLoc);
7159 return ExprError();
7160
7161 case OR_Deleted:
7162 Diag(LLoc, diag::err_ovl_deleted_oper)
7163 << Best->Function->isDeleted() << "[]"
7164 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007165 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00007166 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007167 return ExprError();
7168 }
7169
7170 // We matched a built-in operator; build it.
7171 Base.release();
7172 Idx.release();
7173 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
7174 Owned(Args[1]), RLoc);
7175}
7176
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007177/// BuildCallToMemberFunction - Build a call to a member
7178/// function. MemExpr is the expression that refers to the member
7179/// function (and includes the object parameter), Args/NumArgs are the
7180/// arguments to the function call (not including the object
7181/// parameter). The caller needs to validate that the member
7182/// expression refers to a member function or an overloaded member
7183/// function.
John McCall2d74de92009-12-01 22:10:20 +00007184Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00007185Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7186 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007187 unsigned NumArgs, SourceLocation *CommaLocs,
7188 SourceLocation RParenLoc) {
7189 // Dig out the member expression. This holds both the object
7190 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00007191 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7192
John McCall10eae182009-11-30 22:42:35 +00007193 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007194 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00007195 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007196 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00007197 if (isa<MemberExpr>(NakedMemExpr)) {
7198 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00007199 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00007200 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007201 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00007202 } else {
7203 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007204 Qualifier = UnresExpr->getQualifier();
7205
John McCall6e9f8f62009-12-03 04:06:58 +00007206 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00007207
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007208 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00007209 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00007210
John McCall2d74de92009-12-01 22:10:20 +00007211 // FIXME: avoid copy.
7212 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7213 if (UnresExpr->hasExplicitTemplateArgs()) {
7214 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7215 TemplateArgs = &TemplateArgsBuffer;
7216 }
7217
John McCall10eae182009-11-30 22:42:35 +00007218 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7219 E = UnresExpr->decls_end(); I != E; ++I) {
7220
John McCall6e9f8f62009-12-03 04:06:58 +00007221 NamedDecl *Func = *I;
7222 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7223 if (isa<UsingShadowDecl>(Func))
7224 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7225
John McCall10eae182009-11-30 22:42:35 +00007226 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00007227 // If explicit template arguments were provided, we can't call a
7228 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00007229 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00007230 continue;
7231
John McCalla0296f72010-03-19 07:35:19 +00007232 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00007233 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007234 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007235 } else {
John McCall10eae182009-11-30 22:42:35 +00007236 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00007237 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007238 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007239 CandidateSet,
7240 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007241 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007242 }
Mike Stump11289f42009-09-09 15:08:12 +00007243
John McCall10eae182009-11-30 22:42:35 +00007244 DeclarationName DeclName = UnresExpr->getMemberName();
7245
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007246 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00007247 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007248 case OR_Success:
7249 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007250 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00007251 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007252 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007253 break;
7254
7255 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00007256 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007257 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007258 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007259 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007260 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007261 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007262
7263 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00007264 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007265 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007266 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007267 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007268 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007269
7270 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00007271 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00007272 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00007273 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007274 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007275 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007276 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007277 }
7278
John McCall16df1e52010-03-30 21:47:33 +00007279 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00007280
John McCall2d74de92009-12-01 22:10:20 +00007281 // If overload resolution picked a static member, build a
7282 // non-member call based on that function.
7283 if (Method->isStatic()) {
7284 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7285 Args, NumArgs, RParenLoc);
7286 }
7287
John McCall10eae182009-11-30 22:42:35 +00007288 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007289 }
7290
7291 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00007292 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00007293 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00007294 NumArgs,
Douglas Gregor603d81b2010-07-13 08:18:22 +00007295 Method->getCallResultType(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007296 RParenLoc));
7297
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007298 // Check for a valid return type.
7299 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
7300 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00007301 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007302
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007303 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00007304 // We only need to do this if there was actually an overload; otherwise
7305 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00007306 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00007307 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00007308 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7309 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00007310 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007311 MemExpr->setBase(ObjectArg);
7312
7313 // Convert the rest of the arguments
Douglas Gregorc8be9522010-05-04 18:18:31 +00007314 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00007315 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007316 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00007317 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007318
Anders Carlssonbc4c1072009-08-16 01:56:34 +00007319 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00007320 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00007321
John McCall2d74de92009-12-01 22:10:20 +00007322 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007323}
7324
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007325/// BuildCallToObjectOfClassType - Build a call to an object of class
7326/// type (C++ [over.call.object]), which can end up invoking an
7327/// overloaded function call operator (@c operator()) or performing a
7328/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00007329Sema::ExprResult
7330Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00007331 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007332 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00007333 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007334 SourceLocation RParenLoc) {
7335 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007336 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00007337
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007338 // C++ [over.call.object]p1:
7339 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00007340 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007341 // candidate functions includes at least the function call
7342 // operators of T. The function call operators of T are obtained by
7343 // ordinary lookup of the name operator() in the context of
7344 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00007345 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00007346 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007347
7348 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007349 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007350 << Object->getSourceRange()))
7351 return true;
7352
John McCall27b18f82009-11-17 02:14:36 +00007353 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7354 LookupQualifiedName(R, Record->getDecl());
7355 R.suppressDiagnostics();
7356
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007357 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00007358 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007359 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00007360 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00007361 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00007362 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007363
Douglas Gregorab7897a2008-11-19 22:57:39 +00007364 // C++ [over.call.object]p2:
7365 // In addition, for each conversion function declared in T of the
7366 // form
7367 //
7368 // operator conversion-type-id () cv-qualifier;
7369 //
7370 // where cv-qualifier is the same cv-qualification as, or a
7371 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00007372 // denotes the type "pointer to function of (P1,...,Pn) returning
7373 // R", or the type "reference to pointer to function of
7374 // (P1,...,Pn) returning R", or the type "reference to function
7375 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00007376 // is also considered as a candidate function. Similarly,
7377 // surrogate call functions are added to the set of candidate
7378 // functions for each conversion function declared in an
7379 // accessible base class provided the function is not hidden
7380 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00007381 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00007382 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00007383 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00007384 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00007385 NamedDecl *D = *I;
7386 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7387 if (isa<UsingShadowDecl>(D))
7388 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7389
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007390 // Skip over templated conversion functions; they aren't
7391 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00007392 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007393 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007394
John McCall6e9f8f62009-12-03 04:06:58 +00007395 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00007396
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007397 // Strip the reference type (if any) and then the pointer type (if
7398 // any) to get down to what might be a function type.
7399 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7400 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7401 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007402
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007403 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00007404 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00007405 Object->getType(), Args, NumArgs,
7406 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007407 }
Mike Stump11289f42009-09-09 15:08:12 +00007408
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007409 // Perform overload resolution.
7410 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007411 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007412 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00007413 // Overload resolution succeeded; we'll build the appropriate call
7414 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007415 break;
7416
7417 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00007418 if (CandidateSet.empty())
7419 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7420 << Object->getType() << /*call*/ 1
7421 << Object->getSourceRange();
7422 else
7423 Diag(Object->getSourceRange().getBegin(),
7424 diag::err_ovl_no_viable_object_call)
7425 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007426 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007427 break;
7428
7429 case OR_Ambiguous:
7430 Diag(Object->getSourceRange().getBegin(),
7431 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007432 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007433 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007434 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007435
7436 case OR_Deleted:
7437 Diag(Object->getSourceRange().getBegin(),
7438 diag::err_ovl_deleted_object_call)
7439 << Best->Function->isDeleted()
7440 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007441 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007442 break;
Mike Stump11289f42009-09-09 15:08:12 +00007443 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007444
Douglas Gregorb412e172010-07-25 18:17:45 +00007445 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007446 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007447
Douglas Gregorab7897a2008-11-19 22:57:39 +00007448 if (Best->Function == 0) {
7449 // Since there is no function declaration, this is one of the
7450 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00007451 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00007452 = cast<CXXConversionDecl>(
7453 Best->Conversions[0].UserDefined.ConversionFunction);
7454
John McCalla0296f72010-03-19 07:35:19 +00007455 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007456 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007457
Douglas Gregorab7897a2008-11-19 22:57:39 +00007458 // We selected one of the surrogate functions that converts the
7459 // object parameter to a function pointer. Perform the conversion
7460 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00007461
7462 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007463 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00007464 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7465 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007466
Fariborz Jahanian774cf792009-09-28 18:35:46 +00007467 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007468 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
Douglas Gregore5e775b2010-04-13 15:50:39 +00007469 CommaLocs, RParenLoc).result();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007470 }
7471
John McCalla0296f72010-03-19 07:35:19 +00007472 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007473 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007474
Douglas Gregorab7897a2008-11-19 22:57:39 +00007475 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7476 // that calls this method, using Object for the implicit object
7477 // parameter and passing along the remaining arguments.
7478 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00007479 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007480
7481 unsigned NumArgsInProto = Proto->getNumArgs();
7482 unsigned NumArgsToCheck = NumArgs;
7483
7484 // Build the full argument list for the method call (the
7485 // implicit object parameter is placed at the beginning of the
7486 // list).
7487 Expr **MethodArgs;
7488 if (NumArgs < NumArgsInProto) {
7489 NumArgsToCheck = NumArgsInProto;
7490 MethodArgs = new Expr*[NumArgsInProto + 1];
7491 } else {
7492 MethodArgs = new Expr*[NumArgs + 1];
7493 }
7494 MethodArgs[0] = Object;
7495 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7496 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00007497
7498 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00007499 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007500 UsualUnaryConversions(NewFn);
7501
7502 // Once we've built TheCall, all of the expressions are properly
7503 // owned.
Douglas Gregor603d81b2010-07-13 08:18:22 +00007504 QualType ResultTy = Method->getCallResultType();
Mike Stump11289f42009-09-09 15:08:12 +00007505 ExprOwningPtr<CXXOperatorCallExpr>
7506 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007507 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00007508 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007509 delete [] MethodArgs;
7510
Anders Carlsson3d5829c2009-10-13 21:49:31 +00007511 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
7512 Method))
7513 return true;
7514
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007515 // We may have default arguments. If so, we need to allocate more
7516 // slots in the call for them.
7517 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00007518 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007519 else if (NumArgs > NumArgsInProto)
7520 NumArgsToCheck = NumArgsInProto;
7521
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007522 bool IsError = false;
7523
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007524 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007525 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007526 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007527 TheCall->setArg(0, Object);
7528
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007529
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007530 // Check the argument types.
7531 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007532 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007533 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007534 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00007535
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007536 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007537
7538 OwningExprResult InputInit
7539 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7540 Method->getParamDecl(i)),
7541 SourceLocation(), Owned(Arg));
7542
7543 IsError |= InputInit.isInvalid();
7544 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007545 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00007546 OwningExprResult DefArg
7547 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7548 if (DefArg.isInvalid()) {
7549 IsError = true;
7550 break;
7551 }
7552
7553 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007554 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007555
7556 TheCall->setArg(i + 1, Arg);
7557 }
7558
7559 // If this is a variadic call, handle args passed through "...".
7560 if (Proto->isVariadic()) {
7561 // Promote the arguments (C99 6.5.2.2p7).
7562 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7563 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00007564 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007565 TheCall->setArg(i + 1, Arg);
7566 }
7567 }
7568
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007569 if (IsError) return true;
7570
Anders Carlssonbc4c1072009-08-16 01:56:34 +00007571 if (CheckFunctionCall(Method, TheCall.get()))
7572 return true;
7573
Douglas Gregore5e775b2010-04-13 15:50:39 +00007574 return MaybeBindToTemporary(TheCall.release()).result();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007575}
7576
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007577/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00007578/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007579/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00007580Sema::OwningExprResult
7581Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
7582 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007583 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00007584
John McCallbc077cf2010-02-08 23:07:23 +00007585 SourceLocation Loc = Base->getExprLoc();
7586
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007587 // C++ [over.ref]p1:
7588 //
7589 // [...] An expression x->m is interpreted as (x.operator->())->m
7590 // for a class object x of type T if T::operator->() exists and if
7591 // the operator is selected as the best match function by the
7592 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007593 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00007594 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007595 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00007596
John McCallbc077cf2010-02-08 23:07:23 +00007597 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00007598 PDiag(diag::err_typecheck_incomplete_tag)
7599 << Base->getSourceRange()))
7600 return ExprError();
7601
John McCall27b18f82009-11-17 02:14:36 +00007602 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7603 LookupQualifiedName(R, BaseRecord->getDecl());
7604 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00007605
7606 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00007607 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007608 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007609 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00007610 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007611
7612 // Perform overload resolution.
7613 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007614 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007615 case OR_Success:
7616 // Overload resolution succeeded; we'll build the call below.
7617 break;
7618
7619 case OR_No_Viable_Function:
7620 if (CandidateSet.empty())
7621 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00007622 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007623 else
7624 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00007625 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007626 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007627 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007628
7629 case OR_Ambiguous:
7630 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00007631 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007632 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007633 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007634
7635 case OR_Deleted:
7636 Diag(OpLoc, diag::err_ovl_deleted_oper)
7637 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00007638 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007639 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007640 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007641 }
7642
John McCalla0296f72010-03-19 07:35:19 +00007643 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007644 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00007645
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007646 // Convert the object parameter.
7647 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007648 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7649 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00007650 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00007651
7652 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00007653 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007654
7655 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00007656 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7657 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007658 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007659
Douglas Gregor603d81b2010-07-13 08:18:22 +00007660 QualType ResultTy = Method->getCallResultType();
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007661 ExprOwningPtr<CXXOperatorCallExpr>
7662 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7663 &Base, 1, ResultTy, OpLoc));
7664
7665 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
7666 Method))
7667 return ExprError();
7668 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007669}
7670
Douglas Gregorcd695e52008-11-10 20:40:00 +00007671/// FixOverloadedFunctionReference - E is an expression that refers to
7672/// a C++ overloaded function (possibly with some parentheses and
7673/// perhaps a '&' around it). We have resolved the overloaded function
7674/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007675/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00007676Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00007677 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00007678 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007679 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7680 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007681 if (SubExpr == PE->getSubExpr())
7682 return PE->Retain();
7683
7684 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7685 }
7686
7687 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007688 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7689 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00007690 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00007691 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00007692 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00007693 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00007694 if (SubExpr == ICE->getSubExpr())
7695 return ICE->Retain();
7696
John McCallcf142162010-08-07 06:22:56 +00007697 return ImplicitCastExpr::Create(Context, ICE->getType(),
7698 ICE->getCastKind(),
7699 SubExpr, 0,
7700 ICE->getCategory());
Douglas Gregor51c538b2009-11-20 19:42:02 +00007701 }
7702
7703 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00007704 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00007705 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007706 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7707 if (Method->isStatic()) {
7708 // Do nothing: static member functions aren't any different
7709 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00007710 } else {
John McCalle66edc12009-11-24 19:00:30 +00007711 // Fix the sub expression, which really has to be an
7712 // UnresolvedLookupExpr holding an overloaded member function
7713 // or template.
John McCall16df1e52010-03-30 21:47:33 +00007714 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7715 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00007716 if (SubExpr == UnOp->getSubExpr())
7717 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00007718
John McCalld14a8642009-11-21 08:51:07 +00007719 assert(isa<DeclRefExpr>(SubExpr)
7720 && "fixed to something other than a decl ref");
7721 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7722 && "fixed to a member ref with no nested name qualifier");
7723
7724 // We have taken the address of a pointer to member
7725 // function. Perform the computation here so that we get the
7726 // appropriate pointer to member type.
7727 QualType ClassType
7728 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7729 QualType MemPtrType
7730 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7731
7732 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7733 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007734 }
7735 }
John McCall16df1e52010-03-30 21:47:33 +00007736 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7737 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007738 if (SubExpr == UnOp->getSubExpr())
7739 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007740
Douglas Gregor51c538b2009-11-20 19:42:02 +00007741 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7742 Context.getPointerType(SubExpr->getType()),
7743 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00007744 }
John McCalld14a8642009-11-21 08:51:07 +00007745
7746 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00007747 // FIXME: avoid copy.
7748 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00007749 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00007750 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7751 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00007752 }
7753
John McCalld14a8642009-11-21 08:51:07 +00007754 return DeclRefExpr::Create(Context,
7755 ULE->getQualifier(),
7756 ULE->getQualifierRange(),
7757 Fn,
7758 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00007759 Fn->getType(),
7760 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00007761 }
7762
John McCall10eae182009-11-30 22:42:35 +00007763 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00007764 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00007765 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7766 if (MemExpr->hasExplicitTemplateArgs()) {
7767 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7768 TemplateArgs = &TemplateArgsBuffer;
7769 }
John McCall6b51f282009-11-23 01:53:49 +00007770
John McCall2d74de92009-12-01 22:10:20 +00007771 Expr *Base;
7772
7773 // If we're filling in
7774 if (MemExpr->isImplicitAccess()) {
7775 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7776 return DeclRefExpr::Create(Context,
7777 MemExpr->getQualifier(),
7778 MemExpr->getQualifierRange(),
7779 Fn,
7780 MemExpr->getMemberLoc(),
7781 Fn->getType(),
7782 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00007783 } else {
7784 SourceLocation Loc = MemExpr->getMemberLoc();
7785 if (MemExpr->getQualifier())
7786 Loc = MemExpr->getQualifierRange().getBegin();
7787 Base = new (Context) CXXThisExpr(Loc,
7788 MemExpr->getBaseType(),
7789 /*isImplicit=*/true);
7790 }
John McCall2d74de92009-12-01 22:10:20 +00007791 } else
7792 Base = MemExpr->getBase()->Retain();
7793
7794 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007795 MemExpr->isArrow(),
7796 MemExpr->getQualifier(),
7797 MemExpr->getQualifierRange(),
7798 Fn,
John McCall16df1e52010-03-30 21:47:33 +00007799 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007800 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00007801 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007802 Fn->getType());
7803 }
7804
Douglas Gregor51c538b2009-11-20 19:42:02 +00007805 assert(false && "Invalid reference to overloaded function");
7806 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00007807}
7808
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007809Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCalla8ae2222010-04-06 21:38:20 +00007810 DeclAccessPair Found,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007811 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00007812 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007813}
7814
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007815} // end namespace clang