blob: a22556a7e5a975cf65b144b475fdba82365271db [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:
318 case Sema::TDK_InconsistentQuals: {
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:
351 case Sema::TDK_InconsistentQuals:
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:
383 case Sema::TDK_InconsistentQuals:
384 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:
405 case Sema::TDK_InconsistentQuals:
406 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:
432 case Sema::TDK_InconsistentQuals:
433 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:
457 case Sema::TDK_InconsistentQuals:
458 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
459
Douglas Gregor461761d2010-05-08 18:20:53 +0000460 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000461 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000462 case Sema::TDK_FailedOverloadResolution:
463 break;
464 }
465
466 return 0;
467}
468
469void OverloadCandidateSet::clear() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000470 inherited::clear();
471 Functions.clear();
472}
473
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000474// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000475// overload of the declarations in Old. This routine returns false if
476// New and Old cannot be overloaded, e.g., if New has the same
477// signature as some function in Old (C++ 1.3.10) or if the Old
478// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000479// it does return false, MatchedDecl will point to the decl that New
480// cannot be overloaded with. This decl may be a UsingShadowDecl on
481// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000482//
483// Example: Given the following input:
484//
485// void f(int, float); // #1
486// void f(int, int); // #2
487// int f(int, int); // #3
488//
489// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000490// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000491//
John McCall3d988d92009-12-02 08:47:38 +0000492// When we process #2, Old contains only the FunctionDecl for #1. By
493// comparing the parameter types, we see that #1 and #2 are overloaded
494// (since they have different signatures), so this routine returns
495// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000496//
John McCall3d988d92009-12-02 08:47:38 +0000497// When we process #3, Old is an overload set containing #1 and #2. We
498// compare the signatures of #3 to #1 (they're overloaded, so we do
499// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
500// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000501// signature), IsOverload returns false and MatchedDecl will be set to
502// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000503//
504// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
505// into a class by a using declaration. The rules for whether to hide
506// shadow declarations ignore some properties which otherwise figure
507// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000508Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000509Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
510 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000511 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000512 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000513 NamedDecl *OldD = *I;
514
515 bool OldIsUsingDecl = false;
516 if (isa<UsingShadowDecl>(OldD)) {
517 OldIsUsingDecl = true;
518
519 // We can always introduce two using declarations into the same
520 // context, even if they have identical signatures.
521 if (NewIsUsingDecl) continue;
522
523 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
524 }
525
526 // If either declaration was introduced by a using declaration,
527 // we'll need to use slightly different rules for matching.
528 // Essentially, these rules are the normal rules, except that
529 // function templates hide function templates with different
530 // return types or template parameter lists.
531 bool UseMemberUsingDeclRules =
532 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
533
John McCall3d988d92009-12-02 08:47:38 +0000534 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000535 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
536 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
537 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
538 continue;
539 }
540
John McCalldaa3d6b2009-12-09 03:35:25 +0000541 Match = *I;
542 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000543 }
John McCall3d988d92009-12-02 08:47:38 +0000544 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000545 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
546 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
547 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
548 continue;
549 }
550
John McCalldaa3d6b2009-12-09 03:35:25 +0000551 Match = *I;
552 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000553 }
John McCall84d87672009-12-10 09:41:52 +0000554 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
555 // We can overload with these, which can show up when doing
556 // redeclaration checks for UsingDecls.
557 assert(Old.getLookupKind() == LookupUsingDeclName);
558 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
559 // Optimistically assume that an unresolved using decl will
560 // overload; if it doesn't, we'll have to diagnose during
561 // template instantiation.
562 } else {
John McCall1f82f242009-11-18 22:49:29 +0000563 // (C++ 13p1):
564 // Only function declarations can be overloaded; object and type
565 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000566 Match = *I;
567 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000568 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000569 }
John McCall1f82f242009-11-18 22:49:29 +0000570
John McCalldaa3d6b2009-12-09 03:35:25 +0000571 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000572}
573
John McCalle9cccd82010-06-16 08:42:20 +0000574bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
575 bool UseUsingDeclRules) {
John McCall1f82f242009-11-18 22:49:29 +0000576 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
577 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
578
579 // C++ [temp.fct]p2:
580 // A function template can be overloaded with other function templates
581 // and with normal (non-template) functions.
582 if ((OldTemplate == 0) != (NewTemplate == 0))
583 return true;
584
585 // Is the function New an overload of the function Old?
586 QualType OldQType = Context.getCanonicalType(Old->getType());
587 QualType NewQType = Context.getCanonicalType(New->getType());
588
589 // Compare the signatures (C++ 1.3.10) of the two functions to
590 // determine whether they are overloads. If we find any mismatch
591 // in the signature, they are overloads.
592
593 // If either of these functions is a K&R-style function (no
594 // prototype), then we consider them to have matching signatures.
595 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
596 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
597 return false;
598
599 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
600 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
601
602 // The signature of a function includes the types of its
603 // parameters (C++ 1.3.10), which includes the presence or absence
604 // of the ellipsis; see C++ DR 357).
605 if (OldQType != NewQType &&
606 (OldType->getNumArgs() != NewType->getNumArgs() ||
607 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000608 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000609 return true;
610
611 // C++ [temp.over.link]p4:
612 // The signature of a function template consists of its function
613 // signature, its return type and its template parameter list. The names
614 // of the template parameters are significant only for establishing the
615 // relationship between the template parameters and the rest of the
616 // signature.
617 //
618 // We check the return type and template parameter lists for function
619 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000620 //
621 // However, we don't consider either of these when deciding whether
622 // a member introduced by a shadow declaration is hidden.
623 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000624 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
625 OldTemplate->getTemplateParameters(),
626 false, TPL_TemplateMatch) ||
627 OldType->getResultType() != NewType->getResultType()))
628 return true;
629
630 // If the function is a class member, its signature includes the
631 // cv-qualifiers (if any) on the function itself.
632 //
633 // As part of this, also check whether one of the member functions
634 // is static, in which case they are not overloads (C++
635 // 13.1p2). While not part of the definition of the signature,
636 // this check is important to determine whether these functions
637 // can be overloaded.
638 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
639 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
640 if (OldMethod && NewMethod &&
641 !OldMethod->isStatic() && !NewMethod->isStatic() &&
642 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
643 return true;
644
645 // The signatures match; this is not an overload.
646 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000647}
648
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000649/// TryImplicitConversion - Attempt to perform an implicit conversion
650/// from the given expression (Expr) to the given type (ToType). This
651/// function returns an implicit conversion sequence that can be used
652/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000653///
654/// void f(float f);
655/// void g(int i) { f(i); }
656///
657/// this routine would produce an implicit conversion sequence to
658/// describe the initialization of f from i, which will be a standard
659/// conversion sequence containing an lvalue-to-rvalue conversion (C++
660/// 4.1) followed by a floating-integral conversion (C++ 4.9).
661//
662/// Note that this routine only determines how the conversion can be
663/// performed; it does not actually perform the conversion. As such,
664/// it will not produce any diagnostics if no conversion is available,
665/// but will instead return an implicit conversion sequence of kind
666/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000667///
668/// If @p SuppressUserConversions, then user-defined conversions are
669/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000670/// If @p AllowExplicit, then explicit user-defined conversions are
671/// permitted.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000672ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000673Sema::TryImplicitConversion(Expr* From, QualType ToType,
674 bool SuppressUserConversions,
Douglas Gregore81335c2010-04-16 18:00:29 +0000675 bool AllowExplicit,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000676 bool InOverloadResolution) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000677 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +0000678 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000679 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000680 return ICS;
681 }
682
683 if (!getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000684 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000685 return ICS;
686 }
687
Douglas Gregor5ab11652010-04-17 22:01:05 +0000688 if (SuppressUserConversions) {
689 // C++ [over.ics.user]p4:
690 // A conversion of an expression of class type to the same class
691 // type is given Exact Match rank, and a conversion of an
692 // expression of class type to a base class of that type is
693 // given Conversion rank, in spite of the fact that a copy/move
694 // constructor (i.e., a user-defined conversion function) is
695 // called for those cases.
696 QualType FromType = From->getType();
697 if (!ToType->getAs<RecordType>() || !FromType->getAs<RecordType>() ||
698 !(Context.hasSameUnqualifiedType(FromType, ToType) ||
699 IsDerivedFrom(FromType, ToType))) {
700 // We're not in the case above, so there is no conversion that
701 // we can perform.
702 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
703 return ICS;
704 }
705
706 ICS.setStandard();
707 ICS.Standard.setAsIdentityConversion();
708 ICS.Standard.setFromType(FromType);
709 ICS.Standard.setAllToTypes(ToType);
710
711 // We don't actually check at this point whether there is a valid
712 // copy/move constructor, since overloading just assumes that it
713 // exists. When we actually perform initialization, we'll find the
714 // appropriate constructor to copy the returned object, if needed.
715 ICS.Standard.CopyConstructor = 0;
716
717 // Determine whether this is considered a derived-to-base conversion.
718 if (!Context.hasSameUnqualifiedType(FromType, ToType))
719 ICS.Standard.Second = ICK_Derived_To_Base;
720
721 return ICS;
722 }
723
724 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000725 OverloadCandidateSet Conversions(From->getExprLoc());
726 OverloadingResult UserDefResult
727 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000728 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000729
730 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000731 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000732 // C++ [over.ics.user]p4:
733 // A conversion of an expression of class type to the same class
734 // type is given Exact Match rank, and a conversion of an
735 // expression of class type to a base class of that type is
736 // given Conversion rank, in spite of the fact that a copy
737 // constructor (i.e., a user-defined conversion function) is
738 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000739 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000740 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000741 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000742 = Context.getCanonicalType(From->getType().getUnqualifiedType());
743 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000744 if (Constructor->isCopyConstructor() &&
Douglas Gregor4141d5b2009-12-22 00:21:20 +0000745 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000746 // Turn this into a "standard" conversion sequence, so that it
747 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000748 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000749 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000750 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000751 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000752 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000753 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000754 ICS.Standard.Second = ICK_Derived_To_Base;
755 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000756 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000757
758 // C++ [over.best.ics]p4:
759 // However, when considering the argument of a user-defined
760 // conversion function that is a candidate by 13.3.1.3 when
761 // invoked for the copying of the temporary in the second step
762 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
763 // 13.3.1.6 in all cases, only standard conversion sequences and
764 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000765 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000766 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000767 }
John McCalle8c8cd22010-01-13 22:30:33 +0000768 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000769 ICS.setAmbiguous();
770 ICS.Ambiguous.setFromType(From->getType());
771 ICS.Ambiguous.setToType(ToType);
772 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
773 Cand != Conversions.end(); ++Cand)
774 if (Cand->Viable)
775 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000776 } else {
John McCall65eb8792010-02-25 01:37:24 +0000777 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000778 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000779
780 return ICS;
781}
782
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000783/// PerformImplicitConversion - Perform an implicit conversion of the
784/// expression From to the type ToType. Returns true if there was an
785/// error, false otherwise. The expression From is replaced with the
786/// converted expression. Flavor is the kind of conversion we're
787/// performing, used in the error message. If @p AllowExplicit,
788/// explicit user-defined conversions are permitted.
789bool
790Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
791 AssignmentAction Action, bool AllowExplicit) {
792 ImplicitConversionSequence ICS;
793 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
794}
795
796bool
797Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
798 AssignmentAction Action, bool AllowExplicit,
799 ImplicitConversionSequence& ICS) {
800 ICS = TryImplicitConversion(From, ToType,
801 /*SuppressUserConversions=*/false,
802 AllowExplicit,
803 /*InOverloadResolution=*/false);
804 return PerformImplicitConversion(From, ToType, ICS, Action);
805}
806
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000807/// \brief Determine whether the conversion from FromType to ToType is a valid
808/// conversion that strips "noreturn" off the nested function type.
809static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
810 QualType ToType, QualType &ResultTy) {
811 if (Context.hasSameUnqualifiedType(FromType, ToType))
812 return false;
813
814 // Strip the noreturn off the type we're converting from; noreturn can
815 // safely be removed.
816 FromType = Context.getNoReturnType(FromType, false);
817 if (!Context.hasSameUnqualifiedType(FromType, ToType))
818 return false;
819
820 ResultTy = FromType;
821 return true;
822}
Douglas Gregor46188682010-05-18 22:42:18 +0000823
824/// \brief Determine whether the conversion from FromType to ToType is a valid
825/// vector conversion.
826///
827/// \param ICK Will be set to the vector conversion kind, if this is a vector
828/// conversion.
829static bool IsVectorConversion(ASTContext &Context, QualType FromType,
830 QualType ToType, ImplicitConversionKind &ICK) {
831 // We need at least one of these types to be a vector type to have a vector
832 // conversion.
833 if (!ToType->isVectorType() && !FromType->isVectorType())
834 return false;
835
836 // Identical types require no conversions.
837 if (Context.hasSameUnqualifiedType(FromType, ToType))
838 return false;
839
840 // There are no conversions between extended vector types, only identity.
841 if (ToType->isExtVectorType()) {
842 // There are no conversions between extended vector types other than the
843 // identity conversion.
844 if (FromType->isExtVectorType())
845 return false;
846
847 // Vector splat from any arithmetic type to a vector.
848 if (!FromType->isVectorType() && FromType->isArithmeticType()) {
849 ICK = ICK_Vector_Splat;
850 return true;
851 }
852 }
853
854 // If lax vector conversions are permitted and the vector types are of the
855 // same size, we can perform the conversion.
856 if (Context.getLangOptions().LaxVectorConversions &&
857 FromType->isVectorType() && ToType->isVectorType() &&
858 Context.getTypeSize(FromType) == Context.getTypeSize(ToType)) {
859 ICK = ICK_Vector_Conversion;
860 return true;
861 }
862
863 return false;
864}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000865
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000866/// IsStandardConversion - Determines whether there is a standard
867/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
868/// expression From to the type ToType. Standard conversion sequences
869/// only consider non-class types; for conversions that involve class
870/// types, use TryImplicitConversion. If a conversion exists, SCS will
871/// contain the standard conversion sequence required to perform this
872/// conversion and this routine will return true. Otherwise, this
873/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000874bool
875Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000876 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000877 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000878 QualType FromType = From->getType();
879
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000880 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000881 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000882 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000883 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000884 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000885 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000886
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000887 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000888 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000889 if (FromType->isRecordType() || ToType->isRecordType()) {
890 if (getLangOptions().CPlusPlus)
891 return false;
892
Mike Stump11289f42009-09-09 15:08:12 +0000893 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000894 }
895
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000896 // The first conversion can be an lvalue-to-rvalue conversion,
897 // array-to-pointer conversion, or function-to-pointer conversion
898 // (C++ 4p1).
899
Douglas Gregor980fb162010-04-29 18:24:40 +0000900 if (FromType == Context.OverloadTy) {
901 DeclAccessPair AccessPair;
902 if (FunctionDecl *Fn
903 = ResolveAddressOfOverloadedFunction(From, ToType, false,
904 AccessPair)) {
905 // We were able to resolve the address of the overloaded function,
906 // so we can convert to the type of that function.
907 FromType = Fn->getType();
908 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
909 if (!Method->isStatic()) {
910 Type *ClassType
911 = Context.getTypeDeclType(Method->getParent()).getTypePtr();
912 FromType = Context.getMemberPointerType(FromType, ClassType);
913 }
914 }
915
916 // If the "from" expression takes the address of the overloaded
917 // function, update the type of the resulting expression accordingly.
918 if (FromType->getAs<FunctionType>())
919 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
920 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
921 FromType = Context.getPointerType(FromType);
922
923 // Check that we've computed the proper type after overload resolution.
924 assert(Context.hasSameType(FromType,
925 FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
926 } else {
927 return false;
928 }
929 }
Mike Stump11289f42009-09-09 15:08:12 +0000930 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000931 // An lvalue (3.10) of a non-function, non-array type T can be
932 // converted to an rvalue.
933 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000934 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000935 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000936 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000937 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000938
939 // If T is a non-class type, the type of the rvalue is the
940 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000941 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
942 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000943 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000944 } else if (FromType->isArrayType()) {
945 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000946 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000947
948 // An lvalue or rvalue of type "array of N T" or "array of unknown
949 // bound of T" can be converted to an rvalue of type "pointer to
950 // T" (C++ 4.2p1).
951 FromType = Context.getArrayDecayedType(FromType);
952
953 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
954 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +0000955 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000956
957 // For the purpose of ranking in overload resolution
958 // (13.3.3.1.1), this conversion is considered an
959 // array-to-pointer conversion followed by a qualification
960 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000961 SCS.Second = ICK_Identity;
962 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000963 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000964 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000965 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000966 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
967 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000968 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000969
970 // An lvalue of function type T can be converted to an rvalue of
971 // type "pointer to T." The result is a pointer to the
972 // function. (C++ 4.3p1).
973 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000974 } else {
975 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000976 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000977 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000978 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000979
980 // The second conversion can be an integral promotion, floating
981 // point promotion, integral conversion, floating point conversion,
982 // floating-integral conversion, pointer conversion,
983 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000984 // For overloading in C, this can also be a "compatible-type"
985 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000986 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +0000987 ImplicitConversionKind SecondICK = ICK_Identity;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000988 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000989 // The unqualified versions of the types are the same: there's no
990 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000991 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000992 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000993 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000994 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000995 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000996 } else if (IsFloatingPointPromotion(FromType, ToType)) {
997 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000998 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000999 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001000 } else if (IsComplexPromotion(FromType, ToType)) {
1001 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001002 SCS.Second = ICK_Complex_Promotion;
1003 FromType = ToType.getUnqualifiedType();
Douglas Gregorb90df602010-06-16 00:17:44 +00001004 } else if (FromType->isIntegralOrEnumerationType() &&
Douglas Gregor6972a622010-06-16 00:35:25 +00001005 ToType->isIntegralType(Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001006 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001007 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001008 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001009 } else if (FromType->isComplexType() && ToType->isComplexType()) {
1010 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001011 SCS.Second = ICK_Complex_Conversion;
1012 FromType = ToType.getUnqualifiedType();
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001013 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
1014 (ToType->isComplexType() && FromType->isArithmeticType())) {
1015 // Complex-real conversions (C99 6.3.1.7)
1016 SCS.Second = ICK_Complex_Real;
1017 FromType = ToType.getUnqualifiedType();
Douglas Gregordb48cf32010-06-22 16:52:27 +00001018 } else if (FromType->isFloatingType() && ToType->isFloatingType() &&
1019 /*FIXME*/!FromType->isVectorType() &&
1020 /*FIXME*/!ToType->isVectorType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001021 // Floating point conversions (C++ 4.8).
1022 SCS.Second = ICK_Floating_Conversion;
1023 FromType = ToType.getUnqualifiedType();
Douglas Gregordb48cf32010-06-22 16:52:27 +00001024 } else if ((FromType->isFloatingType() &&
1025 /*FIXME*/!FromType->isVectorType() &&
Douglas Gregor6972a622010-06-16 00:35:25 +00001026 ToType->isIntegralType(Context) && !ToType->isBooleanType()) ||
Douglas Gregorb90df602010-06-16 00:17:44 +00001027 (FromType->isIntegralOrEnumerationType() &&
Douglas Gregordb48cf32010-06-22 16:52:27 +00001028 ToType->isFloatingType() &&
1029 /*FIXME*/!FromType->isVectorType())) {
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 Gregordb48cf32010-06-22 16:52:27 +00001048 FromType->isNullPtrType()) &&
1049 /*FIXME*/!FromType->isVectorType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001050 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001051 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001052 FromType = Context.BoolTy;
Douglas Gregor46188682010-05-18 22:42:18 +00001053 } else if (IsVectorConversion(Context, FromType, ToType, SecondICK)) {
1054 SCS.Second = SecondICK;
1055 FromType = ToType.getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001056 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +00001057 Context.typesAreCompatible(ToType, FromType)) {
1058 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001059 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001060 FromType = ToType.getUnqualifiedType();
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001061 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
1062 // Treat a conversion that strips "noreturn" as an identity conversion.
1063 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001064 } else {
1065 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001066 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001067 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001068 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001069
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001070 QualType CanonFrom;
1071 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001072 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +00001073 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001074 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001075 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001076 CanonFrom = Context.getCanonicalType(FromType);
1077 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001078 } else {
1079 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001080 SCS.Third = ICK_Identity;
1081
Mike Stump11289f42009-09-09 15:08:12 +00001082 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001083 // [...] Any difference in top-level cv-qualification is
1084 // subsumed by the initialization itself and does not constitute
1085 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001086 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +00001087 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001088 if (CanonFrom.getLocalUnqualifiedType()
1089 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001090 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1091 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001092 FromType = ToType;
1093 CanonFrom = CanonTo;
1094 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001095 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001096 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001097
1098 // If we have not converted the argument type to the parameter type,
1099 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001100 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001101 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001102
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001103 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001104}
1105
1106/// IsIntegralPromotion - Determines whether the conversion from the
1107/// expression From (whose potentially-adjusted type is FromType) to
1108/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1109/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001110bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001111 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001112 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001113 if (!To) {
1114 return false;
1115 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001116
1117 // An rvalue of type char, signed char, unsigned char, short int, or
1118 // unsigned short int can be converted to an rvalue of type int if
1119 // int can represent all the values of the source type; otherwise,
1120 // the source rvalue can be converted to an rvalue of type unsigned
1121 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001122 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1123 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001124 if (// We can promote any signed, promotable integer type to an int
1125 (FromType->isSignedIntegerType() ||
1126 // We can promote any unsigned integer type whose size is
1127 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001128 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001129 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001130 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001131 }
1132
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001133 return To->getKind() == BuiltinType::UInt;
1134 }
1135
1136 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
1137 // can be converted to an rvalue of the first of the following types
1138 // that can represent all the values of its underlying type: int,
1139 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +00001140
1141 // We pre-calculate the promotion type for enum types.
1142 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
1143 if (ToType->isIntegerType())
1144 return Context.hasSameUnqualifiedType(ToType,
1145 FromEnumType->getDecl()->getPromotionType());
1146
1147 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001148 // Determine whether the type we're converting from is signed or
1149 // unsigned.
1150 bool FromIsSigned;
1151 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +00001152
1153 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1154 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001155
1156 // The types we'll try to promote to, in the appropriate
1157 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001158 QualType PromoteTypes[6] = {
1159 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001160 Context.LongTy, Context.UnsignedLongTy ,
1161 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001162 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001163 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001164 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1165 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001166 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001167 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1168 // We found the type that we can promote to. If this is the
1169 // type we wanted, we have a promotion. Otherwise, no
1170 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001171 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001172 }
1173 }
1174 }
1175
1176 // An rvalue for an integral bit-field (9.6) can be converted to an
1177 // rvalue of type int if int can represent all the values of the
1178 // bit-field; otherwise, it can be converted to unsigned int if
1179 // unsigned int can represent all the values of the bit-field. If
1180 // the bit-field is larger yet, no integral promotion applies to
1181 // it. If the bit-field has an enumerated type, it is treated as any
1182 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001183 // FIXME: We should delay checking of bit-fields until we actually perform the
1184 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001185 using llvm::APSInt;
1186 if (From)
1187 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001188 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001189 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001190 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1191 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1192 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001193
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001194 // Are we promoting to an int from a bitfield that fits in an int?
1195 if (BitWidth < ToSize ||
1196 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1197 return To->getKind() == BuiltinType::Int;
1198 }
Mike Stump11289f42009-09-09 15:08:12 +00001199
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001200 // Are we promoting to an unsigned int from an unsigned bitfield
1201 // that fits into an unsigned int?
1202 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1203 return To->getKind() == BuiltinType::UInt;
1204 }
Mike Stump11289f42009-09-09 15:08:12 +00001205
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001206 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001207 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001208 }
Mike Stump11289f42009-09-09 15:08:12 +00001209
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001210 // An rvalue of type bool can be converted to an rvalue of type int,
1211 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001212 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001213 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001214 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001215
1216 return false;
1217}
1218
1219/// IsFloatingPointPromotion - Determines whether the conversion from
1220/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1221/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001222bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001223 /// An rvalue of type float can be converted to an rvalue of type
1224 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001225 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1226 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001227 if (FromBuiltin->getKind() == BuiltinType::Float &&
1228 ToBuiltin->getKind() == BuiltinType::Double)
1229 return true;
1230
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001231 // C99 6.3.1.5p1:
1232 // When a float is promoted to double or long double, or a
1233 // double is promoted to long double [...].
1234 if (!getLangOptions().CPlusPlus &&
1235 (FromBuiltin->getKind() == BuiltinType::Float ||
1236 FromBuiltin->getKind() == BuiltinType::Double) &&
1237 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1238 return true;
1239 }
1240
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001241 return false;
1242}
1243
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001244/// \brief Determine if a conversion is a complex promotion.
1245///
1246/// A complex promotion is defined as a complex -> complex conversion
1247/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001248/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001249bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001250 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001251 if (!FromComplex)
1252 return false;
1253
John McCall9dd450b2009-09-21 23:43:11 +00001254 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001255 if (!ToComplex)
1256 return false;
1257
1258 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001259 ToComplex->getElementType()) ||
1260 IsIntegralPromotion(0, FromComplex->getElementType(),
1261 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001262}
1263
Douglas Gregor237f96c2008-11-26 23:31:11 +00001264/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1265/// the pointer type FromPtr to a pointer to type ToPointee, with the
1266/// same type qualifiers as FromPtr has on its pointee type. ToType,
1267/// if non-empty, will be a pointer to ToType that may or may not have
1268/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001269static QualType
1270BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001271 QualType ToPointee, QualType ToType,
1272 ASTContext &Context) {
1273 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1274 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001275 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001276
1277 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001278 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001279 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001280 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001281 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001282
1283 // Build a pointer to ToPointee. It has the right qualifiers
1284 // already.
1285 return Context.getPointerType(ToPointee);
1286 }
1287
1288 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +00001289 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001290 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1291 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +00001292}
1293
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001294/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1295/// the FromType, which is an objective-c pointer, to ToType, which may or may
1296/// not have the right set of qualifiers.
1297static QualType
1298BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1299 QualType ToType,
1300 ASTContext &Context) {
1301 QualType CanonFromType = Context.getCanonicalType(FromType);
1302 QualType CanonToType = Context.getCanonicalType(ToType);
1303 Qualifiers Quals = CanonFromType.getQualifiers();
1304
1305 // Exact qualifier match -> return the pointer type we're converting to.
1306 if (CanonToType.getLocalQualifiers() == Quals)
1307 return ToType;
1308
1309 // Just build a canonical type that has the right qualifiers.
1310 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1311}
1312
Mike Stump11289f42009-09-09 15:08:12 +00001313static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001314 bool InOverloadResolution,
1315 ASTContext &Context) {
1316 // Handle value-dependent integral null pointer constants correctly.
1317 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1318 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001319 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001320 return !InOverloadResolution;
1321
Douglas Gregor56751b52009-09-25 04:25:58 +00001322 return Expr->isNullPointerConstant(Context,
1323 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1324 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001325}
Mike Stump11289f42009-09-09 15:08:12 +00001326
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001327/// IsPointerConversion - Determines whether the conversion of the
1328/// expression From, which has the (possibly adjusted) type FromType,
1329/// can be converted to the type ToType via a pointer conversion (C++
1330/// 4.10). If so, returns true and places the converted type (that
1331/// might differ from ToType in its cv-qualifiers at some level) into
1332/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001333///
Douglas Gregora29dc052008-11-27 01:19:21 +00001334/// This routine also supports conversions to and from block pointers
1335/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1336/// pointers to interfaces. FIXME: Once we've determined the
1337/// appropriate overloading rules for Objective-C, we may want to
1338/// split the Objective-C checks into a different routine; however,
1339/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001340/// conversions, so for now they live here. IncompatibleObjC will be
1341/// set if the conversion is an allowed Objective-C conversion that
1342/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001343bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001344 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001345 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001346 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001347 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001348 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1349 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001350
Mike Stump11289f42009-09-09 15:08:12 +00001351 // Conversion from a null pointer constant to any Objective-C pointer type.
1352 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001353 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001354 ConvertedType = ToType;
1355 return true;
1356 }
1357
Douglas Gregor231d1c62008-11-27 00:15:41 +00001358 // Blocks: Block pointers can be converted to void*.
1359 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001360 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001361 ConvertedType = ToType;
1362 return true;
1363 }
1364 // Blocks: A null pointer constant can be converted to a block
1365 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001366 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001367 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001368 ConvertedType = ToType;
1369 return true;
1370 }
1371
Sebastian Redl576fd422009-05-10 18:38:11 +00001372 // If the left-hand-side is nullptr_t, the right side can be a null
1373 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001374 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001375 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001376 ConvertedType = ToType;
1377 return true;
1378 }
1379
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001380 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001381 if (!ToTypePtr)
1382 return false;
1383
1384 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001385 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001386 ConvertedType = ToType;
1387 return true;
1388 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001389
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001390 // Beyond this point, both types need to be pointers
1391 // , including objective-c pointers.
1392 QualType ToPointeeType = ToTypePtr->getPointeeType();
1393 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1394 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1395 ToType, Context);
1396 return true;
1397
1398 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001399 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001400 if (!FromTypePtr)
1401 return false;
1402
1403 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001404
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001405 // An rvalue of type "pointer to cv T," where T is an object type,
1406 // can be converted to an rvalue of type "pointer to cv void" (C++
1407 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +00001408 if (FromPointeeType->isObjectType() && 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,
Anders Carlssona70cff62010-04-24 19:06:50 +00001666 CXXBaseSpecifierArray& 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,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001758 CXXBaseSpecifierArray &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())) {
Mike Stump11289f42009-09-09 15:08:12 +00001904 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001905 = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor5ab11652010-04-17 22:01:05 +00001906 Context.getCanonicalType(ToType).getUnqualifiedType());
Douglas Gregor89ee6822009-02-28 01:32:25 +00001907 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001908 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001909 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001910 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00001911 NamedDecl *D = *Con;
1912 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1913
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001914 // Find the constructor (which may be a template).
1915 CXXConstructorDecl *Constructor = 0;
1916 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00001917 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001918 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001919 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001920 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1921 else
John McCalla0296f72010-03-19 07:35:19 +00001922 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001923
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001924 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001925 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001926 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00001927 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001928 /*ExplicitArgs*/ 0,
John McCall6b51f282009-11-23 01:53:49 +00001929 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001930 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001931 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001932 // Allow one user-defined conversion when user specifies a
1933 // From->ToType conversion via an static cast (c-style, etc).
John McCalla0296f72010-03-19 07:35:19 +00001934 AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001935 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001936 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001937 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001938 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001939 }
1940 }
1941
Douglas Gregor5ab11652010-04-17 22:01:05 +00001942 // Enumerate conversion functions, if we're allowed to.
1943 if (ConstructorsOnly) {
Mike Stump11289f42009-09-09 15:08:12 +00001944 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
Douglas Gregor5ab11652010-04-17 22:01:05 +00001945 PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001946 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001947 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00001948 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001949 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001950 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1951 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00001952 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001953 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001954 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001955 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00001956 DeclAccessPair FoundDecl = I.getPair();
1957 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00001958 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1959 if (isa<UsingShadowDecl>(D))
1960 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1961
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001962 CXXConversionDecl *Conv;
1963 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00001964 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1965 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001966 else
John McCallda4458e2010-03-31 01:36:47 +00001967 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001968
1969 if (AllowExplicit || !Conv->isExplicit()) {
1970 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00001971 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001972 ActingContext, From, ToType,
1973 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001974 else
John McCalla0296f72010-03-19 07:35:19 +00001975 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCallb89836b2010-01-26 01:37:31 +00001976 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001977 }
1978 }
1979 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001980 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001981
1982 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001983 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001984 case OR_Success:
1985 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001986 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001987 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1988 // C++ [over.ics.user]p1:
1989 // If the user-defined conversion is specified by a
1990 // constructor (12.3.1), the initial standard conversion
1991 // sequence converts the source type to the type required by
1992 // the argument of the constructor.
1993 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001994 QualType ThisType = Constructor->getThisType(Context);
John McCall0d1da222010-01-12 00:44:57 +00001995 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian55824512009-11-06 00:23:08 +00001996 User.EllipsisConversion = true;
1997 else {
1998 User.Before = Best->Conversions[0].Standard;
1999 User.EllipsisConversion = false;
2000 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002001 User.ConversionFunction = Constructor;
2002 User.After.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00002003 User.After.setFromType(
2004 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002005 User.After.setAllToTypes(ToType);
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002006 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002007 } else if (CXXConversionDecl *Conversion
2008 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2009 // C++ [over.ics.user]p1:
2010 //
2011 // [...] If the user-defined conversion is specified by a
2012 // conversion function (12.3.2), the initial standard
2013 // conversion sequence converts the source type to the
2014 // implicit object parameter of the conversion function.
2015 User.Before = Best->Conversions[0].Standard;
2016 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002017 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002018
2019 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00002020 // The second standard conversion sequence converts the
2021 // result of the user-defined conversion to the target type
2022 // for the sequence. Since an implicit conversion sequence
2023 // is an initialization, the special rules for
2024 // initialization by user-defined conversion apply when
2025 // selecting the best user-defined conversion for a
2026 // user-defined conversion sequence (see 13.3.3 and
2027 // 13.3.3.1).
2028 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002029 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002030 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002031 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002032 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002033 }
Mike Stump11289f42009-09-09 15:08:12 +00002034
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002035 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002036 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00002037 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002038 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002039 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002040
2041 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002042 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002043 }
2044
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002045 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002046}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002047
2048bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002049Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002050 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002051 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002052 OverloadingResult OvResult =
2053 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002054 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002055 if (OvResult == OR_Ambiguous)
2056 Diag(From->getSourceRange().getBegin(),
2057 diag::err_typecheck_ambiguous_condition)
2058 << From->getType() << ToType << From->getSourceRange();
2059 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2060 Diag(From->getSourceRange().getBegin(),
2061 diag::err_typecheck_nonviable_condition)
2062 << From->getType() << ToType << From->getSourceRange();
2063 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002064 return false;
John McCallad907772010-01-12 07:18:19 +00002065 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002066 return true;
2067}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002068
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002069/// CompareImplicitConversionSequences - Compare two implicit
2070/// conversion sequences to determine whether one is better than the
2071/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00002072ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002073Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
2074 const ImplicitConversionSequence& ICS2)
2075{
2076 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2077 // conversion sequences (as defined in 13.3.3.1)
2078 // -- a standard conversion sequence (13.3.3.1.1) is a better
2079 // conversion sequence than a user-defined conversion sequence or
2080 // an ellipsis conversion sequence, and
2081 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2082 // conversion sequence than an ellipsis conversion sequence
2083 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002084 //
John McCall0d1da222010-01-12 00:44:57 +00002085 // C++0x [over.best.ics]p10:
2086 // For the purpose of ranking implicit conversion sequences as
2087 // described in 13.3.3.2, the ambiguous conversion sequence is
2088 // treated as a user-defined sequence that is indistinguishable
2089 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002090 if (ICS1.getKindRank() < ICS2.getKindRank())
2091 return ImplicitConversionSequence::Better;
2092 else if (ICS2.getKindRank() < ICS1.getKindRank())
2093 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002094
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002095 // The following checks require both conversion sequences to be of
2096 // the same kind.
2097 if (ICS1.getKind() != ICS2.getKind())
2098 return ImplicitConversionSequence::Indistinguishable;
2099
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002100 // Two implicit conversion sequences of the same form are
2101 // indistinguishable conversion sequences unless one of the
2102 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002103 if (ICS1.isStandard())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002104 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002105 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002106 // User-defined conversion sequence U1 is a better conversion
2107 // sequence than another user-defined conversion sequence U2 if
2108 // they contain the same user-defined conversion function or
2109 // constructor and if the second standard conversion sequence of
2110 // U1 is better than the second standard conversion sequence of
2111 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002112 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002113 ICS2.UserDefined.ConversionFunction)
2114 return CompareStandardConversionSequences(ICS1.UserDefined.After,
2115 ICS2.UserDefined.After);
2116 }
2117
2118 return ImplicitConversionSequence::Indistinguishable;
2119}
2120
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002121static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2122 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2123 Qualifiers Quals;
2124 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2125 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2126 }
2127
2128 return Context.hasSameUnqualifiedType(T1, T2);
2129}
2130
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002131// Per 13.3.3.2p3, compare the given standard conversion sequences to
2132// determine if one is a proper subset of the other.
2133static ImplicitConversionSequence::CompareKind
2134compareStandardConversionSubsets(ASTContext &Context,
2135 const StandardConversionSequence& SCS1,
2136 const StandardConversionSequence& SCS2) {
2137 ImplicitConversionSequence::CompareKind Result
2138 = ImplicitConversionSequence::Indistinguishable;
2139
Douglas Gregore87561a2010-05-23 22:10:15 +00002140 // the identity conversion sequence is considered to be a subsequence of
2141 // any non-identity conversion sequence
2142 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2143 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2144 return ImplicitConversionSequence::Better;
2145 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2146 return ImplicitConversionSequence::Worse;
2147 }
2148
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002149 if (SCS1.Second != SCS2.Second) {
2150 if (SCS1.Second == ICK_Identity)
2151 Result = ImplicitConversionSequence::Better;
2152 else if (SCS2.Second == ICK_Identity)
2153 Result = ImplicitConversionSequence::Worse;
2154 else
2155 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002156 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002157 return ImplicitConversionSequence::Indistinguishable;
2158
2159 if (SCS1.Third == SCS2.Third) {
2160 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2161 : ImplicitConversionSequence::Indistinguishable;
2162 }
2163
2164 if (SCS1.Third == ICK_Identity)
2165 return Result == ImplicitConversionSequence::Worse
2166 ? ImplicitConversionSequence::Indistinguishable
2167 : ImplicitConversionSequence::Better;
2168
2169 if (SCS2.Third == ICK_Identity)
2170 return Result == ImplicitConversionSequence::Better
2171 ? ImplicitConversionSequence::Indistinguishable
2172 : ImplicitConversionSequence::Worse;
2173
2174 return ImplicitConversionSequence::Indistinguishable;
2175}
2176
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002177/// CompareStandardConversionSequences - Compare two standard
2178/// conversion sequences to determine whether one is better than the
2179/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002180ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002181Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
2182 const StandardConversionSequence& SCS2)
2183{
2184 // Standard conversion sequence S1 is a better conversion sequence
2185 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2186
2187 // -- S1 is a proper subsequence of S2 (comparing the conversion
2188 // sequences in the canonical form defined by 13.3.3.1.1,
2189 // excluding any Lvalue Transformation; the identity conversion
2190 // sequence is considered to be a subsequence of any
2191 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002192 if (ImplicitConversionSequence::CompareKind CK
2193 = compareStandardConversionSubsets(Context, SCS1, SCS2))
2194 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002195
2196 // -- the rank of S1 is better than the rank of S2 (by the rules
2197 // defined below), or, if not that,
2198 ImplicitConversionRank Rank1 = SCS1.getRank();
2199 ImplicitConversionRank Rank2 = SCS2.getRank();
2200 if (Rank1 < Rank2)
2201 return ImplicitConversionSequence::Better;
2202 else if (Rank2 < Rank1)
2203 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002204
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002205 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2206 // are indistinguishable unless one of the following rules
2207 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002208
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002209 // A conversion that is not a conversion of a pointer, or
2210 // pointer to member, to bool is better than another conversion
2211 // that is such a conversion.
2212 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2213 return SCS2.isPointerConversionToBool()
2214 ? ImplicitConversionSequence::Better
2215 : ImplicitConversionSequence::Worse;
2216
Douglas Gregor5c407d92008-10-23 00:40:37 +00002217 // C++ [over.ics.rank]p4b2:
2218 //
2219 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002220 // conversion of B* to A* is better than conversion of B* to
2221 // void*, and conversion of A* to void* is better than conversion
2222 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002223 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00002224 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00002225 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00002226 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002227 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2228 // Exactly one of the conversion sequences is a conversion to
2229 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002230 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2231 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002232 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2233 // Neither conversion sequence converts to a void pointer; compare
2234 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002235 if (ImplicitConversionSequence::CompareKind DerivedCK
2236 = CompareDerivedToBaseConversions(SCS1, SCS2))
2237 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002238 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2239 // Both conversion sequences are conversions to void
2240 // pointers. Compare the source types to determine if there's an
2241 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002242 QualType FromType1 = SCS1.getFromType();
2243 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002244
2245 // Adjust the types we're converting from via the array-to-pointer
2246 // conversion, if we need to.
2247 if (SCS1.First == ICK_Array_To_Pointer)
2248 FromType1 = Context.getArrayDecayedType(FromType1);
2249 if (SCS2.First == ICK_Array_To_Pointer)
2250 FromType2 = Context.getArrayDecayedType(FromType2);
2251
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002252 QualType FromPointee1
2253 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2254 QualType FromPointee2
2255 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002256
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002257 if (IsDerivedFrom(FromPointee2, FromPointee1))
2258 return ImplicitConversionSequence::Better;
2259 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2260 return ImplicitConversionSequence::Worse;
2261
2262 // Objective-C++: If one interface is more specific than the
2263 // other, it is the better one.
John McCall8b07ec22010-05-15 11:32:37 +00002264 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2265 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002266 if (FromIface1 && FromIface1) {
2267 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2268 return ImplicitConversionSequence::Better;
2269 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2270 return ImplicitConversionSequence::Worse;
2271 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002272 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002273
2274 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2275 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002276 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002277 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002278 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002279
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002280 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00002281 // C++0x [over.ics.rank]p3b4:
2282 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2283 // implicit object parameter of a non-static member function declared
2284 // without a ref-qualifier, and S1 binds an rvalue reference to an
2285 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00002286 // FIXME: We don't know if we're dealing with the implicit object parameter,
2287 // or if the member function in this case has a ref qualifier.
2288 // (Of course, we don't have ref qualifiers yet.)
2289 if (SCS1.RRefBinding != SCS2.RRefBinding)
2290 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2291 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00002292
2293 // C++ [over.ics.rank]p3b4:
2294 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2295 // which the references refer are the same type except for
2296 // top-level cv-qualifiers, and the type to which the reference
2297 // initialized by S2 refers is more cv-qualified than the type
2298 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002299 QualType T1 = SCS1.getToType(2);
2300 QualType T2 = SCS2.getToType(2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002301 T1 = Context.getCanonicalType(T1);
2302 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002303 Qualifiers T1Quals, T2Quals;
2304 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2305 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2306 if (UnqualT1 == UnqualT2) {
2307 // If the type is an array type, promote the element qualifiers to the type
2308 // for comparison.
2309 if (isa<ArrayType>(T1) && T1Quals)
2310 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2311 if (isa<ArrayType>(T2) && T2Quals)
2312 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002313 if (T2.isMoreQualifiedThan(T1))
2314 return ImplicitConversionSequence::Better;
2315 else if (T1.isMoreQualifiedThan(T2))
2316 return ImplicitConversionSequence::Worse;
2317 }
2318 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002319
2320 return ImplicitConversionSequence::Indistinguishable;
2321}
2322
2323/// CompareQualificationConversions - Compares two standard conversion
2324/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002325/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2326ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002327Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00002328 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002329 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002330 // -- S1 and S2 differ only in their qualification conversion and
2331 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2332 // cv-qualification signature of type T1 is a proper subset of
2333 // the cv-qualification signature of type T2, and S1 is not the
2334 // deprecated string literal array-to-pointer conversion (4.2).
2335 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2336 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2337 return ImplicitConversionSequence::Indistinguishable;
2338
2339 // FIXME: the example in the standard doesn't use a qualification
2340 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002341 QualType T1 = SCS1.getToType(2);
2342 QualType T2 = SCS2.getToType(2);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002343 T1 = Context.getCanonicalType(T1);
2344 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002345 Qualifiers T1Quals, T2Quals;
2346 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2347 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002348
2349 // If the types are the same, we won't learn anything by unwrapped
2350 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002351 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002352 return ImplicitConversionSequence::Indistinguishable;
2353
Chandler Carruth607f38e2009-12-29 07:16:59 +00002354 // If the type is an array type, promote the element qualifiers to the type
2355 // for comparison.
2356 if (isa<ArrayType>(T1) && T1Quals)
2357 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2358 if (isa<ArrayType>(T2) && T2Quals)
2359 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2360
Mike Stump11289f42009-09-09 15:08:12 +00002361 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002362 = ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002363 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002364 // Within each iteration of the loop, we check the qualifiers to
2365 // determine if this still looks like a qualification
2366 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002367 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002368 // until there are no more pointers or pointers-to-members left
2369 // to unwrap. This essentially mimics what
2370 // IsQualificationConversion does, but here we're checking for a
2371 // strict subset of qualifiers.
2372 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2373 // The qualifiers are the same, so this doesn't tell us anything
2374 // about how the sequences rank.
2375 ;
2376 else if (T2.isMoreQualifiedThan(T1)) {
2377 // T1 has fewer qualifiers, so it could be the better sequence.
2378 if (Result == ImplicitConversionSequence::Worse)
2379 // Neither has qualifiers that are a subset of the other's
2380 // qualifiers.
2381 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002382
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002383 Result = ImplicitConversionSequence::Better;
2384 } else if (T1.isMoreQualifiedThan(T2)) {
2385 // T2 has fewer qualifiers, so it could be the better sequence.
2386 if (Result == ImplicitConversionSequence::Better)
2387 // Neither has qualifiers that are a subset of the other's
2388 // qualifiers.
2389 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002390
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002391 Result = ImplicitConversionSequence::Worse;
2392 } else {
2393 // Qualifiers are disjoint.
2394 return ImplicitConversionSequence::Indistinguishable;
2395 }
2396
2397 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002398 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002399 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002400 }
2401
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002402 // Check that the winning standard conversion sequence isn't using
2403 // the deprecated string literal array to pointer conversion.
2404 switch (Result) {
2405 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002406 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002407 Result = ImplicitConversionSequence::Indistinguishable;
2408 break;
2409
2410 case ImplicitConversionSequence::Indistinguishable:
2411 break;
2412
2413 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002414 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002415 Result = ImplicitConversionSequence::Indistinguishable;
2416 break;
2417 }
2418
2419 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002420}
2421
Douglas Gregor5c407d92008-10-23 00:40:37 +00002422/// CompareDerivedToBaseConversions - Compares two standard conversion
2423/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002424/// various kinds of derived-to-base conversions (C++
2425/// [over.ics.rank]p4b3). As part of these checks, we also look at
2426/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002427ImplicitConversionSequence::CompareKind
2428Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2429 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002430 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002431 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002432 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002433 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002434
2435 // Adjust the types we're converting from via the array-to-pointer
2436 // conversion, if we need to.
2437 if (SCS1.First == ICK_Array_To_Pointer)
2438 FromType1 = Context.getArrayDecayedType(FromType1);
2439 if (SCS2.First == ICK_Array_To_Pointer)
2440 FromType2 = Context.getArrayDecayedType(FromType2);
2441
2442 // Canonicalize all of the types.
2443 FromType1 = Context.getCanonicalType(FromType1);
2444 ToType1 = Context.getCanonicalType(ToType1);
2445 FromType2 = Context.getCanonicalType(FromType2);
2446 ToType2 = Context.getCanonicalType(ToType2);
2447
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002448 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002449 //
2450 // If class B is derived directly or indirectly from class A and
2451 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002452 //
2453 // For Objective-C, we let A, B, and C also be Objective-C
2454 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002455
2456 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002457 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002458 SCS2.Second == ICK_Pointer_Conversion &&
2459 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2460 FromType1->isPointerType() && FromType2->isPointerType() &&
2461 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002462 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002463 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002464 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002465 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002466 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002467 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002468 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002469 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002470
John McCall8b07ec22010-05-15 11:32:37 +00002471 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2472 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2473 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2474 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002475
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002476 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002477 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2478 if (IsDerivedFrom(ToPointee1, ToPointee2))
2479 return ImplicitConversionSequence::Better;
2480 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2481 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002482
2483 if (ToIface1 && ToIface2) {
2484 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2485 return ImplicitConversionSequence::Better;
2486 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2487 return ImplicitConversionSequence::Worse;
2488 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002489 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002490
2491 // -- conversion of B* to A* is better than conversion of C* to A*,
2492 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2493 if (IsDerivedFrom(FromPointee2, FromPointee1))
2494 return ImplicitConversionSequence::Better;
2495 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2496 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002497
Douglas Gregor237f96c2008-11-26 23:31:11 +00002498 if (FromIface1 && FromIface2) {
2499 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2500 return ImplicitConversionSequence::Better;
2501 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2502 return ImplicitConversionSequence::Worse;
2503 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002504 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002505 }
2506
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002507 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002508 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2509 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2510 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2511 const MemberPointerType * FromMemPointer1 =
2512 FromType1->getAs<MemberPointerType>();
2513 const MemberPointerType * ToMemPointer1 =
2514 ToType1->getAs<MemberPointerType>();
2515 const MemberPointerType * FromMemPointer2 =
2516 FromType2->getAs<MemberPointerType>();
2517 const MemberPointerType * ToMemPointer2 =
2518 ToType2->getAs<MemberPointerType>();
2519 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2520 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2521 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2522 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2523 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2524 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2525 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2526 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002527 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002528 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2529 if (IsDerivedFrom(ToPointee1, ToPointee2))
2530 return ImplicitConversionSequence::Worse;
2531 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2532 return ImplicitConversionSequence::Better;
2533 }
2534 // conversion of B::* to C::* is better than conversion of A::* to C::*
2535 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2536 if (IsDerivedFrom(FromPointee1, FromPointee2))
2537 return ImplicitConversionSequence::Better;
2538 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2539 return ImplicitConversionSequence::Worse;
2540 }
2541 }
2542
Douglas Gregor5ab11652010-04-17 22:01:05 +00002543 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002544 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002545 // -- binding of an expression of type C to a reference of type
2546 // B& is better than binding an expression of type C to a
2547 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002548 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2549 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002550 if (IsDerivedFrom(ToType1, ToType2))
2551 return ImplicitConversionSequence::Better;
2552 else if (IsDerivedFrom(ToType2, ToType1))
2553 return ImplicitConversionSequence::Worse;
2554 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002555
Douglas Gregor2fe98832008-11-03 19:09:14 +00002556 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002557 // -- binding of an expression of type B to a reference of type
2558 // A& is better than binding an expression of type C to a
2559 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002560 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2561 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002562 if (IsDerivedFrom(FromType2, FromType1))
2563 return ImplicitConversionSequence::Better;
2564 else if (IsDerivedFrom(FromType1, FromType2))
2565 return ImplicitConversionSequence::Worse;
2566 }
2567 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002568
Douglas Gregor5c407d92008-10-23 00:40:37 +00002569 return ImplicitConversionSequence::Indistinguishable;
2570}
2571
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002572/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2573/// determine whether they are reference-related,
2574/// reference-compatible, reference-compatible with added
2575/// qualification, or incompatible, for use in C++ initialization by
2576/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2577/// type, and the first type (T1) is the pointee type of the reference
2578/// type being initialized.
2579Sema::ReferenceCompareResult
2580Sema::CompareReferenceRelationship(SourceLocation Loc,
2581 QualType OrigT1, QualType OrigT2,
2582 bool& DerivedToBase) {
2583 assert(!OrigT1->isReferenceType() &&
2584 "T1 must be the pointee type of the reference type");
2585 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2586
2587 QualType T1 = Context.getCanonicalType(OrigT1);
2588 QualType T2 = Context.getCanonicalType(OrigT2);
2589 Qualifiers T1Quals, T2Quals;
2590 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2591 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2592
2593 // C++ [dcl.init.ref]p4:
2594 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2595 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2596 // T1 is a base class of T2.
2597 if (UnqualT1 == UnqualT2)
2598 DerivedToBase = false;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002599 else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002600 IsDerivedFrom(UnqualT2, UnqualT1))
2601 DerivedToBase = true;
2602 else
2603 return Ref_Incompatible;
2604
2605 // At this point, we know that T1 and T2 are reference-related (at
2606 // least).
2607
2608 // If the type is an array type, promote the element qualifiers to the type
2609 // for comparison.
2610 if (isa<ArrayType>(T1) && T1Quals)
2611 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2612 if (isa<ArrayType>(T2) && T2Quals)
2613 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2614
2615 // C++ [dcl.init.ref]p4:
2616 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2617 // reference-related to T2 and cv1 is the same cv-qualification
2618 // as, or greater cv-qualification than, cv2. For purposes of
2619 // overload resolution, cases for which cv1 is greater
2620 // cv-qualification than cv2 are identified as
2621 // reference-compatible with added qualification (see 13.3.3.2).
2622 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2623 return Ref_Compatible;
2624 else if (T1.isMoreQualifiedThan(T2))
2625 return Ref_Compatible_With_Added_Qualification;
2626 else
2627 return Ref_Related;
2628}
2629
2630/// \brief Compute an implicit conversion sequence for reference
2631/// initialization.
2632static ImplicitConversionSequence
2633TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2634 SourceLocation DeclLoc,
2635 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002636 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002637 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2638
2639 // Most paths end in a failed conversion.
2640 ImplicitConversionSequence ICS;
2641 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2642
2643 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2644 QualType T2 = Init->getType();
2645
2646 // If the initializer is the address of an overloaded function, try
2647 // to resolve the overloaded function. If all goes well, T2 is the
2648 // type of the resulting function.
2649 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2650 DeclAccessPair Found;
2651 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2652 false, Found))
2653 T2 = Fn->getType();
2654 }
2655
2656 // Compute some basic properties of the types and the initializer.
2657 bool isRValRef = DeclType->isRValueReferenceType();
2658 bool DerivedToBase = false;
Douglas Gregoradc7a702010-04-16 17:45:54 +00002659 Expr::isLvalueResult InitLvalue = Init->isLvalue(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002660 Sema::ReferenceCompareResult RefRelationship
2661 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
2662
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002663
2664 // C++ [over.ics.ref]p3:
2665 // Except for an implicit object parameter, for which see 13.3.1,
2666 // a standard conversion sequence cannot be formed if it requires
2667 // binding an lvalue reference to non-const to an rvalue or
2668 // binding an rvalue reference to an lvalue.
Douglas Gregor870f3742010-04-18 09:22:00 +00002669 //
2670 // FIXME: DPG doesn't trust this code. It seems far too early to
2671 // abort because of a binding of an rvalue reference to an lvalue.
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002672 if (isRValRef && InitLvalue == Expr::LV_Valid)
2673 return ICS;
2674
Douglas Gregor870f3742010-04-18 09:22:00 +00002675 // C++0x [dcl.init.ref]p16:
2676 // A reference to type "cv1 T1" is initialized by an expression
2677 // of type "cv2 T2" as follows:
2678
2679 // -- If the initializer expression
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002680 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2681 // reference-compatible with "cv2 T2," or
2682 //
2683 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2684 if (InitLvalue == Expr::LV_Valid &&
2685 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2686 // C++ [over.ics.ref]p1:
2687 // When a parameter of reference type binds directly (8.5.3)
2688 // to an argument expression, the implicit conversion sequence
2689 // is the identity conversion, unless the argument expression
2690 // has a type that is a derived class of the parameter type,
2691 // in which case the implicit conversion sequence is a
2692 // derived-to-base Conversion (13.3.3.1).
2693 ICS.setStandard();
2694 ICS.Standard.First = ICK_Identity;
2695 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2696 ICS.Standard.Third = ICK_Identity;
2697 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2698 ICS.Standard.setToType(0, T2);
2699 ICS.Standard.setToType(1, T1);
2700 ICS.Standard.setToType(2, T1);
2701 ICS.Standard.ReferenceBinding = true;
2702 ICS.Standard.DirectBinding = true;
2703 ICS.Standard.RRefBinding = false;
2704 ICS.Standard.CopyConstructor = 0;
2705
2706 // Nothing more to do: the inaccessibility/ambiguity check for
2707 // derived-to-base conversions is suppressed when we're
2708 // computing the implicit conversion sequence (C++
2709 // [over.best.ics]p2).
2710 return ICS;
2711 }
2712
2713 // -- has a class type (i.e., T2 is a class type), where T1 is
2714 // not reference-related to T2, and can be implicitly
2715 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2716 // is reference-compatible with "cv3 T3" 92) (this
2717 // conversion is selected by enumerating the applicable
2718 // conversion functions (13.3.1.6) and choosing the best
2719 // one through overload resolution (13.3)),
2720 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
2721 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2722 RefRelationship == Sema::Ref_Incompatible) {
2723 CXXRecordDecl *T2RecordDecl
2724 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2725
2726 OverloadCandidateSet CandidateSet(DeclLoc);
2727 const UnresolvedSetImpl *Conversions
2728 = T2RecordDecl->getVisibleConversionFunctions();
2729 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2730 E = Conversions->end(); I != E; ++I) {
2731 NamedDecl *D = *I;
2732 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2733 if (isa<UsingShadowDecl>(D))
2734 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2735
2736 FunctionTemplateDecl *ConvTemplate
2737 = dyn_cast<FunctionTemplateDecl>(D);
2738 CXXConversionDecl *Conv;
2739 if (ConvTemplate)
2740 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2741 else
2742 Conv = cast<CXXConversionDecl>(D);
2743
2744 // If the conversion function doesn't return a reference type,
2745 // it can't be considered for this conversion.
2746 if (Conv->getConversionType()->isLValueReferenceType() &&
2747 (AllowExplicit || !Conv->isExplicit())) {
2748 if (ConvTemplate)
2749 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2750 Init, DeclType, CandidateSet);
2751 else
2752 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2753 DeclType, CandidateSet);
2754 }
2755 }
2756
2757 OverloadCandidateSet::iterator Best;
2758 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2759 case OR_Success:
2760 // C++ [over.ics.ref]p1:
2761 //
2762 // [...] If the parameter binds directly to the result of
2763 // applying a conversion function to the argument
2764 // expression, the implicit conversion sequence is a
2765 // user-defined conversion sequence (13.3.3.1.2), with the
2766 // second standard conversion sequence either an identity
2767 // conversion or, if the conversion function returns an
2768 // entity of a type that is a derived class of the parameter
2769 // type, a derived-to-base Conversion.
2770 if (!Best->FinalConversion.DirectBinding)
2771 break;
2772
2773 ICS.setUserDefined();
2774 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2775 ICS.UserDefined.After = Best->FinalConversion;
2776 ICS.UserDefined.ConversionFunction = Best->Function;
2777 ICS.UserDefined.EllipsisConversion = false;
2778 assert(ICS.UserDefined.After.ReferenceBinding &&
2779 ICS.UserDefined.After.DirectBinding &&
2780 "Expected a direct reference binding!");
2781 return ICS;
2782
2783 case OR_Ambiguous:
2784 ICS.setAmbiguous();
2785 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2786 Cand != CandidateSet.end(); ++Cand)
2787 if (Cand->Viable)
2788 ICS.Ambiguous.addConversion(Cand->Function);
2789 return ICS;
2790
2791 case OR_No_Viable_Function:
2792 case OR_Deleted:
2793 // There was no suitable conversion, or we found a deleted
2794 // conversion; continue with other checks.
2795 break;
2796 }
2797 }
2798
2799 // -- Otherwise, the reference shall be to a non-volatile const
2800 // type (i.e., cv1 shall be const), or the reference shall be an
2801 // rvalue reference and the initializer expression shall be an rvalue.
Douglas Gregor870f3742010-04-18 09:22:00 +00002802 //
2803 // We actually handle one oddity of C++ [over.ics.ref] at this
2804 // point, which is that, due to p2 (which short-circuits reference
2805 // binding by only attempting a simple conversion for non-direct
2806 // bindings) and p3's strange wording, we allow a const volatile
2807 // reference to bind to an rvalue. Hence the check for the presence
2808 // of "const" rather than checking for "const" being the only
2809 // qualifier.
2810 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002811 return ICS;
2812
Douglas Gregorf93df192010-04-18 08:46:23 +00002813 // -- if T2 is a class type and
2814 // -- the initializer expression is an rvalue and "cv1 T1"
2815 // is reference-compatible with "cv2 T2," or
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002816 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002817 // -- T1 is not reference-related to T2 and the initializer
2818 // expression can be implicitly converted to an rvalue
2819 // of type "cv3 T3" (this conversion is selected by
2820 // enumerating the applicable conversion functions
2821 // (13.3.1.6) and choosing the best one through overload
2822 // resolution (13.3)),
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002823 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002824 // then the reference is bound to the initializer
2825 // expression rvalue in the first case and to the object
2826 // that is the result of the conversion in the second case
2827 // (or, in either case, to the appropriate base class
2828 // subobject of the object).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002829 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002830 // We're only checking the first case here, which is a direct
2831 // binding in C++0x but not in C++03.
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002832 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
2833 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2834 ICS.setStandard();
2835 ICS.Standard.First = ICK_Identity;
2836 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2837 ICS.Standard.Third = ICK_Identity;
2838 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2839 ICS.Standard.setToType(0, T2);
2840 ICS.Standard.setToType(1, T1);
2841 ICS.Standard.setToType(2, T1);
2842 ICS.Standard.ReferenceBinding = true;
Douglas Gregorf93df192010-04-18 08:46:23 +00002843 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002844 ICS.Standard.RRefBinding = isRValRef;
2845 ICS.Standard.CopyConstructor = 0;
2846 return ICS;
2847 }
2848
2849 // -- Otherwise, a temporary of type "cv1 T1" is created and
2850 // initialized from the initializer expression using the
2851 // rules for a non-reference copy initialization (8.5). The
2852 // reference is then bound to the temporary. If T1 is
2853 // reference-related to T2, cv1 must be the same
2854 // cv-qualification as, or greater cv-qualification than,
2855 // cv2; otherwise, the program is ill-formed.
2856 if (RefRelationship == Sema::Ref_Related) {
2857 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2858 // we would be reference-compatible or reference-compatible with
2859 // added qualification. But that wasn't the case, so the reference
2860 // initialization fails.
2861 return ICS;
2862 }
2863
2864 // If at least one of the types is a class type, the types are not
2865 // related, and we aren't allowed any user conversions, the
2866 // reference binding fails. This case is important for breaking
2867 // recursion, since TryImplicitConversion below will attempt to
2868 // create a temporary through the use of a copy constructor.
2869 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2870 (T1->isRecordType() || T2->isRecordType()))
2871 return ICS;
2872
2873 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002874 // When a parameter of reference type is not bound directly to
2875 // an argument expression, the conversion sequence is the one
2876 // required to convert the argument expression to the
2877 // underlying type of the reference according to
2878 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2879 // to copy-initializing a temporary of the underlying type with
2880 // the argument expression. Any difference in top-level
2881 // cv-qualification is subsumed by the initialization itself
2882 // and does not constitute a conversion.
2883 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2884 /*AllowExplicit=*/false,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002885 /*InOverloadResolution=*/false);
2886
2887 // Of course, that's still a reference binding.
2888 if (ICS.isStandard()) {
2889 ICS.Standard.ReferenceBinding = true;
2890 ICS.Standard.RRefBinding = isRValRef;
2891 } else if (ICS.isUserDefined()) {
2892 ICS.UserDefined.After.ReferenceBinding = true;
2893 ICS.UserDefined.After.RRefBinding = isRValRef;
2894 }
2895 return ICS;
2896}
2897
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002898/// TryCopyInitialization - Try to copy-initialize a value of type
2899/// ToType from the expression From. Return the implicit conversion
2900/// sequence required to pass this argument, which may be a bad
2901/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002902/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00002903/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002904static ImplicitConversionSequence
2905TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00002906 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002907 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002908 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002909 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002910 /*FIXME:*/From->getLocStart(),
2911 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002912 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002913
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002914 return S.TryImplicitConversion(From, ToType,
2915 SuppressUserConversions,
2916 /*AllowExplicit=*/false,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002917 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002918}
2919
Douglas Gregor436424c2008-11-18 23:14:02 +00002920/// TryObjectArgumentInitialization - Try to initialize the object
2921/// parameter of the given member function (@c Method) from the
2922/// expression @p From.
2923ImplicitConversionSequence
John McCall47000992010-01-14 03:28:57 +00002924Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall6e9f8f62009-12-03 04:06:58 +00002925 CXXMethodDecl *Method,
2926 CXXRecordDecl *ActingContext) {
2927 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002928 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2929 // const volatile object.
2930 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2931 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2932 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002933
2934 // Set up the conversion sequence as a "bad" conversion, to allow us
2935 // to exit early.
2936 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00002937
2938 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00002939 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002940 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002941 FromType = PT->getPointeeType();
2942
2943 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002944
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002945 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002946 // where X is the class of which the function is a member
2947 // (C++ [over.match.funcs]p4). However, when finding an implicit
2948 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002949 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002950 // (C++ [over.match.funcs]p5). We perform a simplified version of
2951 // reference binding here, that allows class rvalues to bind to
2952 // non-constant references.
2953
2954 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2955 // with the implicit object parameter (C++ [over.match.funcs]p5).
2956 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002957 if (ImplicitParamType.getCVRQualifiers()
2958 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00002959 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00002960 ICS.setBad(BadConversionSequence::bad_qualifiers,
2961 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002962 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002963 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002964
2965 // Check that we have either the same type or a derived type. It
2966 // affects the conversion rank.
2967 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00002968 ImplicitConversionKind SecondKind;
2969 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2970 SecondKind = ICK_Identity;
2971 } else if (IsDerivedFrom(FromType, ClassType))
2972 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00002973 else {
John McCall65eb8792010-02-25 01:37:24 +00002974 ICS.setBad(BadConversionSequence::unrelated_class,
2975 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002976 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002977 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002978
2979 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00002980 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00002981 ICS.Standard.setAsIdentityConversion();
2982 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00002983 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002984 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002985 ICS.Standard.ReferenceBinding = true;
2986 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002987 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002988 return ICS;
2989}
2990
2991/// PerformObjectArgumentInitialization - Perform initialization of
2992/// the implicit object parameter for the given Method with the given
2993/// expression.
2994bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002995Sema::PerformObjectArgumentInitialization(Expr *&From,
2996 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002997 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002998 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002999 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003000 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003001 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003002
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003003 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003004 FromRecordType = PT->getPointeeType();
3005 DestType = Method->getThisType(Context);
3006 } else {
3007 FromRecordType = From->getType();
3008 DestType = ImplicitParamRecordType;
3009 }
3010
John McCall6e9f8f62009-12-03 04:06:58 +00003011 // Note that we always use the true parent context when performing
3012 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003013 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00003014 = TryObjectArgumentInitialization(From->getType(), Method,
3015 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00003016 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00003017 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003018 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003019 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003020
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003021 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00003022 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00003023
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003024 if (!Context.hasSameType(From->getType(), DestType))
Anders Carlsson0c509ee2010-04-24 16:57:13 +00003025 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
3026 /*isLvalue=*/!From->getType()->isPointerType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003027 return false;
3028}
3029
Douglas Gregor5fb53972009-01-14 15:45:31 +00003030/// TryContextuallyConvertToBool - Attempt to contextually convert the
3031/// expression From to bool (C++0x [conv]p3).
3032ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003033 // FIXME: This is pretty broken.
Mike Stump11289f42009-09-09 15:08:12 +00003034 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003035 // FIXME: Are these flags correct?
3036 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003037 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00003038 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003039}
3040
3041/// PerformContextuallyConvertToBool - Perform a contextual conversion
3042/// of the expression From to bool (C++0x [conv]p3).
3043bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
3044 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00003045 if (!ICS.isBad())
3046 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003047
Fariborz Jahanian76197412009-11-18 18:26:29 +00003048 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003049 return Diag(From->getSourceRange().getBegin(),
3050 diag::err_typecheck_bool_condition)
3051 << From->getType() << From->getSourceRange();
3052 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003053}
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003054
3055/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3056/// expression From to 'id'.
3057ImplicitConversionSequence Sema::TryContextuallyConvertToObjCId(Expr *From) {
John McCall8b07ec22010-05-15 11:32:37 +00003058 QualType Ty = Context.getObjCIdType();
3059 return TryImplicitConversion(From, Ty,
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003060 // FIXME: Are these flags correct?
3061 /*SuppressUserConversions=*/false,
3062 /*AllowExplicit=*/true,
3063 /*InOverloadResolution=*/false);
3064}
3065
3066/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3067/// of the expression From to 'id'.
3068bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCall8b07ec22010-05-15 11:32:37 +00003069 QualType Ty = Context.getObjCIdType();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003070 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(From);
3071 if (!ICS.isBad())
3072 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3073 return true;
3074}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003075
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003076/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003077/// candidate functions, using the given function call arguments. If
3078/// @p SuppressUserConversions, then don't allow user-defined
3079/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003080///
3081/// \para PartialOverloading true if we are performing "partial" overloading
3082/// based on an incomplete set of function arguments. This feature is used by
3083/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003084void
3085Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003086 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003087 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003088 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003089 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003090 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003091 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003092 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003093 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003094 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003095 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003096
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003097 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003098 if (!isa<CXXConstructorDecl>(Method)) {
3099 // If we get here, it's because we're calling a member function
3100 // that is named without a member access expression (e.g.,
3101 // "this->f") that was either written explicitly or created
3102 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003103 // function, e.g., X::f(). We use an empty type for the implied
3104 // object argument (C++ [over.call.func]p3), and the acting context
3105 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003106 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00003107 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003108 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003109 return;
3110 }
3111 // We treat a constructor like a non-member function, since its object
3112 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003113 }
3114
Douglas Gregorff7028a2009-11-13 23:59:09 +00003115 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003116 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003117
Douglas Gregor27381f32009-11-23 12:27:39 +00003118 // Overload resolution is always an unevaluated context.
3119 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3120
Douglas Gregorffe14e32009-11-14 01:20:54 +00003121 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3122 // C++ [class.copy]p3:
3123 // A member function template is never instantiated to perform the copy
3124 // of a class object to an object of its class type.
3125 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3126 if (NumArgs == 1 &&
3127 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003128 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3129 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003130 return;
3131 }
3132
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003133 // Add this candidate
3134 CandidateSet.push_back(OverloadCandidate());
3135 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003136 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003137 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003138 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003139 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003140 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003141
3142 unsigned NumArgsInProto = Proto->getNumArgs();
3143
3144 // (C++ 13.3.2p2): A candidate function having fewer than m
3145 // parameters is viable only if it has an ellipsis in its parameter
3146 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00003147 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3148 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003149 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003150 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003151 return;
3152 }
3153
3154 // (C++ 13.3.2p2): A candidate function having more than m parameters
3155 // is viable only if the (m+1)st parameter has a default argument
3156 // (8.3.6). For the purposes of overload resolution, the
3157 // parameter list is truncated on the right, so that there are
3158 // exactly m parameters.
3159 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003160 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003161 // Not enough arguments.
3162 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003163 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003164 return;
3165 }
3166
3167 // Determine the implicit conversion sequences for each of the
3168 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003169 Candidate.Conversions.resize(NumArgs);
3170 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3171 if (ArgIdx < NumArgsInProto) {
3172 // (C++ 13.3.2p3): for F to be a viable function, there shall
3173 // exist for each argument an implicit conversion sequence
3174 // (13.3.3.1) that converts that argument to the corresponding
3175 // parameter of F.
3176 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003177 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003178 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00003179 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003180 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003181 if (Candidate.Conversions[ArgIdx].isBad()) {
3182 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003183 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003184 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003185 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003186 } else {
3187 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3188 // argument for which there is no corresponding parameter is
3189 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003190 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003191 }
3192 }
3193}
3194
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003195/// \brief Add all of the function declarations in the given function set to
3196/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003197void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003198 Expr **Args, unsigned NumArgs,
3199 OverloadCandidateSet& CandidateSet,
3200 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003201 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003202 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3203 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003204 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003205 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003206 cast<CXXMethodDecl>(FD)->getParent(),
3207 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003208 CandidateSet, SuppressUserConversions);
3209 else
John McCalla0296f72010-03-19 07:35:19 +00003210 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003211 SuppressUserConversions);
3212 } else {
John McCalla0296f72010-03-19 07:35:19 +00003213 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003214 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3215 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003216 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003217 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003218 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003219 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003220 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003221 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003222 else
John McCalla0296f72010-03-19 07:35:19 +00003223 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003224 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003225 Args, NumArgs, CandidateSet,
3226 SuppressUserConversions);
3227 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003228 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003229}
3230
John McCallf0f1cf02009-11-17 07:50:12 +00003231/// AddMethodCandidate - Adds a named decl (which is some kind of
3232/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003233void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003234 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00003235 Expr **Args, unsigned NumArgs,
3236 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003237 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003238 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003239 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003240
3241 if (isa<UsingShadowDecl>(Decl))
3242 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3243
3244 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3245 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3246 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003247 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3248 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003249 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003250 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003251 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003252 } else {
John McCalla0296f72010-03-19 07:35:19 +00003253 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00003254 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003255 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003256 }
3257}
3258
Douglas Gregor436424c2008-11-18 23:14:02 +00003259/// AddMethodCandidate - Adds the given C++ member function to the set
3260/// of candidate functions, using the given function call arguments
3261/// and the object argument (@c Object). For example, in a call
3262/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3263/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3264/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003265/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003266void
John McCalla0296f72010-03-19 07:35:19 +00003267Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003268 CXXRecordDecl *ActingContext, QualType ObjectType,
3269 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003270 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003271 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003272 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003273 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003274 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003275 assert(!isa<CXXConstructorDecl>(Method) &&
3276 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003277
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003278 if (!CandidateSet.isNewCandidate(Method))
3279 return;
3280
Douglas Gregor27381f32009-11-23 12:27:39 +00003281 // Overload resolution is always an unevaluated context.
3282 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3283
Douglas Gregor436424c2008-11-18 23:14:02 +00003284 // Add this candidate
3285 CandidateSet.push_back(OverloadCandidate());
3286 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003287 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003288 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003289 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003290 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003291
3292 unsigned NumArgsInProto = Proto->getNumArgs();
3293
3294 // (C++ 13.3.2p2): A candidate function having fewer than m
3295 // parameters is viable only if it has an ellipsis in its parameter
3296 // list (8.3.5).
3297 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3298 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003299 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003300 return;
3301 }
3302
3303 // (C++ 13.3.2p2): A candidate function having more than m parameters
3304 // is viable only if the (m+1)st parameter has a default argument
3305 // (8.3.6). For the purposes of overload resolution, the
3306 // parameter list is truncated on the right, so that there are
3307 // exactly m parameters.
3308 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3309 if (NumArgs < MinRequiredArgs) {
3310 // Not enough arguments.
3311 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003312 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003313 return;
3314 }
3315
3316 Candidate.Viable = true;
3317 Candidate.Conversions.resize(NumArgs + 1);
3318
John McCall6e9f8f62009-12-03 04:06:58 +00003319 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003320 // The implicit object argument is ignored.
3321 Candidate.IgnoreObjectArgument = true;
3322 else {
3323 // Determine the implicit conversion sequence for the object
3324 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00003325 Candidate.Conversions[0]
3326 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003327 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003328 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003329 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003330 return;
3331 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003332 }
3333
3334 // Determine the implicit conversion sequences for each of the
3335 // arguments.
3336 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3337 if (ArgIdx < NumArgsInProto) {
3338 // (C++ 13.3.2p3): for F to be a viable function, there shall
3339 // exist for each argument an implicit conversion sequence
3340 // (13.3.3.1) that converts that argument to the corresponding
3341 // parameter of F.
3342 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003343 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003344 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003345 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003346 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003347 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003348 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003349 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003350 break;
3351 }
3352 } else {
3353 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3354 // argument for which there is no corresponding parameter is
3355 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003356 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003357 }
3358 }
3359}
Douglas Gregor3626a5c2010-05-08 17:41:32 +00003360
Douglas Gregor97628d62009-08-21 00:16:32 +00003361/// \brief Add a C++ member function template as a candidate to the candidate
3362/// set, using template argument deduction to produce an appropriate member
3363/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003364void
Douglas Gregor97628d62009-08-21 00:16:32 +00003365Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003366 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003367 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003368 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003369 QualType ObjectType,
3370 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003371 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003372 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003373 if (!CandidateSet.isNewCandidate(MethodTmpl))
3374 return;
3375
Douglas Gregor97628d62009-08-21 00:16:32 +00003376 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003377 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003378 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003379 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003380 // candidate functions in the usual way.113) A given name can refer to one
3381 // or more function templates and also to a set of overloaded non-template
3382 // functions. In such a case, the candidate functions generated from each
3383 // function template are combined with the set of non-template candidate
3384 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003385 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003386 FunctionDecl *Specialization = 0;
3387 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003388 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003389 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003390 CandidateSet.push_back(OverloadCandidate());
3391 OverloadCandidate &Candidate = CandidateSet.back();
3392 Candidate.FoundDecl = FoundDecl;
3393 Candidate.Function = MethodTmpl->getTemplatedDecl();
3394 Candidate.Viable = false;
3395 Candidate.FailureKind = ovl_fail_bad_deduction;
3396 Candidate.IsSurrogate = false;
3397 Candidate.IgnoreObjectArgument = false;
3398 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3399 Info);
3400 return;
3401 }
Mike Stump11289f42009-09-09 15:08:12 +00003402
Douglas Gregor97628d62009-08-21 00:16:32 +00003403 // Add the function template specialization produced by template argument
3404 // deduction as a candidate.
3405 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003406 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003407 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003408 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003409 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003410 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003411}
3412
Douglas Gregor05155d82009-08-21 23:19:43 +00003413/// \brief Add a C++ function template specialization as a candidate
3414/// in the candidate set, using template argument deduction to produce
3415/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003416void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003417Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003418 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003419 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003420 Expr **Args, unsigned NumArgs,
3421 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003422 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003423 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3424 return;
3425
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003426 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003427 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003428 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003429 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003430 // candidate functions in the usual way.113) A given name can refer to one
3431 // or more function templates and also to a set of overloaded non-template
3432 // functions. In such a case, the candidate functions generated from each
3433 // function template are combined with the set of non-template candidate
3434 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003435 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003436 FunctionDecl *Specialization = 0;
3437 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003438 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003439 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003440 CandidateSet.push_back(OverloadCandidate());
3441 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003442 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003443 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3444 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003445 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003446 Candidate.IsSurrogate = false;
3447 Candidate.IgnoreObjectArgument = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003448 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3449 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003450 return;
3451 }
Mike Stump11289f42009-09-09 15:08:12 +00003452
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003453 // Add the function template specialization produced by template argument
3454 // deduction as a candidate.
3455 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003456 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003457 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003458}
Mike Stump11289f42009-09-09 15:08:12 +00003459
Douglas Gregora1f013e2008-11-07 22:36:19 +00003460/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003461/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003462/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003463/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003464/// (which may or may not be the same type as the type that the
3465/// conversion function produces).
3466void
3467Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003468 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003469 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003470 Expr *From, QualType ToType,
3471 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003472 assert(!Conversion->getDescribedFunctionTemplate() &&
3473 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003474 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003475 if (!CandidateSet.isNewCandidate(Conversion))
3476 return;
3477
Douglas Gregor27381f32009-11-23 12:27:39 +00003478 // Overload resolution is always an unevaluated context.
3479 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3480
Douglas Gregora1f013e2008-11-07 22:36:19 +00003481 // Add this candidate
3482 CandidateSet.push_back(OverloadCandidate());
3483 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003484 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003485 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003486 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003487 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003488 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003489 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003490 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003491
Douglas Gregor436424c2008-11-18 23:14:02 +00003492 // Determine the implicit conversion sequence for the implicit
3493 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00003494 Candidate.Viable = true;
3495 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00003496 Candidate.Conversions[0]
3497 = TryObjectArgumentInitialization(From->getType(), Conversion,
3498 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00003499 // Conversion functions to a different type in the base class is visible in
3500 // the derived class. So, a derived to base conversion should not participate
3501 // in overload resolution.
3502 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
3503 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00003504 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003505 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003506 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003507 return;
3508 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003509
3510 // We won't go through a user-define type conversion function to convert a
3511 // derived to base as such conversions are given Conversion Rank. They only
3512 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3513 QualType FromCanon
3514 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3515 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3516 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3517 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003518 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003519 return;
3520 }
3521
Douglas Gregora1f013e2008-11-07 22:36:19 +00003522 // To determine what the conversion from the result of calling the
3523 // conversion function to the type we're eventually trying to
3524 // convert to (ToType), we need to synthesize a call to the
3525 // conversion function and attempt copy initialization from it. This
3526 // makes sure that we get the right semantics with respect to
3527 // lvalues/rvalues and the type. Fortunately, we can allocate this
3528 // call on the stack and we don't need its arguments to be
3529 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003530 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003531 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00003532 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00003533 CastExpr::CK_FunctionToPointerDecay,
Anders Carlsson0c509ee2010-04-24 16:57:13 +00003534 &ConversionRef, CXXBaseSpecifierArray(), false);
Mike Stump11289f42009-09-09 15:08:12 +00003535
3536 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003537 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3538 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00003539 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003540 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003541 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003542 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003543 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003544 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003545 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003546
John McCall0d1da222010-01-12 00:44:57 +00003547 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003548 case ImplicitConversionSequence::StandardConversion:
3549 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003550
3551 // C++ [over.ics.user]p3:
3552 // If the user-defined conversion is specified by a specialization of a
3553 // conversion function template, the second standard conversion sequence
3554 // shall have exact match rank.
3555 if (Conversion->getPrimaryTemplate() &&
3556 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3557 Candidate.Viable = false;
3558 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3559 }
3560
Douglas Gregora1f013e2008-11-07 22:36:19 +00003561 break;
3562
3563 case ImplicitConversionSequence::BadConversion:
3564 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003565 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003566 break;
3567
3568 default:
Mike Stump11289f42009-09-09 15:08:12 +00003569 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003570 "Can only end up with a standard conversion sequence or failure");
3571 }
3572}
3573
Douglas Gregor05155d82009-08-21 23:19:43 +00003574/// \brief Adds a conversion function template specialization
3575/// candidate to the overload set, using template argument deduction
3576/// to deduce the template arguments of the conversion function
3577/// template from the type that we are converting to (C++
3578/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003579void
Douglas Gregor05155d82009-08-21 23:19:43 +00003580Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003581 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003582 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003583 Expr *From, QualType ToType,
3584 OverloadCandidateSet &CandidateSet) {
3585 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3586 "Only conversion function templates permitted here");
3587
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003588 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3589 return;
3590
John McCallbc077cf2010-02-08 23:07:23 +00003591 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003592 CXXConversionDecl *Specialization = 0;
3593 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003594 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003595 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003596 CandidateSet.push_back(OverloadCandidate());
3597 OverloadCandidate &Candidate = CandidateSet.back();
3598 Candidate.FoundDecl = FoundDecl;
3599 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3600 Candidate.Viable = false;
3601 Candidate.FailureKind = ovl_fail_bad_deduction;
3602 Candidate.IsSurrogate = false;
3603 Candidate.IgnoreObjectArgument = false;
3604 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3605 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00003606 return;
3607 }
Mike Stump11289f42009-09-09 15:08:12 +00003608
Douglas Gregor05155d82009-08-21 23:19:43 +00003609 // Add the conversion function template specialization produced by
3610 // template argument deduction as a candidate.
3611 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003612 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00003613 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003614}
3615
Douglas Gregorab7897a2008-11-19 22:57:39 +00003616/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3617/// converts the given @c Object to a function pointer via the
3618/// conversion function @c Conversion, and then attempts to call it
3619/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3620/// the type of function that we'll eventually be calling.
3621void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003622 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003623 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003624 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00003625 QualType ObjectType,
3626 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00003627 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003628 if (!CandidateSet.isNewCandidate(Conversion))
3629 return;
3630
Douglas Gregor27381f32009-11-23 12:27:39 +00003631 // Overload resolution is always an unevaluated context.
3632 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3633
Douglas Gregorab7897a2008-11-19 22:57:39 +00003634 CandidateSet.push_back(OverloadCandidate());
3635 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003636 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003637 Candidate.Function = 0;
3638 Candidate.Surrogate = Conversion;
3639 Candidate.Viable = true;
3640 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003641 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003642 Candidate.Conversions.resize(NumArgs + 1);
3643
3644 // Determine the implicit conversion sequence for the implicit
3645 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003646 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00003647 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003648 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003649 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003650 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00003651 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003652 return;
3653 }
3654
3655 // The first conversion is actually a user-defined conversion whose
3656 // first conversion is ObjectInit's standard conversion (which is
3657 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00003658 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003659 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003660 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003661 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00003662 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00003663 = Candidate.Conversions[0].UserDefined.Before;
3664 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3665
Mike Stump11289f42009-09-09 15:08:12 +00003666 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00003667 unsigned NumArgsInProto = Proto->getNumArgs();
3668
3669 // (C++ 13.3.2p2): A candidate function having fewer than m
3670 // parameters is viable only if it has an ellipsis in its parameter
3671 // list (8.3.5).
3672 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3673 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003674 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003675 return;
3676 }
3677
3678 // Function types don't have any default arguments, so just check if
3679 // we have enough arguments.
3680 if (NumArgs < NumArgsInProto) {
3681 // Not enough arguments.
3682 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003683 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003684 return;
3685 }
3686
3687 // Determine the implicit conversion sequences for each of the
3688 // arguments.
3689 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3690 if (ArgIdx < NumArgsInProto) {
3691 // (C++ 13.3.2p3): for F to be a viable function, there shall
3692 // exist for each argument an implicit conversion sequence
3693 // (13.3.3.1) that converts that argument to the corresponding
3694 // parameter of F.
3695 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003696 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003697 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003698 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00003699 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00003700 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003701 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003702 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003703 break;
3704 }
3705 } else {
3706 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3707 // argument for which there is no corresponding parameter is
3708 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003709 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003710 }
3711 }
3712}
3713
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003714/// \brief Add overload candidates for overloaded operators that are
3715/// member functions.
3716///
3717/// Add the overloaded operator candidates that are member functions
3718/// for the operator Op that was used in an operator expression such
3719/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3720/// CandidateSet will store the added overload candidates. (C++
3721/// [over.match.oper]).
3722void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3723 SourceLocation OpLoc,
3724 Expr **Args, unsigned NumArgs,
3725 OverloadCandidateSet& CandidateSet,
3726 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003727 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3728
3729 // C++ [over.match.oper]p3:
3730 // For a unary operator @ with an operand of a type whose
3731 // cv-unqualified version is T1, and for a binary operator @ with
3732 // a left operand of a type whose cv-unqualified version is T1 and
3733 // a right operand of a type whose cv-unqualified version is T2,
3734 // three sets of candidate functions, designated member
3735 // candidates, non-member candidates and built-in candidates, are
3736 // constructed as follows:
3737 QualType T1 = Args[0]->getType();
3738 QualType T2;
3739 if (NumArgs > 1)
3740 T2 = Args[1]->getType();
3741
3742 // -- If T1 is a class type, the set of member candidates is the
3743 // result of the qualified lookup of T1::operator@
3744 // (13.3.1.1.1); otherwise, the set of member candidates is
3745 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003746 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003747 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003748 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003749 return;
Mike Stump11289f42009-09-09 15:08:12 +00003750
John McCall27b18f82009-11-17 02:14:36 +00003751 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3752 LookupQualifiedName(Operators, T1Rec->getDecl());
3753 Operators.suppressDiagnostics();
3754
Mike Stump11289f42009-09-09 15:08:12 +00003755 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003756 OperEnd = Operators.end();
3757 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00003758 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00003759 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00003760 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00003761 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00003762 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003763}
3764
Douglas Gregora11693b2008-11-12 17:17:38 +00003765/// AddBuiltinCandidate - Add a candidate for a built-in
3766/// operator. ResultTy and ParamTys are the result and parameter types
3767/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00003768/// arguments being passed to the candidate. IsAssignmentOperator
3769/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00003770/// operator. NumContextualBoolArguments is the number of arguments
3771/// (at the beginning of the argument list) that will be contextually
3772/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00003773void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00003774 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00003775 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003776 bool IsAssignmentOperator,
3777 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00003778 // Overload resolution is always an unevaluated context.
3779 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3780
Douglas Gregora11693b2008-11-12 17:17:38 +00003781 // Add this candidate
3782 CandidateSet.push_back(OverloadCandidate());
3783 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003784 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00003785 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00003786 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003787 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00003788 Candidate.BuiltinTypes.ResultTy = ResultTy;
3789 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3790 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3791
3792 // Determine the implicit conversion sequences for each of the
3793 // arguments.
3794 Candidate.Viable = true;
3795 Candidate.Conversions.resize(NumArgs);
3796 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00003797 // C++ [over.match.oper]p4:
3798 // For the built-in assignment operators, conversions of the
3799 // left operand are restricted as follows:
3800 // -- no temporaries are introduced to hold the left operand, and
3801 // -- no user-defined conversions are applied to the left
3802 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00003803 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00003804 //
3805 // We block these conversions by turning off user-defined
3806 // conversions, since that is the only way that initialization of
3807 // a reference to a non-class type can occur from something that
3808 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003809 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00003810 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00003811 "Contextual conversion to bool requires bool type");
3812 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3813 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003814 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003815 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00003816 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00003817 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003818 }
John McCall0d1da222010-01-12 00:44:57 +00003819 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003820 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003821 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003822 break;
3823 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003824 }
3825}
3826
3827/// BuiltinCandidateTypeSet - A set of types that will be used for the
3828/// candidate operator functions for built-in operators (C++
3829/// [over.built]). The types are separated into pointer types and
3830/// enumeration types.
3831class BuiltinCandidateTypeSet {
3832 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003833 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00003834
3835 /// PointerTypes - The set of pointer types that will be used in the
3836 /// built-in candidates.
3837 TypeSet PointerTypes;
3838
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003839 /// MemberPointerTypes - The set of member pointer types that will be
3840 /// used in the built-in candidates.
3841 TypeSet MemberPointerTypes;
3842
Douglas Gregora11693b2008-11-12 17:17:38 +00003843 /// EnumerationTypes - The set of enumeration types that will be
3844 /// used in the built-in candidates.
3845 TypeSet EnumerationTypes;
3846
Douglas Gregorcbfbca12010-05-19 03:21:00 +00003847 /// \brief The set of vector types that will be used in the built-in
3848 /// candidates.
3849 TypeSet VectorTypes;
3850
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003851 /// Sema - The semantic analysis instance where we are building the
3852 /// candidate type set.
3853 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003854
Douglas Gregora11693b2008-11-12 17:17:38 +00003855 /// Context - The AST context in which we will build the type sets.
3856 ASTContext &Context;
3857
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003858 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3859 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003860 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003861
3862public:
3863 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003864 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003865
Mike Stump11289f42009-09-09 15:08:12 +00003866 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003867 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003868
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003869 void AddTypesConvertedFrom(QualType Ty,
3870 SourceLocation Loc,
3871 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003872 bool AllowExplicitConversions,
3873 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003874
3875 /// pointer_begin - First pointer type found;
3876 iterator pointer_begin() { return PointerTypes.begin(); }
3877
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003878 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003879 iterator pointer_end() { return PointerTypes.end(); }
3880
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003881 /// member_pointer_begin - First member pointer type found;
3882 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3883
3884 /// member_pointer_end - Past the last member pointer type found;
3885 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3886
Douglas Gregora11693b2008-11-12 17:17:38 +00003887 /// enumeration_begin - First enumeration type found;
3888 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3889
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003890 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003891 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00003892
3893 iterator vector_begin() { return VectorTypes.begin(); }
3894 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregora11693b2008-11-12 17:17:38 +00003895};
3896
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003897/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003898/// the set of pointer types along with any more-qualified variants of
3899/// that type. For example, if @p Ty is "int const *", this routine
3900/// will add "int const *", "int const volatile *", "int const
3901/// restrict *", and "int const volatile restrict *" to the set of
3902/// pointer types. Returns true if the add of @p Ty itself succeeded,
3903/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003904///
3905/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003906bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003907BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3908 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003909
Douglas Gregora11693b2008-11-12 17:17:38 +00003910 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003911 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003912 return false;
3913
John McCall8ccfcb52009-09-24 19:53:00 +00003914 const PointerType *PointerTy = Ty->getAs<PointerType>();
3915 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003916
John McCall8ccfcb52009-09-24 19:53:00 +00003917 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003918 // Don't add qualified variants of arrays. For one, they're not allowed
3919 // (the qualifier would sink to the element type), and for another, the
3920 // only overload situation where it matters is subscript or pointer +- int,
3921 // and those shouldn't have qualifier variants anyway.
3922 if (PointeeTy->isArrayType())
3923 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003924 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003925 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003926 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003927 bool hasVolatile = VisibleQuals.hasVolatile();
3928 bool hasRestrict = VisibleQuals.hasRestrict();
3929
John McCall8ccfcb52009-09-24 19:53:00 +00003930 // Iterate through all strict supersets of BaseCVR.
3931 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3932 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003933 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3934 // in the types.
3935 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3936 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003937 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3938 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003939 }
3940
3941 return true;
3942}
3943
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003944/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3945/// to the set of pointer types along with any more-qualified variants of
3946/// that type. For example, if @p Ty is "int const *", this routine
3947/// will add "int const *", "int const volatile *", "int const
3948/// restrict *", and "int const volatile restrict *" to the set of
3949/// pointer types. Returns true if the add of @p Ty itself succeeded,
3950/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003951///
3952/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003953bool
3954BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3955 QualType Ty) {
3956 // Insert this type.
3957 if (!MemberPointerTypes.insert(Ty))
3958 return false;
3959
John McCall8ccfcb52009-09-24 19:53:00 +00003960 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3961 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003962
John McCall8ccfcb52009-09-24 19:53:00 +00003963 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003964 // Don't add qualified variants of arrays. For one, they're not allowed
3965 // (the qualifier would sink to the element type), and for another, the
3966 // only overload situation where it matters is subscript or pointer +- int,
3967 // and those shouldn't have qualifier variants anyway.
3968 if (PointeeTy->isArrayType())
3969 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003970 const Type *ClassTy = PointerTy->getClass();
3971
3972 // Iterate through all strict supersets of the pointee type's CVR
3973 // qualifiers.
3974 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3975 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3976 if ((CVR | BaseCVR) != CVR) continue;
3977
3978 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3979 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003980 }
3981
3982 return true;
3983}
3984
Douglas Gregora11693b2008-11-12 17:17:38 +00003985/// AddTypesConvertedFrom - Add each of the types to which the type @p
3986/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003987/// primarily interested in pointer types and enumeration types. We also
3988/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003989/// AllowUserConversions is true if we should look at the conversion
3990/// functions of a class type, and AllowExplicitConversions if we
3991/// should also include the explicit conversion functions of a class
3992/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003993void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003994BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003995 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003996 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003997 bool AllowExplicitConversions,
3998 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003999 // Only deal with canonical types.
4000 Ty = Context.getCanonicalType(Ty);
4001
4002 // Look through reference types; they aren't part of the type of an
4003 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004004 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00004005 Ty = RefTy->getPointeeType();
4006
4007 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004008 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00004009
Sebastian Redl65ae2002009-11-05 16:36:20 +00004010 // If we're dealing with an array type, decay to the pointer.
4011 if (Ty->isArrayType())
4012 Ty = SemaRef.Context.getArrayDecayedType(Ty);
4013
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004014 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004015 QualType PointeeTy = PointerTy->getPointeeType();
4016
4017 // Insert our type, and its more-qualified variants, into the set
4018 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004019 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00004020 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004021 } else if (Ty->isMemberPointerType()) {
4022 // Member pointers are far easier, since the pointee can't be converted.
4023 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4024 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00004025 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00004026 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004027 } else if (Ty->isVectorType()) {
4028 VectorTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004029 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004030 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004031 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004032 // No conversion functions in incomplete types.
4033 return;
4034 }
Mike Stump11289f42009-09-09 15:08:12 +00004035
Douglas Gregora11693b2008-11-12 17:17:38 +00004036 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00004037 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00004038 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00004039 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004040 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004041 NamedDecl *D = I.getDecl();
4042 if (isa<UsingShadowDecl>(D))
4043 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004044
Mike Stump11289f42009-09-09 15:08:12 +00004045 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00004046 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00004047 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00004048 continue;
4049
John McCallda4458e2010-03-31 01:36:47 +00004050 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004051 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004052 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004053 VisibleQuals);
4054 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004055 }
4056 }
4057 }
4058}
4059
Douglas Gregor84605ae2009-08-24 13:43:27 +00004060/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4061/// the volatile- and non-volatile-qualified assignment operators for the
4062/// given type to the candidate set.
4063static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4064 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004065 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004066 unsigned NumArgs,
4067 OverloadCandidateSet &CandidateSet) {
4068 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004069
Douglas Gregor84605ae2009-08-24 13:43:27 +00004070 // T& operator=(T&, T)
4071 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4072 ParamTypes[1] = T;
4073 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4074 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004075
Douglas Gregor84605ae2009-08-24 13:43:27 +00004076 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4077 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004078 ParamTypes[0]
4079 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004080 ParamTypes[1] = T;
4081 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004082 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004083 }
4084}
Mike Stump11289f42009-09-09 15:08:12 +00004085
Sebastian Redl1054fae2009-10-25 17:03:50 +00004086/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4087/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004088static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4089 Qualifiers VRQuals;
4090 const RecordType *TyRec;
4091 if (const MemberPointerType *RHSMPType =
4092 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004093 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004094 else
4095 TyRec = ArgExpr->getType()->getAs<RecordType>();
4096 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004097 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004098 VRQuals.addVolatile();
4099 VRQuals.addRestrict();
4100 return VRQuals;
4101 }
4102
4103 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004104 if (!ClassDecl->hasDefinition())
4105 return VRQuals;
4106
John McCallad371252010-01-20 00:46:10 +00004107 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004108 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004109
John McCallad371252010-01-20 00:46:10 +00004110 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004111 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004112 NamedDecl *D = I.getDecl();
4113 if (isa<UsingShadowDecl>(D))
4114 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4115 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004116 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4117 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4118 CanTy = ResTypeRef->getPointeeType();
4119 // Need to go down the pointer/mempointer chain and add qualifiers
4120 // as see them.
4121 bool done = false;
4122 while (!done) {
4123 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4124 CanTy = ResTypePtr->getPointeeType();
4125 else if (const MemberPointerType *ResTypeMPtr =
4126 CanTy->getAs<MemberPointerType>())
4127 CanTy = ResTypeMPtr->getPointeeType();
4128 else
4129 done = true;
4130 if (CanTy.isVolatileQualified())
4131 VRQuals.addVolatile();
4132 if (CanTy.isRestrictQualified())
4133 VRQuals.addRestrict();
4134 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4135 return VRQuals;
4136 }
4137 }
4138 }
4139 return VRQuals;
4140}
4141
Douglas Gregord08452f2008-11-19 15:42:04 +00004142/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4143/// operator overloads to the candidate set (C++ [over.built]), based
4144/// on the operator @p Op and the arguments given. For example, if the
4145/// operator is a binary '+', this routine might add "int
4146/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00004147void
Mike Stump11289f42009-09-09 15:08:12 +00004148Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004149 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00004150 Expr **Args, unsigned NumArgs,
4151 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004152 // The set of "promoted arithmetic types", which are the arithmetic
4153 // types are that preserved by promotion (C++ [over.built]p2). Note
4154 // that the first few of these types are the promoted integral
4155 // types; these types need to be first.
4156 // FIXME: What about complex?
4157 const unsigned FirstIntegralType = 0;
4158 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00004159 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00004160 LastPromotedIntegralType = 13;
4161 const unsigned FirstPromotedArithmeticType = 7,
4162 LastPromotedArithmeticType = 16;
4163 const unsigned NumArithmeticTypes = 16;
4164 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00004165 Context.BoolTy, Context.CharTy, Context.WCharTy,
4166// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00004167 Context.SignedCharTy, Context.ShortTy,
4168 Context.UnsignedCharTy, Context.UnsignedShortTy,
4169 Context.IntTy, Context.LongTy, Context.LongLongTy,
4170 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
4171 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
4172 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00004173 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
4174 "Invalid first promoted integral type");
4175 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4176 == Context.UnsignedLongLongTy &&
4177 "Invalid last promoted integral type");
4178 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
4179 "Invalid first promoted arithmetic type");
4180 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4181 == Context.LongDoubleTy &&
4182 "Invalid last promoted arithmetic type");
4183
Douglas Gregora11693b2008-11-12 17:17:38 +00004184 // Find all of the types that the arguments can convert to, but only
4185 // if the operator we're looking at has built-in operator candidates
4186 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004187 Qualifiers VisibleTypeConversionsQuals;
4188 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004189 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4190 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4191
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004192 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004193 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4194 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4195 OpLoc,
4196 true,
4197 (Op == OO_Exclaim ||
4198 Op == OO_AmpAmp ||
4199 Op == OO_PipePipe),
4200 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004201
4202 bool isComparison = false;
4203 switch (Op) {
4204 case OO_None:
4205 case NUM_OVERLOADED_OPERATORS:
4206 assert(false && "Expected an overloaded operator");
4207 break;
4208
Douglas Gregord08452f2008-11-19 15:42:04 +00004209 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00004210 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00004211 goto UnaryStar;
4212 else
4213 goto BinaryStar;
4214 break;
4215
4216 case OO_Plus: // '+' is either unary or binary
4217 if (NumArgs == 1)
4218 goto UnaryPlus;
4219 else
4220 goto BinaryPlus;
4221 break;
4222
4223 case OO_Minus: // '-' is either unary or binary
4224 if (NumArgs == 1)
4225 goto UnaryMinus;
4226 else
4227 goto BinaryMinus;
4228 break;
4229
4230 case OO_Amp: // '&' is either unary or binary
4231 if (NumArgs == 1)
4232 goto UnaryAmp;
4233 else
4234 goto BinaryAmp;
4235
4236 case OO_PlusPlus:
4237 case OO_MinusMinus:
4238 // C++ [over.built]p3:
4239 //
4240 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4241 // is either volatile or empty, there exist candidate operator
4242 // functions of the form
4243 //
4244 // VQ T& operator++(VQ T&);
4245 // T operator++(VQ T&, int);
4246 //
4247 // C++ [over.built]p4:
4248 //
4249 // For every pair (T, VQ), where T is an arithmetic type other
4250 // than bool, and VQ is either volatile or empty, there exist
4251 // candidate operator functions of the form
4252 //
4253 // VQ T& operator--(VQ T&);
4254 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00004255 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004256 Arith < NumArithmeticTypes; ++Arith) {
4257 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00004258 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004259 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00004260
4261 // Non-volatile version.
4262 if (NumArgs == 1)
4263 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4264 else
4265 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004266 // heuristic to reduce number of builtin candidates in the set.
4267 // Add volatile version only if there are conversions to a volatile type.
4268 if (VisibleTypeConversionsQuals.hasVolatile()) {
4269 // Volatile version
4270 ParamTypes[0]
4271 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4272 if (NumArgs == 1)
4273 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4274 else
4275 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4276 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004277 }
4278
4279 // C++ [over.built]p5:
4280 //
4281 // For every pair (T, VQ), where T is a cv-qualified or
4282 // cv-unqualified object type, and VQ is either volatile or
4283 // empty, there exist candidate operator functions of the form
4284 //
4285 // T*VQ& operator++(T*VQ&);
4286 // T*VQ& operator--(T*VQ&);
4287 // T* operator++(T*VQ&, int);
4288 // T* operator--(T*VQ&, int);
4289 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4290 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4291 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004292 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00004293 continue;
4294
Mike Stump11289f42009-09-09 15:08:12 +00004295 QualType ParamTypes[2] = {
4296 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00004297 };
Mike Stump11289f42009-09-09 15:08:12 +00004298
Douglas Gregord08452f2008-11-19 15:42:04 +00004299 // Without volatile
4300 if (NumArgs == 1)
4301 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4302 else
4303 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4304
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004305 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4306 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004307 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00004308 ParamTypes[0]
4309 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00004310 if (NumArgs == 1)
4311 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4312 else
4313 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4314 }
4315 }
4316 break;
4317
4318 UnaryStar:
4319 // C++ [over.built]p6:
4320 // For every cv-qualified or cv-unqualified object type T, there
4321 // exist candidate operator functions of the form
4322 //
4323 // T& operator*(T*);
4324 //
4325 // C++ [over.built]p7:
4326 // For every function type T, there exist candidate operator
4327 // functions of the form
4328 // T& operator*(T*);
4329 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4330 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4331 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004332 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004333 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00004334 &ParamTy, Args, 1, CandidateSet);
4335 }
4336 break;
4337
4338 UnaryPlus:
4339 // C++ [over.built]p8:
4340 // For every type T, there exist candidate operator functions of
4341 // the form
4342 //
4343 // T* operator+(T*);
4344 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4345 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4346 QualType ParamTy = *Ptr;
4347 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4348 }
Mike Stump11289f42009-09-09 15:08:12 +00004349
Douglas Gregord08452f2008-11-19 15:42:04 +00004350 // Fall through
4351
4352 UnaryMinus:
4353 // C++ [over.built]p9:
4354 // For every promoted arithmetic type T, there exist candidate
4355 // operator functions of the form
4356 //
4357 // T operator+(T);
4358 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00004359 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004360 Arith < LastPromotedArithmeticType; ++Arith) {
4361 QualType ArithTy = ArithmeticTypes[Arith];
4362 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4363 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004364
4365 // Extension: We also add these operators for vector types.
4366 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4367 VecEnd = CandidateTypes.vector_end();
4368 Vec != VecEnd; ++Vec) {
4369 QualType VecTy = *Vec;
4370 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4371 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004372 break;
4373
4374 case OO_Tilde:
4375 // C++ [over.built]p10:
4376 // For every promoted integral type T, there exist candidate
4377 // operator functions of the form
4378 //
4379 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00004380 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004381 Int < LastPromotedIntegralType; ++Int) {
4382 QualType IntTy = ArithmeticTypes[Int];
4383 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4384 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004385
4386 // Extension: We also add this operator for vector types.
4387 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4388 VecEnd = CandidateTypes.vector_end();
4389 Vec != VecEnd; ++Vec) {
4390 QualType VecTy = *Vec;
4391 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4392 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004393 break;
4394
Douglas Gregora11693b2008-11-12 17:17:38 +00004395 case OO_New:
4396 case OO_Delete:
4397 case OO_Array_New:
4398 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00004399 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00004400 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00004401 break;
4402
4403 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00004404 UnaryAmp:
4405 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00004406 // C++ [over.match.oper]p3:
4407 // -- For the operator ',', the unary operator '&', or the
4408 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00004409 break;
4410
Douglas Gregor84605ae2009-08-24 13:43:27 +00004411 case OO_EqualEqual:
4412 case OO_ExclaimEqual:
4413 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00004414 // For every pointer to member type T, there exist candidate operator
4415 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00004416 //
4417 // bool operator==(T,T);
4418 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00004419 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00004420 MemPtr = CandidateTypes.member_pointer_begin(),
4421 MemPtrEnd = CandidateTypes.member_pointer_end();
4422 MemPtr != MemPtrEnd;
4423 ++MemPtr) {
4424 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4425 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4426 }
Mike Stump11289f42009-09-09 15:08:12 +00004427
Douglas Gregor84605ae2009-08-24 13:43:27 +00004428 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004429
Douglas Gregora11693b2008-11-12 17:17:38 +00004430 case OO_Less:
4431 case OO_Greater:
4432 case OO_LessEqual:
4433 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004434 // C++ [over.built]p15:
4435 //
4436 // For every pointer or enumeration type T, there exist
4437 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004438 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004439 // bool operator<(T, T);
4440 // bool operator>(T, T);
4441 // bool operator<=(T, T);
4442 // bool operator>=(T, T);
4443 // bool operator==(T, T);
4444 // bool operator!=(T, T);
4445 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4446 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4447 QualType ParamTypes[2] = { *Ptr, *Ptr };
4448 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4449 }
Mike Stump11289f42009-09-09 15:08:12 +00004450 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00004451 = CandidateTypes.enumeration_begin();
4452 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4453 QualType ParamTypes[2] = { *Enum, *Enum };
4454 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4455 }
4456
4457 // Fall through.
4458 isComparison = true;
4459
Douglas Gregord08452f2008-11-19 15:42:04 +00004460 BinaryPlus:
4461 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00004462 if (!isComparison) {
4463 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4464
4465 // C++ [over.built]p13:
4466 //
4467 // For every cv-qualified or cv-unqualified object type T
4468 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004469 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004470 // T* operator+(T*, ptrdiff_t);
4471 // T& operator[](T*, ptrdiff_t); [BELOW]
4472 // T* operator-(T*, ptrdiff_t);
4473 // T* operator+(ptrdiff_t, T*);
4474 // T& operator[](ptrdiff_t, T*); [BELOW]
4475 //
4476 // C++ [over.built]p14:
4477 //
4478 // For every T, where T is a pointer to object type, there
4479 // exist candidate operator functions of the form
4480 //
4481 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00004482 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00004483 = CandidateTypes.pointer_begin();
4484 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4485 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4486
4487 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4488 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4489
4490 if (Op == OO_Plus) {
4491 // T* operator+(ptrdiff_t, T*);
4492 ParamTypes[0] = ParamTypes[1];
4493 ParamTypes[1] = *Ptr;
4494 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4495 } else {
4496 // ptrdiff_t operator-(T, T);
4497 ParamTypes[1] = *Ptr;
4498 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4499 Args, 2, CandidateSet);
4500 }
4501 }
4502 }
4503 // Fall through
4504
Douglas Gregora11693b2008-11-12 17:17:38 +00004505 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00004506 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00004507 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00004508 // C++ [over.built]p12:
4509 //
4510 // For every pair of promoted arithmetic types L and R, there
4511 // exist candidate operator functions of the form
4512 //
4513 // LR operator*(L, R);
4514 // LR operator/(L, R);
4515 // LR operator+(L, R);
4516 // LR operator-(L, R);
4517 // bool operator<(L, R);
4518 // bool operator>(L, R);
4519 // bool operator<=(L, R);
4520 // bool operator>=(L, R);
4521 // bool operator==(L, R);
4522 // bool operator!=(L, R);
4523 //
4524 // where LR is the result of the usual arithmetic conversions
4525 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004526 //
4527 // C++ [over.built]p24:
4528 //
4529 // For every pair of promoted arithmetic types L and R, there exist
4530 // candidate operator functions of the form
4531 //
4532 // LR operator?(bool, L, R);
4533 //
4534 // where LR is the result of the usual arithmetic conversions
4535 // between types L and R.
4536 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004537 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004538 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004539 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004540 Right < LastPromotedArithmeticType; ++Right) {
4541 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004542 QualType Result
4543 = isComparison
4544 ? Context.BoolTy
4545 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004546 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4547 }
4548 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004549
4550 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
4551 // conditional operator for vector types.
4552 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4553 Vec1End = CandidateTypes.vector_end();
4554 Vec1 != Vec1End; ++Vec1)
4555 for (BuiltinCandidateTypeSet::iterator
4556 Vec2 = CandidateTypes.vector_begin(),
4557 Vec2End = CandidateTypes.vector_end();
4558 Vec2 != Vec2End; ++Vec2) {
4559 QualType LandR[2] = { *Vec1, *Vec2 };
4560 QualType Result;
4561 if (isComparison)
4562 Result = Context.BoolTy;
4563 else {
4564 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
4565 Result = *Vec1;
4566 else
4567 Result = *Vec2;
4568 }
4569
4570 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4571 }
4572
Douglas Gregora11693b2008-11-12 17:17:38 +00004573 break;
4574
4575 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00004576 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00004577 case OO_Caret:
4578 case OO_Pipe:
4579 case OO_LessLess:
4580 case OO_GreaterGreater:
4581 // C++ [over.built]p17:
4582 //
4583 // For every pair of promoted integral types L and R, there
4584 // exist candidate operator functions of the form
4585 //
4586 // LR operator%(L, R);
4587 // LR operator&(L, R);
4588 // LR operator^(L, R);
4589 // LR operator|(L, R);
4590 // L operator<<(L, R);
4591 // L operator>>(L, R);
4592 //
4593 // where LR is the result of the usual arithmetic conversions
4594 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00004595 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004596 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004597 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004598 Right < LastPromotedIntegralType; ++Right) {
4599 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4600 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4601 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004602 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004603 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4604 }
4605 }
4606 break;
4607
4608 case OO_Equal:
4609 // C++ [over.built]p20:
4610 //
4611 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00004612 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00004613 // empty, there exist candidate operator functions of the form
4614 //
4615 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004616 for (BuiltinCandidateTypeSet::iterator
4617 Enum = CandidateTypes.enumeration_begin(),
4618 EnumEnd = CandidateTypes.enumeration_end();
4619 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00004620 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004621 CandidateSet);
4622 for (BuiltinCandidateTypeSet::iterator
4623 MemPtr = CandidateTypes.member_pointer_begin(),
4624 MemPtrEnd = CandidateTypes.member_pointer_end();
4625 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00004626 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004627 CandidateSet);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004628
4629 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00004630
4631 case OO_PlusEqual:
4632 case OO_MinusEqual:
4633 // C++ [over.built]p19:
4634 //
4635 // For every pair (T, VQ), where T is any type and VQ is either
4636 // volatile or empty, there exist candidate operator functions
4637 // of the form
4638 //
4639 // T*VQ& operator=(T*VQ&, T*);
4640 //
4641 // C++ [over.built]p21:
4642 //
4643 // For every pair (T, VQ), where T is a cv-qualified or
4644 // cv-unqualified object type and VQ is either volatile or
4645 // empty, there exist candidate operator functions of the form
4646 //
4647 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4648 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4649 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4650 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4651 QualType ParamTypes[2];
4652 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4653
4654 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004655 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004656 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4657 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004658
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004659 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4660 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004661 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00004662 ParamTypes[0]
4663 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00004664 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4665 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00004666 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004667 }
4668 // Fall through.
4669
4670 case OO_StarEqual:
4671 case OO_SlashEqual:
4672 // C++ [over.built]p18:
4673 //
4674 // For every triple (L, VQ, R), where L is an arithmetic type,
4675 // VQ is either volatile or empty, and R is a promoted
4676 // arithmetic type, there exist candidate operator functions of
4677 // the form
4678 //
4679 // VQ L& operator=(VQ L&, R);
4680 // VQ L& operator*=(VQ L&, R);
4681 // VQ L& operator/=(VQ L&, R);
4682 // VQ L& operator+=(VQ L&, R);
4683 // VQ L& operator-=(VQ L&, R);
4684 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004685 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004686 Right < LastPromotedArithmeticType; ++Right) {
4687 QualType ParamTypes[2];
4688 ParamTypes[1] = ArithmeticTypes[Right];
4689
4690 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004691 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004692 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4693 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004694
4695 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004696 if (VisibleTypeConversionsQuals.hasVolatile()) {
4697 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4698 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4699 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4700 /*IsAssigmentOperator=*/Op == OO_Equal);
4701 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004702 }
4703 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004704
4705 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
4706 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4707 Vec1End = CandidateTypes.vector_end();
4708 Vec1 != Vec1End; ++Vec1)
4709 for (BuiltinCandidateTypeSet::iterator
4710 Vec2 = CandidateTypes.vector_begin(),
4711 Vec2End = CandidateTypes.vector_end();
4712 Vec2 != Vec2End; ++Vec2) {
4713 QualType ParamTypes[2];
4714 ParamTypes[1] = *Vec2;
4715 // Add this built-in operator as a candidate (VQ is empty).
4716 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
4717 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4718 /*IsAssigmentOperator=*/Op == OO_Equal);
4719
4720 // Add this built-in operator as a candidate (VQ is 'volatile').
4721 if (VisibleTypeConversionsQuals.hasVolatile()) {
4722 ParamTypes[0] = Context.getVolatileType(*Vec1);
4723 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4724 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4725 /*IsAssigmentOperator=*/Op == OO_Equal);
4726 }
4727 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004728 break;
4729
4730 case OO_PercentEqual:
4731 case OO_LessLessEqual:
4732 case OO_GreaterGreaterEqual:
4733 case OO_AmpEqual:
4734 case OO_CaretEqual:
4735 case OO_PipeEqual:
4736 // C++ [over.built]p22:
4737 //
4738 // For every triple (L, VQ, R), where L is an integral type, VQ
4739 // is either volatile or empty, and R is a promoted integral
4740 // type, there exist candidate operator functions of the form
4741 //
4742 // VQ L& operator%=(VQ L&, R);
4743 // VQ L& operator<<=(VQ L&, R);
4744 // VQ L& operator>>=(VQ L&, R);
4745 // VQ L& operator&=(VQ L&, R);
4746 // VQ L& operator^=(VQ L&, R);
4747 // VQ L& operator|=(VQ L&, R);
4748 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004749 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004750 Right < LastPromotedIntegralType; ++Right) {
4751 QualType ParamTypes[2];
4752 ParamTypes[1] = ArithmeticTypes[Right];
4753
4754 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004755 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004756 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00004757 if (VisibleTypeConversionsQuals.hasVolatile()) {
4758 // Add this built-in operator as a candidate (VQ is 'volatile').
4759 ParamTypes[0] = ArithmeticTypes[Left];
4760 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4761 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4762 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4763 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004764 }
4765 }
4766 break;
4767
Douglas Gregord08452f2008-11-19 15:42:04 +00004768 case OO_Exclaim: {
4769 // C++ [over.operator]p23:
4770 //
4771 // There also exist candidate operator functions of the form
4772 //
Mike Stump11289f42009-09-09 15:08:12 +00004773 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00004774 // bool operator&&(bool, bool); [BELOW]
4775 // bool operator||(bool, bool); [BELOW]
4776 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00004777 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4778 /*IsAssignmentOperator=*/false,
4779 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004780 break;
4781 }
4782
Douglas Gregora11693b2008-11-12 17:17:38 +00004783 case OO_AmpAmp:
4784 case OO_PipePipe: {
4785 // C++ [over.operator]p23:
4786 //
4787 // There also exist candidate operator functions of the form
4788 //
Douglas Gregord08452f2008-11-19 15:42:04 +00004789 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00004790 // bool operator&&(bool, bool);
4791 // bool operator||(bool, bool);
4792 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00004793 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4794 /*IsAssignmentOperator=*/false,
4795 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00004796 break;
4797 }
4798
4799 case OO_Subscript:
4800 // C++ [over.built]p13:
4801 //
4802 // For every cv-qualified or cv-unqualified object type T there
4803 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004804 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004805 // T* operator+(T*, ptrdiff_t); [ABOVE]
4806 // T& operator[](T*, ptrdiff_t);
4807 // T* operator-(T*, ptrdiff_t); [ABOVE]
4808 // T* operator+(ptrdiff_t, T*); [ABOVE]
4809 // T& operator[](ptrdiff_t, T*);
4810 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4811 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4812 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004813 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004814 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00004815
4816 // T& operator[](T*, ptrdiff_t)
4817 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4818
4819 // T& operator[](ptrdiff_t, T*);
4820 ParamTypes[0] = ParamTypes[1];
4821 ParamTypes[1] = *Ptr;
4822 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004823 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004824 break;
4825
4826 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004827 // C++ [over.built]p11:
4828 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4829 // C1 is the same type as C2 or is a derived class of C2, T is an object
4830 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4831 // there exist candidate operator functions of the form
4832 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4833 // where CV12 is the union of CV1 and CV2.
4834 {
4835 for (BuiltinCandidateTypeSet::iterator Ptr =
4836 CandidateTypes.pointer_begin();
4837 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4838 QualType C1Ty = (*Ptr);
4839 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004840 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004841 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004842 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004843 if (!isa<RecordType>(C1))
4844 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004845 // heuristic to reduce number of builtin candidates in the set.
4846 // Add volatile/restrict version only if there are conversions to a
4847 // volatile/restrict type.
4848 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4849 continue;
4850 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4851 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004852 }
4853 for (BuiltinCandidateTypeSet::iterator
4854 MemPtr = CandidateTypes.member_pointer_begin(),
4855 MemPtrEnd = CandidateTypes.member_pointer_end();
4856 MemPtr != MemPtrEnd; ++MemPtr) {
4857 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4858 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00004859 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004860 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4861 break;
4862 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4863 // build CV12 T&
4864 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004865 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4866 T.isVolatileQualified())
4867 continue;
4868 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4869 T.isRestrictQualified())
4870 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004871 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004872 QualType ResultTy = Context.getLValueReferenceType(T);
4873 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4874 }
4875 }
4876 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004877 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004878
4879 case OO_Conditional:
4880 // Note that we don't consider the first argument, since it has been
4881 // contextually converted to bool long ago. The candidates below are
4882 // therefore added as binary.
4883 //
4884 // C++ [over.built]p24:
4885 // For every type T, where T is a pointer or pointer-to-member type,
4886 // there exist candidate operator functions of the form
4887 //
4888 // T operator?(bool, T, T);
4889 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00004890 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4891 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4892 QualType ParamTypes[2] = { *Ptr, *Ptr };
4893 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4894 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004895 for (BuiltinCandidateTypeSet::iterator Ptr =
4896 CandidateTypes.member_pointer_begin(),
4897 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4898 QualType ParamTypes[2] = { *Ptr, *Ptr };
4899 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4900 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004901 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00004902 }
4903}
4904
Douglas Gregore254f902009-02-04 00:32:51 +00004905/// \brief Add function candidates found via argument-dependent lookup
4906/// to the set of overloading candidates.
4907///
4908/// This routine performs argument-dependent name lookup based on the
4909/// given function name (which may also be an operator name) and adds
4910/// all of the overload candidates found by ADL to the overload
4911/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00004912void
Douglas Gregore254f902009-02-04 00:32:51 +00004913Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00004914 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00004915 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00004916 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004917 OverloadCandidateSet& CandidateSet,
4918 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00004919 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00004920
John McCall91f61fc2010-01-26 06:04:06 +00004921 // FIXME: This approach for uniquing ADL results (and removing
4922 // redundant candidates from the set) relies on pointer-equality,
4923 // which means we need to key off the canonical decl. However,
4924 // always going back to the canonical decl might not get us the
4925 // right set of default arguments. What default arguments are
4926 // we supposed to consider on ADL candidates, anyway?
4927
Douglas Gregorcabea402009-09-22 15:41:20 +00004928 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00004929 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00004930
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004931 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004932 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4933 CandEnd = CandidateSet.end();
4934 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004935 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00004936 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004937 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00004938 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00004939 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004940
4941 // For each of the ADL candidates we found, add it to the overload
4942 // set.
John McCall8fe68082010-01-26 07:16:45 +00004943 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00004944 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00004945 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00004946 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004947 continue;
4948
John McCalla0296f72010-03-19 07:35:19 +00004949 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00004950 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00004951 } else
John McCall4c4c1df2010-01-26 03:27:55 +00004952 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00004953 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004954 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004955 }
Douglas Gregore254f902009-02-04 00:32:51 +00004956}
4957
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004958/// isBetterOverloadCandidate - Determines whether the first overload
4959/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004960bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004961Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCallbc077cf2010-02-08 23:07:23 +00004962 const OverloadCandidate& Cand2,
4963 SourceLocation Loc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004964 // Define viable functions to be better candidates than non-viable
4965 // functions.
4966 if (!Cand2.Viable)
4967 return Cand1.Viable;
4968 else if (!Cand1.Viable)
4969 return false;
4970
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004971 // C++ [over.match.best]p1:
4972 //
4973 // -- if F is a static member function, ICS1(F) is defined such
4974 // that ICS1(F) is neither better nor worse than ICS1(G) for
4975 // any function G, and, symmetrically, ICS1(G) is neither
4976 // better nor worse than ICS1(F).
4977 unsigned StartArg = 0;
4978 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4979 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004980
Douglas Gregord3cb3562009-07-07 23:38:56 +00004981 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004982 // A viable function F1 is defined to be a better function than another
4983 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004984 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004985 unsigned NumArgs = Cand1.Conversions.size();
4986 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4987 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004988 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004989 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4990 Cand2.Conversions[ArgIdx])) {
4991 case ImplicitConversionSequence::Better:
4992 // Cand1 has a better conversion sequence.
4993 HasBetterConversion = true;
4994 break;
4995
4996 case ImplicitConversionSequence::Worse:
4997 // Cand1 can't be better than Cand2.
4998 return false;
4999
5000 case ImplicitConversionSequence::Indistinguishable:
5001 // Do nothing.
5002 break;
5003 }
5004 }
5005
Mike Stump11289f42009-09-09 15:08:12 +00005006 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00005007 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005008 if (HasBetterConversion)
5009 return true;
5010
Mike Stump11289f42009-09-09 15:08:12 +00005011 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00005012 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00005013 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00005014 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5015 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005016
5017 // -- F1 and F2 are function template specializations, and the function
5018 // template for F1 is more specialized than the template for F2
5019 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00005020 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00005021 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5022 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00005023 if (FunctionTemplateDecl *BetterTemplate
5024 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5025 Cand2.Function->getPrimaryTemplate(),
John McCallbc077cf2010-02-08 23:07:23 +00005026 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00005027 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5028 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00005029 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005030
Douglas Gregora1f013e2008-11-07 22:36:19 +00005031 // -- the context is an initialization by user-defined conversion
5032 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5033 // from the return type of F1 to the destination type (i.e.,
5034 // the type of the entity being initialized) is a better
5035 // conversion sequence than the standard conversion sequence
5036 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00005037 if (Cand1.Function && Cand2.Function &&
5038 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00005039 isa<CXXConversionDecl>(Cand2.Function)) {
5040 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
5041 Cand2.FinalConversion)) {
5042 case ImplicitConversionSequence::Better:
5043 // Cand1 has a better conversion sequence.
5044 return true;
5045
5046 case ImplicitConversionSequence::Worse:
5047 // Cand1 can't be better than Cand2.
5048 return false;
5049
5050 case ImplicitConversionSequence::Indistinguishable:
5051 // Do nothing
5052 break;
5053 }
5054 }
5055
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005056 return false;
5057}
5058
Mike Stump11289f42009-09-09 15:08:12 +00005059/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005060/// within an overload candidate set.
5061///
5062/// \param CandidateSet the set of candidate functions.
5063///
5064/// \param Loc the location of the function name (or operator symbol) for
5065/// which overload resolution occurs.
5066///
Mike Stump11289f42009-09-09 15:08:12 +00005067/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005068/// function, Best points to the candidate function found.
5069///
5070/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005071OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
5072 SourceLocation Loc,
5073 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005074 // Find the best viable function.
5075 Best = CandidateSet.end();
5076 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5077 Cand != CandidateSet.end(); ++Cand) {
5078 if (Cand->Viable) {
John McCallbc077cf2010-02-08 23:07:23 +00005079 if (Best == CandidateSet.end() ||
5080 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005081 Best = Cand;
5082 }
5083 }
5084
5085 // If we didn't find any viable functions, abort.
5086 if (Best == CandidateSet.end())
5087 return OR_No_Viable_Function;
5088
5089 // Make sure that this function is better than every other viable
5090 // function. If not, we have an ambiguity.
5091 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5092 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00005093 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005094 Cand != Best &&
John McCallbc077cf2010-02-08 23:07:23 +00005095 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005096 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005097 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005098 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005099 }
Mike Stump11289f42009-09-09 15:08:12 +00005100
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005101 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00005102 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005103 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005104 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00005105 return OR_Deleted;
5106
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005107 // C++ [basic.def.odr]p2:
5108 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00005109 // when referred to from a potentially-evaluated expression. [Note: this
5110 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005111 // (clause 13), user-defined conversions (12.3.2), allocation function for
5112 // placement new (5.3.4), as well as non-default initialization (8.5).
5113 if (Best->Function)
5114 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005115 return OR_Success;
5116}
5117
John McCall53262c92010-01-12 02:15:36 +00005118namespace {
5119
5120enum OverloadCandidateKind {
5121 oc_function,
5122 oc_method,
5123 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005124 oc_function_template,
5125 oc_method_template,
5126 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00005127 oc_implicit_default_constructor,
5128 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005129 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00005130};
5131
John McCalle1ac8d12010-01-13 00:25:19 +00005132OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5133 FunctionDecl *Fn,
5134 std::string &Description) {
5135 bool isTemplate = false;
5136
5137 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5138 isTemplate = true;
5139 Description = S.getTemplateArgumentBindingsText(
5140 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5141 }
John McCallfd0b2f82010-01-06 09:43:14 +00005142
5143 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00005144 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005145 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005146
John McCall53262c92010-01-12 02:15:36 +00005147 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5148 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005149 }
5150
5151 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5152 // This actually gets spelled 'candidate function' for now, but
5153 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00005154 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005155 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00005156
5157 assert(Meth->isCopyAssignment()
5158 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00005159 return oc_implicit_copy_assignment;
5160 }
5161
John McCalle1ac8d12010-01-13 00:25:19 +00005162 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00005163}
5164
5165} // end anonymous namespace
5166
5167// Notes the location of an overload candidate.
5168void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00005169 std::string FnDesc;
5170 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5171 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5172 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00005173}
5174
John McCall0d1da222010-01-12 00:44:57 +00005175/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5176/// "lead" diagnostic; it will be given two arguments, the source and
5177/// target types of the conversion.
5178void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
5179 SourceLocation CaretLoc,
5180 const PartialDiagnostic &PDiag) {
5181 Diag(CaretLoc, PDiag)
5182 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
5183 for (AmbiguousConversionSequence::const_iterator
5184 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
5185 NoteOverloadCandidate(*I);
5186 }
John McCall12f97bc2010-01-08 04:41:39 +00005187}
5188
John McCall0d1da222010-01-12 00:44:57 +00005189namespace {
5190
John McCall6a61b522010-01-13 09:16:55 +00005191void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5192 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5193 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00005194 assert(Cand->Function && "for now, candidate must be a function");
5195 FunctionDecl *Fn = Cand->Function;
5196
5197 // There's a conversion slot for the object argument if this is a
5198 // non-constructor method. Note that 'I' corresponds the
5199 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00005200 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00005201 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00005202 if (I == 0)
5203 isObjectArgument = true;
5204 else
5205 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00005206 }
5207
John McCalle1ac8d12010-01-13 00:25:19 +00005208 std::string FnDesc;
5209 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5210
John McCall6a61b522010-01-13 09:16:55 +00005211 Expr *FromExpr = Conv.Bad.FromExpr;
5212 QualType FromTy = Conv.Bad.getFromType();
5213 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00005214
John McCallfb7ad0f2010-02-02 02:42:52 +00005215 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00005216 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00005217 Expr *E = FromExpr->IgnoreParens();
5218 if (isa<UnaryOperator>(E))
5219 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00005220 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00005221
5222 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5223 << (unsigned) FnKind << FnDesc
5224 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5225 << ToTy << Name << I+1;
5226 return;
5227 }
5228
John McCall6d174642010-01-23 08:10:49 +00005229 // Do some hand-waving analysis to see if the non-viability is due
5230 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00005231 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5232 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5233 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5234 CToTy = RT->getPointeeType();
5235 else {
5236 // TODO: detect and diagnose the full richness of const mismatches.
5237 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5238 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5239 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5240 }
5241
5242 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5243 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5244 // It is dumb that we have to do this here.
5245 while (isa<ArrayType>(CFromTy))
5246 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5247 while (isa<ArrayType>(CToTy))
5248 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5249
5250 Qualifiers FromQs = CFromTy.getQualifiers();
5251 Qualifiers ToQs = CToTy.getQualifiers();
5252
5253 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5254 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5255 << (unsigned) FnKind << FnDesc
5256 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5257 << FromTy
5258 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5259 << (unsigned) isObjectArgument << I+1;
5260 return;
5261 }
5262
5263 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5264 assert(CVR && "unexpected qualifiers mismatch");
5265
5266 if (isObjectArgument) {
5267 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5268 << (unsigned) FnKind << FnDesc
5269 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5270 << FromTy << (CVR - 1);
5271 } else {
5272 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5273 << (unsigned) FnKind << FnDesc
5274 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5275 << FromTy << (CVR - 1) << I+1;
5276 }
5277 return;
5278 }
5279
John McCall6d174642010-01-23 08:10:49 +00005280 // Diagnose references or pointers to incomplete types differently,
5281 // since it's far from impossible that the incompleteness triggered
5282 // the failure.
5283 QualType TempFromTy = FromTy.getNonReferenceType();
5284 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5285 TempFromTy = PTy->getPointeeType();
5286 if (TempFromTy->isIncompleteType()) {
5287 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5288 << (unsigned) FnKind << FnDesc
5289 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5290 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5291 return;
5292 }
5293
John McCall47000992010-01-14 03:28:57 +00005294 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00005295 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5296 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00005297 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00005298 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00005299}
5300
5301void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5302 unsigned NumFormalArgs) {
5303 // TODO: treat calls to a missing default constructor as a special case
5304
5305 FunctionDecl *Fn = Cand->Function;
5306 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5307
5308 unsigned MinParams = Fn->getMinRequiredArguments();
5309
5310 // at least / at most / exactly
Douglas Gregor02eb4832010-05-08 18:13:28 +00005311 // FIXME: variadic templates "at most" should account for parameter packs
John McCall6a61b522010-01-13 09:16:55 +00005312 unsigned mode, modeCount;
5313 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005314 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5315 (Cand->FailureKind == ovl_fail_bad_deduction &&
5316 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCall6a61b522010-01-13 09:16:55 +00005317 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5318 mode = 0; // "at least"
5319 else
5320 mode = 2; // "exactly"
5321 modeCount = MinParams;
5322 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005323 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5324 (Cand->FailureKind == ovl_fail_bad_deduction &&
5325 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00005326 if (MinParams != FnTy->getNumArgs())
5327 mode = 1; // "at most"
5328 else
5329 mode = 2; // "exactly"
5330 modeCount = FnTy->getNumArgs();
5331 }
5332
5333 std::string Description;
5334 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5335
5336 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregor02eb4832010-05-08 18:13:28 +00005337 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5338 << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00005339}
5340
John McCall8b9ed552010-02-01 18:53:26 +00005341/// Diagnose a failed template-argument deduction.
5342void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5343 Expr **Args, unsigned NumArgs) {
5344 FunctionDecl *Fn = Cand->Function; // pattern
5345
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005346 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005347 NamedDecl *ParamD;
5348 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5349 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5350 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00005351 switch (Cand->DeductionFailure.Result) {
5352 case Sema::TDK_Success:
5353 llvm_unreachable("TDK_success while diagnosing bad deduction");
5354
5355 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00005356 assert(ParamD && "no parameter found for incomplete deduction result");
5357 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5358 << ParamD->getDeclName();
5359 return;
5360 }
5361
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005362 case Sema::TDK_Inconsistent:
5363 case Sema::TDK_InconsistentQuals: {
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005364 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005365 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005366 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005367 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005368 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005369 which = 1;
5370 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005371 which = 2;
5372 }
5373
5374 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5375 << which << ParamD->getDeclName()
5376 << *Cand->DeductionFailure.getFirstArg()
5377 << *Cand->DeductionFailure.getSecondArg();
5378 return;
5379 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00005380
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005381 case Sema::TDK_InvalidExplicitArguments:
5382 assert(ParamD && "no parameter found for invalid explicit arguments");
5383 if (ParamD->getDeclName())
5384 S.Diag(Fn->getLocation(),
5385 diag::note_ovl_candidate_explicit_arg_mismatch_named)
5386 << ParamD->getDeclName();
5387 else {
5388 int index = 0;
5389 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5390 index = TTP->getIndex();
5391 else if (NonTypeTemplateParmDecl *NTTP
5392 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5393 index = NTTP->getIndex();
5394 else
5395 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
5396 S.Diag(Fn->getLocation(),
5397 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
5398 << (index + 1);
5399 }
5400 return;
5401
Douglas Gregor02eb4832010-05-08 18:13:28 +00005402 case Sema::TDK_TooManyArguments:
5403 case Sema::TDK_TooFewArguments:
5404 DiagnoseArityMismatch(S, Cand, NumArgs);
5405 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00005406
5407 case Sema::TDK_InstantiationDepth:
5408 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
5409 return;
5410
5411 case Sema::TDK_SubstitutionFailure: {
5412 std::string ArgString;
5413 if (TemplateArgumentList *Args
5414 = Cand->DeductionFailure.getTemplateArgumentList())
5415 ArgString = S.getTemplateArgumentBindingsText(
5416 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
5417 *Args);
5418 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
5419 << ArgString;
5420 return;
5421 }
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005422
John McCall8b9ed552010-02-01 18:53:26 +00005423 // TODO: diagnose these individually, then kill off
5424 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00005425 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00005426 case Sema::TDK_FailedOverloadResolution:
5427 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
5428 return;
5429 }
5430}
5431
5432/// Generates a 'note' diagnostic for an overload candidate. We've
5433/// already generated a primary error at the call site.
5434///
5435/// It really does need to be a single diagnostic with its caret
5436/// pointed at the candidate declaration. Yes, this creates some
5437/// major challenges of technical writing. Yes, this makes pointing
5438/// out problems with specific arguments quite awkward. It's still
5439/// better than generating twenty screens of text for every failed
5440/// overload.
5441///
5442/// It would be great to be able to express per-candidate problems
5443/// more richly for those diagnostic clients that cared, but we'd
5444/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00005445void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
5446 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00005447 FunctionDecl *Fn = Cand->Function;
5448
John McCall12f97bc2010-01-08 04:41:39 +00005449 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00005450 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00005451 std::string FnDesc;
5452 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00005453
5454 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00005455 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00005456 return;
John McCall12f97bc2010-01-08 04:41:39 +00005457 }
5458
John McCalle1ac8d12010-01-13 00:25:19 +00005459 // We don't really have anything else to say about viable candidates.
5460 if (Cand->Viable) {
5461 S.NoteOverloadCandidate(Fn);
5462 return;
5463 }
John McCall0d1da222010-01-12 00:44:57 +00005464
John McCall6a61b522010-01-13 09:16:55 +00005465 switch (Cand->FailureKind) {
5466 case ovl_fail_too_many_arguments:
5467 case ovl_fail_too_few_arguments:
5468 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00005469
John McCall6a61b522010-01-13 09:16:55 +00005470 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00005471 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5472
John McCallfe796dd2010-01-23 05:17:32 +00005473 case ovl_fail_trivial_conversion:
5474 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005475 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00005476 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005477
John McCall65eb8792010-02-25 01:37:24 +00005478 case ovl_fail_bad_conversion: {
5479 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5480 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00005481 if (Cand->Conversions[I].isBad())
5482 return DiagnoseBadConversion(S, Cand, I);
5483
5484 // FIXME: this currently happens when we're called from SemaInit
5485 // when user-conversion overload fails. Figure out how to handle
5486 // those conditions and diagnose them well.
5487 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005488 }
John McCall65eb8792010-02-25 01:37:24 +00005489 }
John McCalld3224162010-01-08 00:58:21 +00005490}
5491
5492void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5493 // Desugar the type of the surrogate down to a function type,
5494 // retaining as many typedefs as possible while still showing
5495 // the function type (and, therefore, its parameter types).
5496 QualType FnType = Cand->Surrogate->getConversionType();
5497 bool isLValueReference = false;
5498 bool isRValueReference = false;
5499 bool isPointer = false;
5500 if (const LValueReferenceType *FnTypeRef =
5501 FnType->getAs<LValueReferenceType>()) {
5502 FnType = FnTypeRef->getPointeeType();
5503 isLValueReference = true;
5504 } else if (const RValueReferenceType *FnTypeRef =
5505 FnType->getAs<RValueReferenceType>()) {
5506 FnType = FnTypeRef->getPointeeType();
5507 isRValueReference = true;
5508 }
5509 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5510 FnType = FnTypePtr->getPointeeType();
5511 isPointer = true;
5512 }
5513 // Desugar down to a function type.
5514 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5515 // Reconstruct the pointer/reference as appropriate.
5516 if (isPointer) FnType = S.Context.getPointerType(FnType);
5517 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5518 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5519
5520 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5521 << FnType;
5522}
5523
5524void NoteBuiltinOperatorCandidate(Sema &S,
5525 const char *Opc,
5526 SourceLocation OpLoc,
5527 OverloadCandidate *Cand) {
5528 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5529 std::string TypeStr("operator");
5530 TypeStr += Opc;
5531 TypeStr += "(";
5532 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5533 if (Cand->Conversions.size() == 1) {
5534 TypeStr += ")";
5535 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5536 } else {
5537 TypeStr += ", ";
5538 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5539 TypeStr += ")";
5540 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5541 }
5542}
5543
5544void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5545 OverloadCandidate *Cand) {
5546 unsigned NoOperands = Cand->Conversions.size();
5547 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5548 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00005549 if (ICS.isBad()) break; // all meaningless after first invalid
5550 if (!ICS.isAmbiguous()) continue;
5551
5552 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00005553 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00005554 }
5555}
5556
John McCall3712d9e2010-01-15 23:32:50 +00005557SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5558 if (Cand->Function)
5559 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00005560 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00005561 return Cand->Surrogate->getLocation();
5562 return SourceLocation();
5563}
5564
John McCallad2587a2010-01-12 00:48:53 +00005565struct CompareOverloadCandidatesForDisplay {
5566 Sema &S;
5567 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00005568
5569 bool operator()(const OverloadCandidate *L,
5570 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00005571 // Fast-path this check.
5572 if (L == R) return false;
5573
John McCall12f97bc2010-01-08 04:41:39 +00005574 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00005575 if (L->Viable) {
5576 if (!R->Viable) return true;
5577
5578 // TODO: introduce a tri-valued comparison for overload
5579 // candidates. Would be more worthwhile if we had a sort
5580 // that could exploit it.
John McCallbc077cf2010-02-08 23:07:23 +00005581 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5582 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00005583 } else if (R->Viable)
5584 return false;
John McCall12f97bc2010-01-08 04:41:39 +00005585
John McCall3712d9e2010-01-15 23:32:50 +00005586 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00005587
John McCall3712d9e2010-01-15 23:32:50 +00005588 // Criteria by which we can sort non-viable candidates:
5589 if (!L->Viable) {
5590 // 1. Arity mismatches come after other candidates.
5591 if (L->FailureKind == ovl_fail_too_many_arguments ||
5592 L->FailureKind == ovl_fail_too_few_arguments)
5593 return false;
5594 if (R->FailureKind == ovl_fail_too_many_arguments ||
5595 R->FailureKind == ovl_fail_too_few_arguments)
5596 return true;
John McCall12f97bc2010-01-08 04:41:39 +00005597
John McCallfe796dd2010-01-23 05:17:32 +00005598 // 2. Bad conversions come first and are ordered by the number
5599 // of bad conversions and quality of good conversions.
5600 if (L->FailureKind == ovl_fail_bad_conversion) {
5601 if (R->FailureKind != ovl_fail_bad_conversion)
5602 return true;
5603
5604 // If there's any ordering between the defined conversions...
5605 // FIXME: this might not be transitive.
5606 assert(L->Conversions.size() == R->Conversions.size());
5607
5608 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00005609 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5610 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCallfe796dd2010-01-23 05:17:32 +00005611 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5612 R->Conversions[I])) {
5613 case ImplicitConversionSequence::Better:
5614 leftBetter++;
5615 break;
5616
5617 case ImplicitConversionSequence::Worse:
5618 leftBetter--;
5619 break;
5620
5621 case ImplicitConversionSequence::Indistinguishable:
5622 break;
5623 }
5624 }
5625 if (leftBetter > 0) return true;
5626 if (leftBetter < 0) return false;
5627
5628 } else if (R->FailureKind == ovl_fail_bad_conversion)
5629 return false;
5630
John McCall3712d9e2010-01-15 23:32:50 +00005631 // TODO: others?
5632 }
5633
5634 // Sort everything else by location.
5635 SourceLocation LLoc = GetLocationForCandidate(L);
5636 SourceLocation RLoc = GetLocationForCandidate(R);
5637
5638 // Put candidates without locations (e.g. builtins) at the end.
5639 if (LLoc.isInvalid()) return false;
5640 if (RLoc.isInvalid()) return true;
5641
5642 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00005643 }
5644};
5645
John McCallfe796dd2010-01-23 05:17:32 +00005646/// CompleteNonViableCandidate - Normally, overload resolution only
5647/// computes up to the first
5648void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5649 Expr **Args, unsigned NumArgs) {
5650 assert(!Cand->Viable);
5651
5652 // Don't do anything on failures other than bad conversion.
5653 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5654
5655 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00005656 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00005657 unsigned ConvCount = Cand->Conversions.size();
5658 while (true) {
5659 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5660 ConvIdx++;
5661 if (Cand->Conversions[ConvIdx - 1].isBad())
5662 break;
5663 }
5664
5665 if (ConvIdx == ConvCount)
5666 return;
5667
John McCall65eb8792010-02-25 01:37:24 +00005668 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
5669 "remaining conversion is initialized?");
5670
Douglas Gregoradc7a702010-04-16 17:45:54 +00005671 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00005672 // operation somehow.
5673 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00005674
5675 const FunctionProtoType* Proto;
5676 unsigned ArgIdx = ConvIdx;
5677
5678 if (Cand->IsSurrogate) {
5679 QualType ConvType
5680 = Cand->Surrogate->getConversionType().getNonReferenceType();
5681 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5682 ConvType = ConvPtrType->getPointeeType();
5683 Proto = ConvType->getAs<FunctionProtoType>();
5684 ArgIdx--;
5685 } else if (Cand->Function) {
5686 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
5687 if (isa<CXXMethodDecl>(Cand->Function) &&
5688 !isa<CXXConstructorDecl>(Cand->Function))
5689 ArgIdx--;
5690 } else {
5691 // Builtin binary operator with a bad first conversion.
5692 assert(ConvCount <= 3);
5693 for (; ConvIdx != ConvCount; ++ConvIdx)
5694 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005695 = TryCopyInitialization(S, Args[ConvIdx],
5696 Cand->BuiltinTypes.ParamTypes[ConvIdx],
5697 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005698 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00005699 return;
5700 }
5701
5702 // Fill in the rest of the conversions.
5703 unsigned NumArgsInProto = Proto->getNumArgs();
5704 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
5705 if (ArgIdx < NumArgsInProto)
5706 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005707 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
5708 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005709 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00005710 else
5711 Cand->Conversions[ConvIdx].setEllipsis();
5712 }
5713}
5714
John McCalld3224162010-01-08 00:58:21 +00005715} // end anonymous namespace
5716
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005717/// PrintOverloadCandidates - When overload resolution fails, prints
5718/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00005719/// set.
Mike Stump11289f42009-09-09 15:08:12 +00005720void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005721Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00005722 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00005723 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005724 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00005725 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00005726 // Sort the candidates by viability and position. Sorting directly would
5727 // be prohibitive, so we make a set of pointers and sort those.
5728 llvm::SmallVector<OverloadCandidate*, 32> Cands;
5729 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
5730 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5731 LastCand = CandidateSet.end();
John McCallfe796dd2010-01-23 05:17:32 +00005732 Cand != LastCand; ++Cand) {
5733 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00005734 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00005735 else if (OCD == OCD_AllCandidates) {
5736 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00005737 if (Cand->Function || Cand->IsSurrogate)
5738 Cands.push_back(Cand);
5739 // Otherwise, this a non-viable builtin candidate. We do not, in general,
5740 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00005741 }
5742 }
5743
John McCallad2587a2010-01-12 00:48:53 +00005744 std::sort(Cands.begin(), Cands.end(),
5745 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00005746
John McCall0d1da222010-01-12 00:44:57 +00005747 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00005748
John McCall12f97bc2010-01-08 04:41:39 +00005749 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00005750 const Diagnostic::OverloadsShown ShowOverloads = Diags.getShowOverloads();
5751 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00005752 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
5753 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00005754
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00005755 // Set an arbitrary limit on the number of candidate functions we'll spam
5756 // the user with. FIXME: This limit should depend on details of the
5757 // candidate list.
5758 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
5759 break;
5760 }
5761 ++CandsShown;
5762
John McCalld3224162010-01-08 00:58:21 +00005763 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00005764 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00005765 else if (Cand->IsSurrogate)
5766 NoteSurrogateCandidate(*this, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00005767 else {
5768 assert(Cand->Viable &&
5769 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00005770 // Generally we only see ambiguities including viable builtin
5771 // operators if overload resolution got screwed up by an
5772 // ambiguous user-defined conversion.
5773 //
5774 // FIXME: It's quite possible for different conversions to see
5775 // different ambiguities, though.
5776 if (!ReportedAmbiguousConversions) {
5777 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
5778 ReportedAmbiguousConversions = true;
5779 }
John McCalld3224162010-01-08 00:58:21 +00005780
John McCall0d1da222010-01-12 00:44:57 +00005781 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00005782 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00005783 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005784 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00005785
5786 if (I != E)
Jeffrey Yasskin5d474d02010-06-11 06:58:43 +00005787 Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005788}
5789
John McCalla0296f72010-03-19 07:35:19 +00005790static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00005791 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00005792 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005793
John McCalla0296f72010-03-19 07:35:19 +00005794 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005795}
5796
Douglas Gregorcd695e52008-11-10 20:40:00 +00005797/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
5798/// an overloaded function (C++ [over.over]), where @p From is an
5799/// expression with overloaded function type and @p ToType is the type
5800/// we're trying to resolve to. For example:
5801///
5802/// @code
5803/// int f(double);
5804/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00005805///
Douglas Gregorcd695e52008-11-10 20:40:00 +00005806/// int (*pfd)(double) = f; // selects f(double)
5807/// @endcode
5808///
5809/// This routine returns the resulting FunctionDecl if it could be
5810/// resolved, and NULL otherwise. When @p Complain is true, this
5811/// routine will emit diagnostics if there is an error.
5812FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005813Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00005814 bool Complain,
5815 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005816 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005817 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005818 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00005819 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005820 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00005821 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005822 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005823 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005824 FunctionType = MemTypePtr->getPointeeType();
5825 IsMember = true;
5826 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005827
Douglas Gregorcd695e52008-11-10 20:40:00 +00005828 // C++ [over.over]p1:
5829 // [...] [Note: any redundant set of parentheses surrounding the
5830 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00005831 // C++ [over.over]p1:
5832 // [...] The overloaded function name can be preceded by the &
5833 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005834 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5835 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
5836 if (OvlExpr->hasExplicitTemplateArgs()) {
5837 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5838 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005839 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00005840
5841 // We expect a pointer or reference to function, or a function pointer.
5842 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
5843 if (!FunctionType->isFunctionType()) {
5844 if (Complain)
5845 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
5846 << OvlExpr->getName() << ToType;
5847
5848 return 0;
5849 }
5850
5851 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005852
Douglas Gregorcd695e52008-11-10 20:40:00 +00005853 // Look through all of the overloaded functions, searching for one
5854 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00005855 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005856 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
5857
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005858 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00005859 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5860 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005861 // Look through any using declarations to find the underlying function.
5862 NamedDecl *Fn = (*I)->getUnderlyingDecl();
5863
Douglas Gregorcd695e52008-11-10 20:40:00 +00005864 // C++ [over.over]p3:
5865 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00005866 // targets of type "pointer-to-function" or "reference-to-function."
5867 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005868 // type "pointer-to-member-function."
5869 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00005870
Mike Stump11289f42009-09-09 15:08:12 +00005871 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005872 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00005873 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005874 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00005875 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005876 // static when converting to member pointer.
5877 if (Method->isStatic() == IsMember)
5878 continue;
5879 } else if (IsMember)
5880 continue;
Mike Stump11289f42009-09-09 15:08:12 +00005881
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005882 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005883 // If the name is a function template, template argument deduction is
5884 // done (14.8.2.2), and if the argument deduction succeeds, the
5885 // resulting template argument list is used to generate a single
5886 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005887 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005888 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00005889 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005890 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00005891 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00005892 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00005893 FunctionType, Specialization, Info)) {
5894 // FIXME: make a note of the failed deduction for diagnostics.
5895 (void)Result;
5896 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005897 // FIXME: If the match isn't exact, shouldn't we just drop this as
5898 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00005899 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00005900 == Context.getCanonicalType(Specialization->getType()));
John McCalla0296f72010-03-19 07:35:19 +00005901 Matches.push_back(std::make_pair(I.getPair(),
5902 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor9b146582009-07-08 20:55:45 +00005903 }
John McCalld14a8642009-11-21 08:51:07 +00005904
5905 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00005906 }
Mike Stump11289f42009-09-09 15:08:12 +00005907
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005908 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005909 // Skip non-static functions when converting to pointer, and static
5910 // when converting to member pointer.
5911 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00005912 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00005913
5914 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00005915 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00005916 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005917 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005918 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005919
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005920 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00005921 QualType ResultTy;
5922 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5923 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5924 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00005925 Matches.push_back(std::make_pair(I.getPair(),
5926 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005927 FoundNonTemplateFunction = true;
5928 }
Mike Stump11289f42009-09-09 15:08:12 +00005929 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005930 }
5931
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005932 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00005933 if (Matches.empty()) {
5934 if (Complain) {
5935 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
5936 << OvlExpr->getName() << FunctionType;
5937 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5938 E = OvlExpr->decls_end();
5939 I != E; ++I)
5940 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
5941 NoteOverloadCandidate(F);
5942 }
5943
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005944 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00005945 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00005946 FunctionDecl *Result = Matches[0].second;
John McCall16df1e52010-03-30 21:47:33 +00005947 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005948 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCall58cc69d2010-01-27 01:50:18 +00005949 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00005950 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005951 return Result;
5952 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005953
5954 // C++ [over.over]p4:
5955 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00005956 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005957 // [...] and any given function template specialization F1 is
5958 // eliminated if the set contains a second function template
5959 // specialization whose function template is more specialized
5960 // than the function template of F1 according to the partial
5961 // ordering rules of 14.5.5.2.
5962
5963 // The algorithm specified above is quadratic. We instead use a
5964 // two-pass algorithm (similar to the one used to identify the
5965 // best viable function in an overload set) that identifies the
5966 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00005967
5968 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
5969 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5970 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00005971
5972 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00005973 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005974 TPOC_Other, From->getLocStart(),
5975 PDiag(),
5976 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00005977 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00005978 PDiag(diag::note_ovl_candidate)
5979 << (unsigned) oc_function_template);
John McCalla0296f72010-03-19 07:35:19 +00005980 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCall58cc69d2010-01-27 01:50:18 +00005981 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00005982 FoundResult = Matches[Result - MatchesCopy.begin()].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00005983 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00005984 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall4fa0d5f2010-05-06 18:15:07 +00005985 DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc());
5986 }
John McCall58cc69d2010-01-27 01:50:18 +00005987 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005988 }
Mike Stump11289f42009-09-09 15:08:12 +00005989
Douglas Gregorfae1d712009-09-26 03:56:17 +00005990 // [...] any function template specializations in the set are
5991 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00005992 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00005993 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00005994 ++I;
5995 else {
John McCalla0296f72010-03-19 07:35:19 +00005996 Matches[I] = Matches[--N];
5997 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00005998 }
5999 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00006000
Mike Stump11289f42009-09-09 15:08:12 +00006001 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006002 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00006003 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006004 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00006005 FoundResult = Matches[0].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00006006 if (Complain) {
John McCalla0296f72010-03-19 07:35:19 +00006007 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
John McCall4fa0d5f2010-05-06 18:15:07 +00006008 DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc());
6009 }
John McCalla0296f72010-03-19 07:35:19 +00006010 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006011 }
Mike Stump11289f42009-09-09 15:08:12 +00006012
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006013 // FIXME: We should probably return the same thing that BestViableFunction
6014 // returns (even if we issue the diagnostics here).
6015 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006016 << Matches[0].second->getDeclName();
6017 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6018 NoteOverloadCandidate(Matches[I].second);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006019 return 0;
6020}
6021
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006022/// \brief Given an expression that refers to an overloaded function, try to
6023/// resolve that overloaded function expression down to a single function.
6024///
6025/// This routine can only resolve template-ids that refer to a single function
6026/// template, where that template-id refers to a single template whose template
6027/// arguments are either provided by the template-id or have defaults,
6028/// as described in C++0x [temp.arg.explicit]p3.
6029FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6030 // C++ [over.over]p1:
6031 // [...] [Note: any redundant set of parentheses surrounding the
6032 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006033 // C++ [over.over]p1:
6034 // [...] The overloaded function name can be preceded by the &
6035 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00006036
6037 if (From->getType() != Context.OverloadTy)
6038 return 0;
6039
6040 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006041
6042 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00006043 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006044 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00006045
6046 TemplateArgumentListInfo ExplicitTemplateArgs;
6047 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006048
6049 // Look through all of the overloaded functions, searching for one
6050 // whose type matches exactly.
6051 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00006052 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6053 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006054 // C++0x [temp.arg.explicit]p3:
6055 // [...] In contexts where deduction is done and fails, or in contexts
6056 // where deduction is not done, if a template argument list is
6057 // specified and it, along with any default template arguments,
6058 // identifies a single function template specialization, then the
6059 // template-id is an lvalue for the function template specialization.
6060 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
6061
6062 // C++ [over.over]p2:
6063 // If the name is a function template, template argument deduction is
6064 // done (14.8.2.2), and if the argument deduction succeeds, the
6065 // resulting template argument list is used to generate a single
6066 // function template specialization, which is added to the set of
6067 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006068 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006069 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006070 if (TemplateDeductionResult Result
6071 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6072 Specialization, Info)) {
6073 // FIXME: make a note of the failed deduction for diagnostics.
6074 (void)Result;
6075 continue;
6076 }
6077
6078 // Multiple matches; we can't resolve to a single declaration.
6079 if (Matched)
6080 return 0;
6081
6082 Matched = Specialization;
6083 }
6084
6085 return Matched;
6086}
6087
Douglas Gregorcabea402009-09-22 15:41:20 +00006088/// \brief Add a single candidate to the overload set.
6089static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00006090 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00006091 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006092 Expr **Args, unsigned NumArgs,
6093 OverloadCandidateSet &CandidateSet,
6094 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00006095 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00006096 if (isa<UsingShadowDecl>(Callee))
6097 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6098
Douglas Gregorcabea402009-09-22 15:41:20 +00006099 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00006100 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00006101 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006102 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006103 return;
John McCalld14a8642009-11-21 08:51:07 +00006104 }
6105
6106 if (FunctionTemplateDecl *FuncTemplate
6107 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00006108 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6109 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006110 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00006111 return;
6112 }
6113
6114 assert(false && "unhandled case in overloaded call candidate");
6115
6116 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00006117}
6118
6119/// \brief Add the overload candidates named by callee and/or found by argument
6120/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00006121void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00006122 Expr **Args, unsigned NumArgs,
6123 OverloadCandidateSet &CandidateSet,
6124 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00006125
6126#ifndef NDEBUG
6127 // Verify that ArgumentDependentLookup is consistent with the rules
6128 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00006129 //
Douglas Gregorcabea402009-09-22 15:41:20 +00006130 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6131 // and let Y be the lookup set produced by argument dependent
6132 // lookup (defined as follows). If X contains
6133 //
6134 // -- a declaration of a class member, or
6135 //
6136 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00006137 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00006138 //
6139 // -- a declaration that is neither a function or a function
6140 // template
6141 //
6142 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00006143
John McCall57500772009-12-16 12:17:52 +00006144 if (ULE->requiresADL()) {
6145 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6146 E = ULE->decls_end(); I != E; ++I) {
6147 assert(!(*I)->getDeclContext()->isRecord());
6148 assert(isa<UsingShadowDecl>(*I) ||
6149 !(*I)->getDeclContext()->isFunctionOrMethod());
6150 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00006151 }
6152 }
6153#endif
6154
John McCall57500772009-12-16 12:17:52 +00006155 // It would be nice to avoid this copy.
6156 TemplateArgumentListInfo TABuffer;
6157 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6158 if (ULE->hasExplicitTemplateArgs()) {
6159 ULE->copyTemplateArgumentsInto(TABuffer);
6160 ExplicitTemplateArgs = &TABuffer;
6161 }
6162
6163 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6164 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00006165 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006166 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00006167 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00006168
John McCall57500772009-12-16 12:17:52 +00006169 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00006170 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6171 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006172 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006173 CandidateSet,
6174 PartialOverloading);
6175}
John McCalld681c392009-12-16 08:11:27 +00006176
John McCall57500772009-12-16 12:17:52 +00006177static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
6178 Expr **Args, unsigned NumArgs) {
6179 Fn->Destroy(SemaRef.Context);
6180 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
6181 Args[Arg]->Destroy(SemaRef.Context);
6182 return SemaRef.ExprError();
6183}
6184
John McCalld681c392009-12-16 08:11:27 +00006185/// Attempts to recover from a call where no functions were found.
6186///
6187/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00006188static Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006189BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00006190 UnresolvedLookupExpr *ULE,
6191 SourceLocation LParenLoc,
6192 Expr **Args, unsigned NumArgs,
6193 SourceLocation *CommaLocs,
6194 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00006195
6196 CXXScopeSpec SS;
6197 if (ULE->getQualifier()) {
6198 SS.setScopeRep(ULE->getQualifier());
6199 SS.setRange(ULE->getQualifierRange());
6200 }
6201
John McCall57500772009-12-16 12:17:52 +00006202 TemplateArgumentListInfo TABuffer;
6203 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6204 if (ULE->hasExplicitTemplateArgs()) {
6205 ULE->copyTemplateArgumentsInto(TABuffer);
6206 ExplicitTemplateArgs = &TABuffer;
6207 }
6208
John McCalld681c392009-12-16 08:11:27 +00006209 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6210 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00006211 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCall57500772009-12-16 12:17:52 +00006212 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCalld681c392009-12-16 08:11:27 +00006213
John McCall57500772009-12-16 12:17:52 +00006214 assert(!R.empty() && "lookup results empty despite recovery");
6215
6216 // Build an implicit member call if appropriate. Just drop the
6217 // casts and such from the call, we don't really care.
6218 Sema::OwningExprResult NewFn = SemaRef.ExprError();
6219 if ((*R.begin())->isCXXClassMember())
6220 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6221 else if (ExplicitTemplateArgs)
6222 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6223 else
6224 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6225
6226 if (NewFn.isInvalid())
6227 return Destroy(SemaRef, Fn, Args, NumArgs);
6228
6229 Fn->Destroy(SemaRef.Context);
6230
6231 // This shouldn't cause an infinite loop because we're giving it
6232 // an expression with non-empty lookup results, which should never
6233 // end up here.
6234 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
6235 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
6236 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006237}
Douglas Gregor4038cf42010-06-08 17:35:15 +00006238
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006239/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00006240/// (which eventually refers to the declaration Func) and the call
6241/// arguments Args/NumArgs, attempt to resolve the function call down
6242/// to a specific function. If overload resolution succeeds, returns
6243/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00006244/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006245/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00006246Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006247Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00006248 SourceLocation LParenLoc,
6249 Expr **Args, unsigned NumArgs,
6250 SourceLocation *CommaLocs,
6251 SourceLocation RParenLoc) {
6252#ifndef NDEBUG
6253 if (ULE->requiresADL()) {
6254 // To do ADL, we must have found an unqualified name.
6255 assert(!ULE->getQualifier() && "qualified name with ADL");
6256
6257 // We don't perform ADL for implicit declarations of builtins.
6258 // Verify that this was correctly set up.
6259 FunctionDecl *F;
6260 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6261 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6262 F->getBuiltinID() && F->isImplicit())
6263 assert(0 && "performing ADL for builtin");
6264
6265 // We don't perform ADL in C.
6266 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6267 }
6268#endif
6269
John McCallbc077cf2010-02-08 23:07:23 +00006270 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00006271
John McCall57500772009-12-16 12:17:52 +00006272 // Add the functions denoted by the callee to the set of candidate
6273 // functions, including those from argument-dependent lookup.
6274 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00006275
6276 // If we found nothing, try to recover.
6277 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6278 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00006279 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006280 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall57500772009-12-16 12:17:52 +00006281 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006282
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006283 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006284 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00006285 case OR_Success: {
6286 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00006287 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006288 DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00006289 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00006290 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6291 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006292
6293 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00006294 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006295 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00006296 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006297 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006298 break;
6299
6300 case OR_Ambiguous:
6301 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00006302 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006303 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006304 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006305
6306 case OR_Deleted:
6307 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6308 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00006309 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00006310 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006311 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006312 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006313 }
6314
6315 // Overload resolution failed. Destroy all of the subexpressions and
6316 // return NULL.
6317 Fn->Destroy(Context);
6318 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
6319 Args[Arg]->Destroy(Context);
John McCall57500772009-12-16 12:17:52 +00006320 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006321}
6322
John McCall4c4c1df2010-01-26 03:27:55 +00006323static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00006324 return Functions.size() > 1 ||
6325 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6326}
6327
Douglas Gregor084d8552009-03-13 23:49:33 +00006328/// \brief Create a unary operation that may resolve to an overloaded
6329/// operator.
6330///
6331/// \param OpLoc The location of the operator itself (e.g., '*').
6332///
6333/// \param OpcIn The UnaryOperator::Opcode that describes this
6334/// operator.
6335///
6336/// \param Functions The set of non-member functions that will be
6337/// considered by overload resolution. The caller needs to build this
6338/// set based on the context using, e.g.,
6339/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6340/// set should not contain any member functions; those will be added
6341/// by CreateOverloadedUnaryOp().
6342///
6343/// \param input The input argument.
John McCall4c4c1df2010-01-26 03:27:55 +00006344Sema::OwningExprResult
6345Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6346 const UnresolvedSetImpl &Fns,
6347 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006348 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
6349 Expr *Input = (Expr *)input.get();
6350
6351 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6352 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6353 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6354
6355 Expr *Args[2] = { Input, 0 };
6356 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00006357
Douglas Gregor084d8552009-03-13 23:49:33 +00006358 // For post-increment and post-decrement, add the implicit '0' as
6359 // the second argument, so that we know this is a post-increment or
6360 // post-decrement.
6361 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
6362 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00006363 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00006364 SourceLocation());
6365 NumArgs = 2;
6366 }
6367
6368 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00006369 if (Fns.empty())
6370 return Owned(new (Context) UnaryOperator(input.takeAs<Expr>(),
6371 Opc,
6372 Context.DependentTy,
6373 OpLoc));
6374
John McCall58cc69d2010-01-27 01:50:18 +00006375 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006376 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006377 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006378 0, SourceRange(), OpName, OpLoc,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006379 /*ADL*/ true, IsOverloaded(Fns),
6380 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00006381 input.release();
6382 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6383 &Args[0], NumArgs,
6384 Context.DependentTy,
6385 OpLoc));
6386 }
6387
6388 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006389 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006390
6391 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006392 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00006393
6394 // Add operator candidates that are member functions.
6395 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6396
John McCall4c4c1df2010-01-26 03:27:55 +00006397 // Add candidates from ADL.
6398 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00006399 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00006400 /*ExplicitTemplateArgs*/ 0,
6401 CandidateSet);
6402
Douglas Gregor084d8552009-03-13 23:49:33 +00006403 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006404 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00006405
6406 // Perform overload resolution.
6407 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006408 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006409 case OR_Success: {
6410 // We found a built-in operator or an overloaded operator.
6411 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00006412
Douglas Gregor084d8552009-03-13 23:49:33 +00006413 if (FnDecl) {
6414 // We matched an overloaded operator. Build a call to that
6415 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00006416
Douglas Gregor084d8552009-03-13 23:49:33 +00006417 // Convert the arguments.
6418 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00006419 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006420
John McCall16df1e52010-03-30 21:47:33 +00006421 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6422 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00006423 return ExprError();
6424 } else {
6425 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00006426 OwningExprResult InputInit
6427 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006428 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00006429 SourceLocation(),
6430 move(input));
6431 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00006432 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006433
Douglas Gregore6600372009-12-23 17:40:29 +00006434 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006435 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00006436 }
6437
John McCall4fa0d5f2010-05-06 18:15:07 +00006438 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6439
Douglas Gregor084d8552009-03-13 23:49:33 +00006440 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006441 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00006442
Douglas Gregor084d8552009-03-13 23:49:33 +00006443 // Build the actual expression node.
6444 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6445 SourceLocation());
6446 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00006447
Douglas Gregor084d8552009-03-13 23:49:33 +00006448 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00006449 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006450 ExprOwningPtr<CallExpr> TheCall(this,
6451 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00006452 Args, NumArgs, ResultTy, OpLoc));
John McCall4fa0d5f2010-05-06 18:15:07 +00006453
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006454 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6455 FnDecl))
6456 return ExprError();
6457
6458 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00006459 } else {
6460 // We matched a built-in operator. Convert the arguments, then
6461 // break out so that we will build the appropriate built-in
6462 // operator node.
6463 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006464 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00006465 return ExprError();
6466
6467 break;
6468 }
6469 }
6470
6471 case OR_No_Viable_Function:
6472 // No viable function; fall through to handling this as a
6473 // built-in operator, which will produce an error message for us.
6474 break;
6475
6476 case OR_Ambiguous:
6477 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6478 << UnaryOperator::getOpcodeStr(Opc)
6479 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006480 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006481 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006482 return ExprError();
6483
6484 case OR_Deleted:
6485 Diag(OpLoc, diag::err_ovl_deleted_oper)
6486 << Best->Function->isDeleted()
6487 << UnaryOperator::getOpcodeStr(Opc)
6488 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006489 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00006490 return ExprError();
6491 }
6492
6493 // Either we found no viable overloaded operator or we matched a
6494 // built-in operator. In either case, fall through to trying to
6495 // build a built-in operation.
6496 input.release();
6497 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
6498}
6499
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006500/// \brief Create a binary operation that may resolve to an overloaded
6501/// operator.
6502///
6503/// \param OpLoc The location of the operator itself (e.g., '+').
6504///
6505/// \param OpcIn The BinaryOperator::Opcode that describes this
6506/// operator.
6507///
6508/// \param Functions The set of non-member functions that will be
6509/// considered by overload resolution. The caller needs to build this
6510/// set based on the context using, e.g.,
6511/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6512/// set should not contain any member functions; those will be added
6513/// by CreateOverloadedBinOp().
6514///
6515/// \param LHS Left-hand argument.
6516/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00006517Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006518Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006519 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00006520 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006521 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006522 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00006523 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006524
6525 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6526 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6527 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6528
6529 // If either side is type-dependent, create an appropriate dependent
6530 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00006531 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00006532 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006533 // If there are no functions to store, just build a dependent
6534 // BinaryOperator or CompoundAssignment.
6535 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
6536 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6537 Context.DependentTy, OpLoc));
6538
6539 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6540 Context.DependentTy,
6541 Context.DependentTy,
6542 Context.DependentTy,
6543 OpLoc));
6544 }
John McCall4c4c1df2010-01-26 03:27:55 +00006545
6546 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00006547 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006548 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006549 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006550 0, SourceRange(), OpName, OpLoc,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006551 /*ADL*/ true, IsOverloaded(Fns),
6552 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006553 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00006554 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006555 Context.DependentTy,
6556 OpLoc));
6557 }
6558
6559 // If this is the .* operator, which is not overloadable, just
6560 // create a built-in binary operator.
6561 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00006562 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006563
Sebastian Redl6a96bf72009-11-18 23:10:33 +00006564 // If this is the assignment operator, we only perform overload resolution
6565 // if the left-hand side is a class or enumeration type. This is actually
6566 // a hack. The standard requires that we do overload resolution between the
6567 // various built-in candidates, but as DR507 points out, this can lead to
6568 // problems. So we do it this way, which pretty much follows what GCC does.
6569 // Note that we go the traditional code path for compound assignment forms.
6570 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00006571 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006572
Douglas Gregor084d8552009-03-13 23:49:33 +00006573 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006574 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006575
6576 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006577 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006578
6579 // Add operator candidates that are member functions.
6580 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6581
John McCall4c4c1df2010-01-26 03:27:55 +00006582 // Add candidates from ADL.
6583 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6584 Args, 2,
6585 /*ExplicitTemplateArgs*/ 0,
6586 CandidateSet);
6587
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006588 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006589 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006590
6591 // Perform overload resolution.
6592 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006593 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00006594 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006595 // We found a built-in operator or an overloaded operator.
6596 FunctionDecl *FnDecl = Best->Function;
6597
6598 if (FnDecl) {
6599 // We matched an overloaded operator. Build a call to that
6600 // operator.
6601
6602 // Convert the arguments.
6603 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00006604 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00006605 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006606
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006607 OwningExprResult Arg1
6608 = PerformCopyInitialization(
6609 InitializedEntity::InitializeParameter(
6610 FnDecl->getParamDecl(0)),
6611 SourceLocation(),
6612 Owned(Args[1]));
6613 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006614 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006615
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006616 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006617 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006618 return ExprError();
6619
6620 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006621 } else {
6622 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006623 OwningExprResult Arg0
6624 = PerformCopyInitialization(
6625 InitializedEntity::InitializeParameter(
6626 FnDecl->getParamDecl(0)),
6627 SourceLocation(),
6628 Owned(Args[0]));
6629 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006630 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006631
6632 OwningExprResult Arg1
6633 = PerformCopyInitialization(
6634 InitializedEntity::InitializeParameter(
6635 FnDecl->getParamDecl(1)),
6636 SourceLocation(),
6637 Owned(Args[1]));
6638 if (Arg1.isInvalid())
6639 return ExprError();
6640 Args[0] = LHS = Arg0.takeAs<Expr>();
6641 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006642 }
6643
John McCall4fa0d5f2010-05-06 18:15:07 +00006644 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6645
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006646 // Determine the result type
6647 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00006648 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006649 ResultTy = ResultTy.getNonReferenceType();
6650
6651 // Build the actual expression node.
6652 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00006653 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006654 UsualUnaryConversions(FnExpr);
6655
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006656 ExprOwningPtr<CXXOperatorCallExpr>
6657 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6658 Args, 2, ResultTy,
6659 OpLoc));
6660
6661 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6662 FnDecl))
6663 return ExprError();
6664
6665 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006666 } else {
6667 // We matched a built-in operator. Convert the arguments, then
6668 // break out so that we will build the appropriate built-in
6669 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00006670 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006671 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00006672 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006673 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006674 return ExprError();
6675
6676 break;
6677 }
6678 }
6679
Douglas Gregor66950a32009-09-30 21:46:01 +00006680 case OR_No_Viable_Function: {
6681 // C++ [over.match.oper]p9:
6682 // If the operator is the operator , [...] and there are no
6683 // viable functions, then the operator is assumed to be the
6684 // built-in operator and interpreted according to clause 5.
6685 if (Opc == BinaryOperator::Comma)
6686 break;
6687
Sebastian Redl027de2a2009-05-21 11:50:50 +00006688 // For class as left operand for assignment or compound assigment operator
6689 // do not fall through to handling in built-in, but report that no overloaded
6690 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00006691 OwningExprResult Result = ExprError();
6692 if (Args[0]->getType()->isRecordType() &&
6693 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00006694 Diag(OpLoc, diag::err_ovl_no_viable_oper)
6695 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006696 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00006697 } else {
6698 // No viable function; try to create a built-in operation, which will
6699 // produce an error. Then, show the non-viable candidates.
6700 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00006701 }
Douglas Gregor66950a32009-09-30 21:46:01 +00006702 assert(Result.isInvalid() &&
6703 "C++ binary operator overloading is missing candidates!");
6704 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00006705 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006706 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00006707 return move(Result);
6708 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006709
6710 case OR_Ambiguous:
6711 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6712 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006713 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006714 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006715 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006716 return ExprError();
6717
6718 case OR_Deleted:
6719 Diag(OpLoc, diag::err_ovl_deleted_oper)
6720 << Best->Function->isDeleted()
6721 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006722 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006723 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006724 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00006725 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006726
Douglas Gregor66950a32009-09-30 21:46:01 +00006727 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00006728 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006729}
6730
Sebastian Redladba46e2009-10-29 20:17:01 +00006731Action::OwningExprResult
6732Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
6733 SourceLocation RLoc,
6734 ExprArg Base, ExprArg Idx) {
6735 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
6736 static_cast<Expr*>(Idx.get()) };
6737 DeclarationName OpName =
6738 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
6739
6740 // If either side is type-dependent, create an appropriate dependent
6741 // expression.
6742 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
6743
John McCall58cc69d2010-01-27 01:50:18 +00006744 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006745 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006746 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006747 0, SourceRange(), OpName, LLoc,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006748 /*ADL*/ true, /*Overloaded*/ false,
6749 UnresolvedSetIterator(),
6750 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00006751 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00006752
6753 Base.release();
6754 Idx.release();
6755 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
6756 Args, 2,
6757 Context.DependentTy,
6758 RLoc));
6759 }
6760
6761 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006762 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006763
6764 // Subscript can only be overloaded as a member function.
6765
6766 // Add operator candidates that are member functions.
6767 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6768
6769 // Add builtin operator candidates.
6770 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6771
6772 // Perform overload resolution.
6773 OverloadCandidateSet::iterator Best;
6774 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
6775 case OR_Success: {
6776 // We found a built-in operator or an overloaded operator.
6777 FunctionDecl *FnDecl = Best->Function;
6778
6779 if (FnDecl) {
6780 // We matched an overloaded operator. Build a call to that
6781 // operator.
6782
John McCalla0296f72010-03-19 07:35:19 +00006783 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006784 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00006785
Sebastian Redladba46e2009-10-29 20:17:01 +00006786 // Convert the arguments.
6787 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006788 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006789 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00006790 return ExprError();
6791
Anders Carlssona68e51e2010-01-29 18:37:50 +00006792 // Convert the arguments.
6793 OwningExprResult InputInit
6794 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6795 FnDecl->getParamDecl(0)),
6796 SourceLocation(),
6797 Owned(Args[1]));
6798 if (InputInit.isInvalid())
6799 return ExprError();
6800
6801 Args[1] = InputInit.takeAs<Expr>();
6802
Sebastian Redladba46e2009-10-29 20:17:01 +00006803 // Determine the result type
6804 QualType ResultTy
6805 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
6806 ResultTy = ResultTy.getNonReferenceType();
6807
6808 // Build the actual expression node.
6809 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6810 LLoc);
6811 UsualUnaryConversions(FnExpr);
6812
6813 Base.release();
6814 Idx.release();
6815 ExprOwningPtr<CXXOperatorCallExpr>
6816 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
6817 FnExpr, Args, 2,
6818 ResultTy, RLoc));
6819
6820 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
6821 FnDecl))
6822 return ExprError();
6823
6824 return MaybeBindToTemporary(TheCall.release());
6825 } else {
6826 // We matched a built-in operator. Convert the arguments, then
6827 // break out so that we will build the appropriate built-in
6828 // operator node.
6829 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006830 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00006831 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006832 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00006833 return ExprError();
6834
6835 break;
6836 }
6837 }
6838
6839 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00006840 if (CandidateSet.empty())
6841 Diag(LLoc, diag::err_ovl_no_oper)
6842 << Args[0]->getType() << /*subscript*/ 0
6843 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6844 else
6845 Diag(LLoc, diag::err_ovl_no_viable_subscript)
6846 << Args[0]->getType()
6847 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006848 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00006849 "[]", LLoc);
6850 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00006851 }
6852
6853 case OR_Ambiguous:
6854 Diag(LLoc, diag::err_ovl_ambiguous_oper)
6855 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006856 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00006857 "[]", LLoc);
6858 return ExprError();
6859
6860 case OR_Deleted:
6861 Diag(LLoc, diag::err_ovl_deleted_oper)
6862 << Best->Function->isDeleted() << "[]"
6863 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006864 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00006865 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006866 return ExprError();
6867 }
6868
6869 // We matched a built-in operator; build it.
6870 Base.release();
6871 Idx.release();
6872 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
6873 Owned(Args[1]), RLoc);
6874}
6875
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006876/// BuildCallToMemberFunction - Build a call to a member
6877/// function. MemExpr is the expression that refers to the member
6878/// function (and includes the object parameter), Args/NumArgs are the
6879/// arguments to the function call (not including the object
6880/// parameter). The caller needs to validate that the member
6881/// expression refers to a member function or an overloaded member
6882/// function.
John McCall2d74de92009-12-01 22:10:20 +00006883Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00006884Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
6885 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006886 unsigned NumArgs, SourceLocation *CommaLocs,
6887 SourceLocation RParenLoc) {
6888 // Dig out the member expression. This holds both the object
6889 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00006890 Expr *NakedMemExpr = MemExprE->IgnoreParens();
6891
John McCall10eae182009-11-30 22:42:35 +00006892 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006893 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00006894 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006895 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00006896 if (isa<MemberExpr>(NakedMemExpr)) {
6897 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00006898 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00006899 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006900 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00006901 } else {
6902 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006903 Qualifier = UnresExpr->getQualifier();
6904
John McCall6e9f8f62009-12-03 04:06:58 +00006905 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00006906
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006907 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00006908 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00006909
John McCall2d74de92009-12-01 22:10:20 +00006910 // FIXME: avoid copy.
6911 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6912 if (UnresExpr->hasExplicitTemplateArgs()) {
6913 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6914 TemplateArgs = &TemplateArgsBuffer;
6915 }
6916
John McCall10eae182009-11-30 22:42:35 +00006917 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6918 E = UnresExpr->decls_end(); I != E; ++I) {
6919
John McCall6e9f8f62009-12-03 04:06:58 +00006920 NamedDecl *Func = *I;
6921 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6922 if (isa<UsingShadowDecl>(Func))
6923 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6924
John McCall10eae182009-11-30 22:42:35 +00006925 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00006926 // If explicit template arguments were provided, we can't call a
6927 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00006928 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00006929 continue;
6930
John McCalla0296f72010-03-19 07:35:19 +00006931 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00006932 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006933 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006934 } else {
John McCall10eae182009-11-30 22:42:35 +00006935 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00006936 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006937 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006938 CandidateSet,
6939 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006940 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006941 }
Mike Stump11289f42009-09-09 15:08:12 +00006942
John McCall10eae182009-11-30 22:42:35 +00006943 DeclarationName DeclName = UnresExpr->getMemberName();
6944
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006945 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00006946 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006947 case OR_Success:
6948 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00006949 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00006950 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006951 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006952 break;
6953
6954 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00006955 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006956 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006957 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006958 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006959 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006960 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006961
6962 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00006963 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006964 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006965 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006966 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006967 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006968
6969 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00006970 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00006971 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00006972 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006973 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006974 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006975 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006976 }
6977
John McCall16df1e52010-03-30 21:47:33 +00006978 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00006979
John McCall2d74de92009-12-01 22:10:20 +00006980 // If overload resolution picked a static member, build a
6981 // non-member call based on that function.
6982 if (Method->isStatic()) {
6983 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6984 Args, NumArgs, RParenLoc);
6985 }
6986
John McCall10eae182009-11-30 22:42:35 +00006987 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006988 }
6989
6990 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00006991 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00006992 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00006993 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006994 Method->getResultType().getNonReferenceType(),
6995 RParenLoc));
6996
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006997 // Check for a valid return type.
6998 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6999 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00007000 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007001
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007002 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00007003 // We only need to do this if there was actually an overload; otherwise
7004 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00007005 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00007006 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00007007 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7008 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00007009 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007010 MemExpr->setBase(ObjectArg);
7011
7012 // Convert the rest of the arguments
Douglas Gregorc8be9522010-05-04 18:18:31 +00007013 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00007014 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007015 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00007016 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007017
Anders Carlssonbc4c1072009-08-16 01:56:34 +00007018 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00007019 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00007020
John McCall2d74de92009-12-01 22:10:20 +00007021 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007022}
7023
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007024/// BuildCallToObjectOfClassType - Build a call to an object of class
7025/// type (C++ [over.call.object]), which can end up invoking an
7026/// overloaded function call operator (@c operator()) or performing a
7027/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00007028Sema::ExprResult
7029Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00007030 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007031 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00007032 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007033 SourceLocation RParenLoc) {
7034 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007035 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00007036
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007037 // C++ [over.call.object]p1:
7038 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00007039 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007040 // candidate functions includes at least the function call
7041 // operators of T. The function call operators of T are obtained by
7042 // ordinary lookup of the name operator() in the context of
7043 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00007044 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00007045 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007046
7047 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007048 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007049 << Object->getSourceRange()))
7050 return true;
7051
John McCall27b18f82009-11-17 02:14:36 +00007052 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7053 LookupQualifiedName(R, Record->getDecl());
7054 R.suppressDiagnostics();
7055
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007056 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00007057 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007058 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00007059 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00007060 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00007061 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007062
Douglas Gregorab7897a2008-11-19 22:57:39 +00007063 // C++ [over.call.object]p2:
7064 // In addition, for each conversion function declared in T of the
7065 // form
7066 //
7067 // operator conversion-type-id () cv-qualifier;
7068 //
7069 // where cv-qualifier is the same cv-qualification as, or a
7070 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00007071 // denotes the type "pointer to function of (P1,...,Pn) returning
7072 // R", or the type "reference to pointer to function of
7073 // (P1,...,Pn) returning R", or the type "reference to function
7074 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00007075 // is also considered as a candidate function. Similarly,
7076 // surrogate call functions are added to the set of candidate
7077 // functions for each conversion function declared in an
7078 // accessible base class provided the function is not hidden
7079 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00007080 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00007081 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00007082 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00007083 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00007084 NamedDecl *D = *I;
7085 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7086 if (isa<UsingShadowDecl>(D))
7087 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7088
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007089 // Skip over templated conversion functions; they aren't
7090 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00007091 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007092 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007093
John McCall6e9f8f62009-12-03 04:06:58 +00007094 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00007095
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007096 // Strip the reference type (if any) and then the pointer type (if
7097 // any) to get down to what might be a function type.
7098 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7099 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7100 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007101
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007102 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00007103 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00007104 Object->getType(), Args, NumArgs,
7105 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007106 }
Mike Stump11289f42009-09-09 15:08:12 +00007107
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007108 // Perform overload resolution.
7109 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007110 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007111 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00007112 // Overload resolution succeeded; we'll build the appropriate call
7113 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007114 break;
7115
7116 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00007117 if (CandidateSet.empty())
7118 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7119 << Object->getType() << /*call*/ 1
7120 << Object->getSourceRange();
7121 else
7122 Diag(Object->getSourceRange().getBegin(),
7123 diag::err_ovl_no_viable_object_call)
7124 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007125 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007126 break;
7127
7128 case OR_Ambiguous:
7129 Diag(Object->getSourceRange().getBegin(),
7130 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007131 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007132 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007133 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007134
7135 case OR_Deleted:
7136 Diag(Object->getSourceRange().getBegin(),
7137 diag::err_ovl_deleted_object_call)
7138 << Best->Function->isDeleted()
7139 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007140 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007141 break;
Mike Stump11289f42009-09-09 15:08:12 +00007142 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007143
Douglas Gregorab7897a2008-11-19 22:57:39 +00007144 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007145 // We had an error; delete all of the subexpressions and return
7146 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00007147 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007148 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00007149 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007150 return true;
7151 }
7152
Douglas Gregorab7897a2008-11-19 22:57:39 +00007153 if (Best->Function == 0) {
7154 // Since there is no function declaration, this is one of the
7155 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00007156 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00007157 = cast<CXXConversionDecl>(
7158 Best->Conversions[0].UserDefined.ConversionFunction);
7159
John McCalla0296f72010-03-19 07:35:19 +00007160 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007161 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007162
Douglas Gregorab7897a2008-11-19 22:57:39 +00007163 // We selected one of the surrogate functions that converts the
7164 // object parameter to a function pointer. Perform the conversion
7165 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00007166
7167 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007168 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00007169 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7170 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007171
Fariborz Jahanian774cf792009-09-28 18:35:46 +00007172 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007173 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
Douglas Gregore5e775b2010-04-13 15:50:39 +00007174 CommaLocs, RParenLoc).result();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007175 }
7176
John McCalla0296f72010-03-19 07:35:19 +00007177 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007178 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007179
Douglas Gregorab7897a2008-11-19 22:57:39 +00007180 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7181 // that calls this method, using Object for the implicit object
7182 // parameter and passing along the remaining arguments.
7183 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00007184 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007185
7186 unsigned NumArgsInProto = Proto->getNumArgs();
7187 unsigned NumArgsToCheck = NumArgs;
7188
7189 // Build the full argument list for the method call (the
7190 // implicit object parameter is placed at the beginning of the
7191 // list).
7192 Expr **MethodArgs;
7193 if (NumArgs < NumArgsInProto) {
7194 NumArgsToCheck = NumArgsInProto;
7195 MethodArgs = new Expr*[NumArgsInProto + 1];
7196 } else {
7197 MethodArgs = new Expr*[NumArgs + 1];
7198 }
7199 MethodArgs[0] = Object;
7200 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7201 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00007202
7203 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00007204 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007205 UsualUnaryConversions(NewFn);
7206
7207 // Once we've built TheCall, all of the expressions are properly
7208 // owned.
7209 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00007210 ExprOwningPtr<CXXOperatorCallExpr>
7211 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007212 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00007213 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007214 delete [] MethodArgs;
7215
Anders Carlsson3d5829c2009-10-13 21:49:31 +00007216 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
7217 Method))
7218 return true;
7219
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007220 // We may have default arguments. If so, we need to allocate more
7221 // slots in the call for them.
7222 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00007223 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007224 else if (NumArgs > NumArgsInProto)
7225 NumArgsToCheck = NumArgsInProto;
7226
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007227 bool IsError = false;
7228
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007229 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007230 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007231 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007232 TheCall->setArg(0, Object);
7233
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007234
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007235 // Check the argument types.
7236 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007237 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007238 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007239 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00007240
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007241 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007242
7243 OwningExprResult InputInit
7244 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7245 Method->getParamDecl(i)),
7246 SourceLocation(), Owned(Arg));
7247
7248 IsError |= InputInit.isInvalid();
7249 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007250 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00007251 OwningExprResult DefArg
7252 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7253 if (DefArg.isInvalid()) {
7254 IsError = true;
7255 break;
7256 }
7257
7258 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007259 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007260
7261 TheCall->setArg(i + 1, Arg);
7262 }
7263
7264 // If this is a variadic call, handle args passed through "...".
7265 if (Proto->isVariadic()) {
7266 // Promote the arguments (C99 6.5.2.2p7).
7267 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7268 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00007269 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007270 TheCall->setArg(i + 1, Arg);
7271 }
7272 }
7273
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007274 if (IsError) return true;
7275
Anders Carlssonbc4c1072009-08-16 01:56:34 +00007276 if (CheckFunctionCall(Method, TheCall.get()))
7277 return true;
7278
Douglas Gregore5e775b2010-04-13 15:50:39 +00007279 return MaybeBindToTemporary(TheCall.release()).result();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007280}
7281
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007282/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00007283/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007284/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00007285Sema::OwningExprResult
7286Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
7287 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007288 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00007289
John McCallbc077cf2010-02-08 23:07:23 +00007290 SourceLocation Loc = Base->getExprLoc();
7291
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007292 // C++ [over.ref]p1:
7293 //
7294 // [...] An expression x->m is interpreted as (x.operator->())->m
7295 // for a class object x of type T if T::operator->() exists and if
7296 // the operator is selected as the best match function by the
7297 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007298 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00007299 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007300 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00007301
John McCallbc077cf2010-02-08 23:07:23 +00007302 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00007303 PDiag(diag::err_typecheck_incomplete_tag)
7304 << Base->getSourceRange()))
7305 return ExprError();
7306
John McCall27b18f82009-11-17 02:14:36 +00007307 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7308 LookupQualifiedName(R, BaseRecord->getDecl());
7309 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00007310
7311 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00007312 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007313 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007314 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00007315 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007316
7317 // Perform overload resolution.
7318 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007319 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007320 case OR_Success:
7321 // Overload resolution succeeded; we'll build the call below.
7322 break;
7323
7324 case OR_No_Viable_Function:
7325 if (CandidateSet.empty())
7326 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00007327 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007328 else
7329 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00007330 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007331 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007332 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007333
7334 case OR_Ambiguous:
7335 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00007336 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007337 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007338 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007339
7340 case OR_Deleted:
7341 Diag(OpLoc, diag::err_ovl_deleted_oper)
7342 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00007343 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007344 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007345 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007346 }
7347
John McCalla0296f72010-03-19 07:35:19 +00007348 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007349 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00007350
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007351 // Convert the object parameter.
7352 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007353 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7354 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00007355 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00007356
7357 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00007358 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007359
7360 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00007361 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7362 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007363 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007364
7365 QualType ResultTy = Method->getResultType().getNonReferenceType();
7366 ExprOwningPtr<CXXOperatorCallExpr>
7367 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7368 &Base, 1, ResultTy, OpLoc));
7369
7370 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
7371 Method))
7372 return ExprError();
7373 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007374}
7375
Douglas Gregorcd695e52008-11-10 20:40:00 +00007376/// FixOverloadedFunctionReference - E is an expression that refers to
7377/// a C++ overloaded function (possibly with some parentheses and
7378/// perhaps a '&' around it). We have resolved the overloaded function
7379/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007380/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00007381Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00007382 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00007383 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007384 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7385 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007386 if (SubExpr == PE->getSubExpr())
7387 return PE->Retain();
7388
7389 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7390 }
7391
7392 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007393 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7394 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00007395 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00007396 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00007397 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00007398 if (SubExpr == ICE->getSubExpr())
7399 return ICE->Retain();
7400
7401 return new (Context) ImplicitCastExpr(ICE->getType(),
7402 ICE->getCastKind(),
Anders Carlsson0c509ee2010-04-24 16:57:13 +00007403 SubExpr, CXXBaseSpecifierArray(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00007404 ICE->isLvalueCast());
7405 }
7406
7407 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00007408 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00007409 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007410 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7411 if (Method->isStatic()) {
7412 // Do nothing: static member functions aren't any different
7413 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00007414 } else {
John McCalle66edc12009-11-24 19:00:30 +00007415 // Fix the sub expression, which really has to be an
7416 // UnresolvedLookupExpr holding an overloaded member function
7417 // or template.
John McCall16df1e52010-03-30 21:47:33 +00007418 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7419 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00007420 if (SubExpr == UnOp->getSubExpr())
7421 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00007422
John McCalld14a8642009-11-21 08:51:07 +00007423 assert(isa<DeclRefExpr>(SubExpr)
7424 && "fixed to something other than a decl ref");
7425 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7426 && "fixed to a member ref with no nested name qualifier");
7427
7428 // We have taken the address of a pointer to member
7429 // function. Perform the computation here so that we get the
7430 // appropriate pointer to member type.
7431 QualType ClassType
7432 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7433 QualType MemPtrType
7434 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7435
7436 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7437 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007438 }
7439 }
John McCall16df1e52010-03-30 21:47:33 +00007440 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7441 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007442 if (SubExpr == UnOp->getSubExpr())
7443 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007444
Douglas Gregor51c538b2009-11-20 19:42:02 +00007445 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7446 Context.getPointerType(SubExpr->getType()),
7447 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00007448 }
John McCalld14a8642009-11-21 08:51:07 +00007449
7450 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00007451 // FIXME: avoid copy.
7452 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00007453 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00007454 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7455 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00007456 }
7457
John McCalld14a8642009-11-21 08:51:07 +00007458 return DeclRefExpr::Create(Context,
7459 ULE->getQualifier(),
7460 ULE->getQualifierRange(),
7461 Fn,
7462 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00007463 Fn->getType(),
7464 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00007465 }
7466
John McCall10eae182009-11-30 22:42:35 +00007467 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00007468 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00007469 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7470 if (MemExpr->hasExplicitTemplateArgs()) {
7471 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7472 TemplateArgs = &TemplateArgsBuffer;
7473 }
John McCall6b51f282009-11-23 01:53:49 +00007474
John McCall2d74de92009-12-01 22:10:20 +00007475 Expr *Base;
7476
7477 // If we're filling in
7478 if (MemExpr->isImplicitAccess()) {
7479 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7480 return DeclRefExpr::Create(Context,
7481 MemExpr->getQualifier(),
7482 MemExpr->getQualifierRange(),
7483 Fn,
7484 MemExpr->getMemberLoc(),
7485 Fn->getType(),
7486 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00007487 } else {
7488 SourceLocation Loc = MemExpr->getMemberLoc();
7489 if (MemExpr->getQualifier())
7490 Loc = MemExpr->getQualifierRange().getBegin();
7491 Base = new (Context) CXXThisExpr(Loc,
7492 MemExpr->getBaseType(),
7493 /*isImplicit=*/true);
7494 }
John McCall2d74de92009-12-01 22:10:20 +00007495 } else
7496 Base = MemExpr->getBase()->Retain();
7497
7498 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007499 MemExpr->isArrow(),
7500 MemExpr->getQualifier(),
7501 MemExpr->getQualifierRange(),
7502 Fn,
John McCall16df1e52010-03-30 21:47:33 +00007503 Found,
John McCall6b51f282009-11-23 01:53:49 +00007504 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00007505 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007506 Fn->getType());
7507 }
7508
Douglas Gregor51c538b2009-11-20 19:42:02 +00007509 assert(false && "Invalid reference to overloaded function");
7510 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00007511}
7512
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007513Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCalla8ae2222010-04-06 21:38:20 +00007514 DeclAccessPair Found,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007515 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00007516 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007517}
7518
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007519} // end namespace clang