blob: af28d46b5fe77a1df9fe0dfde92717137b900e21 [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.
Douglas Gregora3208f92010-06-22 23:41:02 +0000848 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +0000849 ICK = ICK_Vector_Splat;
850 return true;
851 }
852 }
853
854 // If lax vector conversions are permitted and the vector types are of the
855 // same size, we can perform the conversion.
856 if (Context.getLangOptions().LaxVectorConversions &&
857 FromType->isVectorType() && ToType->isVectorType() &&
858 Context.getTypeSize(FromType) == Context.getTypeSize(ToType)) {
859 ICK = ICK_Vector_Conversion;
860 return true;
861 }
862
863 return false;
864}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000865
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000866/// IsStandardConversion - Determines whether there is a standard
867/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
868/// expression From to the type ToType. Standard conversion sequences
869/// only consider non-class types; for conversions that involve class
870/// types, use TryImplicitConversion. If a conversion exists, SCS will
871/// contain the standard conversion sequence required to perform this
872/// conversion and this routine will return true. Otherwise, this
873/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000874bool
875Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000876 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000877 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000878 QualType FromType = From->getType();
879
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000880 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000881 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000882 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000883 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000884 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000885 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000886
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000887 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000888 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000889 if (FromType->isRecordType() || ToType->isRecordType()) {
890 if (getLangOptions().CPlusPlus)
891 return false;
892
Mike Stump11289f42009-09-09 15:08:12 +0000893 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000894 }
895
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000896 // The first conversion can be an lvalue-to-rvalue conversion,
897 // array-to-pointer conversion, or function-to-pointer conversion
898 // (C++ 4p1).
899
Douglas Gregor980fb162010-04-29 18:24:40 +0000900 if (FromType == Context.OverloadTy) {
901 DeclAccessPair AccessPair;
902 if (FunctionDecl *Fn
903 = ResolveAddressOfOverloadedFunction(From, ToType, false,
904 AccessPair)) {
905 // We were able to resolve the address of the overloaded function,
906 // so we can convert to the type of that function.
907 FromType = Fn->getType();
908 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
909 if (!Method->isStatic()) {
910 Type *ClassType
911 = Context.getTypeDeclType(Method->getParent()).getTypePtr();
912 FromType = Context.getMemberPointerType(FromType, ClassType);
913 }
914 }
915
916 // If the "from" expression takes the address of the overloaded
917 // function, update the type of the resulting expression accordingly.
918 if (FromType->getAs<FunctionType>())
919 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
920 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
921 FromType = Context.getPointerType(FromType);
922
923 // Check that we've computed the proper type after overload resolution.
924 assert(Context.hasSameType(FromType,
925 FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
926 } else {
927 return false;
928 }
929 }
Mike Stump11289f42009-09-09 15:08:12 +0000930 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000931 // An lvalue (3.10) of a non-function, non-array type T can be
932 // converted to an rvalue.
933 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000934 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000935 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000936 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000937 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000938
939 // If T is a non-class type, the type of the rvalue is the
940 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000941 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
942 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000943 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000944 } else if (FromType->isArrayType()) {
945 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000946 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000947
948 // An lvalue or rvalue of type "array of N T" or "array of unknown
949 // bound of T" can be converted to an rvalue of type "pointer to
950 // T" (C++ 4.2p1).
951 FromType = Context.getArrayDecayedType(FromType);
952
953 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
954 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +0000955 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000956
957 // For the purpose of ranking in overload resolution
958 // (13.3.3.1.1), this conversion is considered an
959 // array-to-pointer conversion followed by a qualification
960 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000961 SCS.Second = ICK_Identity;
962 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000963 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000964 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000965 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000966 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
967 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000968 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000969
970 // An lvalue of function type T can be converted to an rvalue of
971 // type "pointer to T." The result is a pointer to the
972 // function. (C++ 4.3p1).
973 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000974 } else {
975 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000976 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000977 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000978 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000979
980 // The second conversion can be an integral promotion, floating
981 // point promotion, integral conversion, floating point conversion,
982 // floating-integral conversion, pointer conversion,
983 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000984 // For overloading in C, this can also be a "compatible-type"
985 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000986 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +0000987 ImplicitConversionKind SecondICK = ICK_Identity;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000988 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000989 // The unqualified versions of the types are the same: there's no
990 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000991 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000992 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000993 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000994 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000995 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000996 } else if (IsFloatingPointPromotion(FromType, ToType)) {
997 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000998 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000999 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001000 } else if (IsComplexPromotion(FromType, ToType)) {
1001 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001002 SCS.Second = ICK_Complex_Promotion;
1003 FromType = ToType.getUnqualifiedType();
Douglas Gregorb90df602010-06-16 00:17:44 +00001004 } else if (FromType->isIntegralOrEnumerationType() &&
Douglas Gregor6972a622010-06-16 00:35:25 +00001005 ToType->isIntegralType(Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001006 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001007 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001008 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001009 } else if (FromType->isComplexType() && ToType->isComplexType()) {
1010 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001011 SCS.Second = ICK_Complex_Conversion;
1012 FromType = ToType.getUnqualifiedType();
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001013 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
1014 (ToType->isComplexType() && FromType->isArithmeticType())) {
1015 // Complex-real conversions (C99 6.3.1.7)
1016 SCS.Second = ICK_Complex_Real;
1017 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001018 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001019 // Floating point conversions (C++ 4.8).
1020 SCS.Second = ICK_Floating_Conversion;
1021 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001022 } else if ((FromType->isRealFloatingType() &&
Douglas Gregor6972a622010-06-16 00:35:25 +00001023 ToType->isIntegralType(Context) && !ToType->isBooleanType()) ||
Douglas Gregorb90df602010-06-16 00:17:44 +00001024 (FromType->isIntegralOrEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001025 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001026 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001027 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001028 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +00001029 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1030 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001031 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001032 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001033 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +00001034 } else if (IsMemberPointerConversion(From, FromType, ToType,
1035 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001036 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001037 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +00001038 } else if (ToType->isBooleanType() &&
1039 (FromType->isArithmeticType() ||
1040 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +00001041 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +00001042 FromType->isBlockPointerType() ||
1043 FromType->isMemberPointerType() ||
Douglas Gregora3208f92010-06-22 23:41:02 +00001044 FromType->isNullPtrType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001045 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001046 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001047 FromType = Context.BoolTy;
Douglas Gregor46188682010-05-18 22:42:18 +00001048 } else if (IsVectorConversion(Context, FromType, ToType, SecondICK)) {
1049 SCS.Second = SecondICK;
1050 FromType = ToType.getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001051 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +00001052 Context.typesAreCompatible(ToType, FromType)) {
1053 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001054 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001055 FromType = ToType.getUnqualifiedType();
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001056 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
1057 // Treat a conversion that strips "noreturn" as an identity conversion.
1058 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001059 } else {
1060 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001061 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001062 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001063 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001064
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001065 QualType CanonFrom;
1066 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001067 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +00001068 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001069 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001070 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001071 CanonFrom = Context.getCanonicalType(FromType);
1072 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001073 } else {
1074 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001075 SCS.Third = ICK_Identity;
1076
Mike Stump11289f42009-09-09 15:08:12 +00001077 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001078 // [...] Any difference in top-level cv-qualification is
1079 // subsumed by the initialization itself and does not constitute
1080 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001081 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +00001082 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001083 if (CanonFrom.getLocalUnqualifiedType()
1084 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001085 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1086 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001087 FromType = ToType;
1088 CanonFrom = CanonTo;
1089 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001090 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001091 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001092
1093 // If we have not converted the argument type to the parameter type,
1094 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001095 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001096 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001097
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001098 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001099}
1100
1101/// IsIntegralPromotion - Determines whether the conversion from the
1102/// expression From (whose potentially-adjusted type is FromType) to
1103/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1104/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001105bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001106 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001107 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001108 if (!To) {
1109 return false;
1110 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001111
1112 // An rvalue of type char, signed char, unsigned char, short int, or
1113 // unsigned short int can be converted to an rvalue of type int if
1114 // int can represent all the values of the source type; otherwise,
1115 // the source rvalue can be converted to an rvalue of type unsigned
1116 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001117 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1118 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001119 if (// We can promote any signed, promotable integer type to an int
1120 (FromType->isSignedIntegerType() ||
1121 // We can promote any unsigned integer type whose size is
1122 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001123 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001124 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001125 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001126 }
1127
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001128 return To->getKind() == BuiltinType::UInt;
1129 }
1130
1131 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
1132 // can be converted to an rvalue of the first of the following types
1133 // that can represent all the values of its underlying type: int,
1134 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +00001135
1136 // We pre-calculate the promotion type for enum types.
1137 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
1138 if (ToType->isIntegerType())
1139 return Context.hasSameUnqualifiedType(ToType,
1140 FromEnumType->getDecl()->getPromotionType());
1141
1142 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001143 // Determine whether the type we're converting from is signed or
1144 // unsigned.
1145 bool FromIsSigned;
1146 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +00001147
1148 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1149 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001150
1151 // The types we'll try to promote to, in the appropriate
1152 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001153 QualType PromoteTypes[6] = {
1154 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001155 Context.LongTy, Context.UnsignedLongTy ,
1156 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001157 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001158 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001159 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1160 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001161 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001162 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1163 // We found the type that we can promote to. If this is the
1164 // type we wanted, we have a promotion. Otherwise, no
1165 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001166 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001167 }
1168 }
1169 }
1170
1171 // An rvalue for an integral bit-field (9.6) can be converted to an
1172 // rvalue of type int if int can represent all the values of the
1173 // bit-field; otherwise, it can be converted to unsigned int if
1174 // unsigned int can represent all the values of the bit-field. If
1175 // the bit-field is larger yet, no integral promotion applies to
1176 // it. If the bit-field has an enumerated type, it is treated as any
1177 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001178 // FIXME: We should delay checking of bit-fields until we actually perform the
1179 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001180 using llvm::APSInt;
1181 if (From)
1182 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001183 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001184 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001185 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1186 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1187 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001188
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001189 // Are we promoting to an int from a bitfield that fits in an int?
1190 if (BitWidth < ToSize ||
1191 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1192 return To->getKind() == BuiltinType::Int;
1193 }
Mike Stump11289f42009-09-09 15:08:12 +00001194
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001195 // Are we promoting to an unsigned int from an unsigned bitfield
1196 // that fits into an unsigned int?
1197 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1198 return To->getKind() == BuiltinType::UInt;
1199 }
Mike Stump11289f42009-09-09 15:08:12 +00001200
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001201 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001202 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001203 }
Mike Stump11289f42009-09-09 15:08:12 +00001204
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001205 // An rvalue of type bool can be converted to an rvalue of type int,
1206 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001207 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001208 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001209 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001210
1211 return false;
1212}
1213
1214/// IsFloatingPointPromotion - Determines whether the conversion from
1215/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1216/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001217bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001218 /// An rvalue of type float can be converted to an rvalue of type
1219 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001220 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1221 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001222 if (FromBuiltin->getKind() == BuiltinType::Float &&
1223 ToBuiltin->getKind() == BuiltinType::Double)
1224 return true;
1225
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001226 // C99 6.3.1.5p1:
1227 // When a float is promoted to double or long double, or a
1228 // double is promoted to long double [...].
1229 if (!getLangOptions().CPlusPlus &&
1230 (FromBuiltin->getKind() == BuiltinType::Float ||
1231 FromBuiltin->getKind() == BuiltinType::Double) &&
1232 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1233 return true;
1234 }
1235
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001236 return false;
1237}
1238
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001239/// \brief Determine if a conversion is a complex promotion.
1240///
1241/// A complex promotion is defined as a complex -> complex conversion
1242/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001243/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001244bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001245 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001246 if (!FromComplex)
1247 return false;
1248
John McCall9dd450b2009-09-21 23:43:11 +00001249 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001250 if (!ToComplex)
1251 return false;
1252
1253 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001254 ToComplex->getElementType()) ||
1255 IsIntegralPromotion(0, FromComplex->getElementType(),
1256 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001257}
1258
Douglas Gregor237f96c2008-11-26 23:31:11 +00001259/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1260/// the pointer type FromPtr to a pointer to type ToPointee, with the
1261/// same type qualifiers as FromPtr has on its pointee type. ToType,
1262/// if non-empty, will be a pointer to ToType that may or may not have
1263/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001264static QualType
1265BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001266 QualType ToPointee, QualType ToType,
1267 ASTContext &Context) {
1268 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1269 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001270 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001271
1272 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001273 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001274 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001275 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001276 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001277
1278 // Build a pointer to ToPointee. It has the right qualifiers
1279 // already.
1280 return Context.getPointerType(ToPointee);
1281 }
1282
1283 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +00001284 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001285 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1286 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +00001287}
1288
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001289/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1290/// the FromType, which is an objective-c pointer, to ToType, which may or may
1291/// not have the right set of qualifiers.
1292static QualType
1293BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1294 QualType ToType,
1295 ASTContext &Context) {
1296 QualType CanonFromType = Context.getCanonicalType(FromType);
1297 QualType CanonToType = Context.getCanonicalType(ToType);
1298 Qualifiers Quals = CanonFromType.getQualifiers();
1299
1300 // Exact qualifier match -> return the pointer type we're converting to.
1301 if (CanonToType.getLocalQualifiers() == Quals)
1302 return ToType;
1303
1304 // Just build a canonical type that has the right qualifiers.
1305 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1306}
1307
Mike Stump11289f42009-09-09 15:08:12 +00001308static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001309 bool InOverloadResolution,
1310 ASTContext &Context) {
1311 // Handle value-dependent integral null pointer constants correctly.
1312 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1313 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001314 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001315 return !InOverloadResolution;
1316
Douglas Gregor56751b52009-09-25 04:25:58 +00001317 return Expr->isNullPointerConstant(Context,
1318 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1319 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001320}
Mike Stump11289f42009-09-09 15:08:12 +00001321
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001322/// IsPointerConversion - Determines whether the conversion of the
1323/// expression From, which has the (possibly adjusted) type FromType,
1324/// can be converted to the type ToType via a pointer conversion (C++
1325/// 4.10). If so, returns true and places the converted type (that
1326/// might differ from ToType in its cv-qualifiers at some level) into
1327/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001328///
Douglas Gregora29dc052008-11-27 01:19:21 +00001329/// This routine also supports conversions to and from block pointers
1330/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1331/// pointers to interfaces. FIXME: Once we've determined the
1332/// appropriate overloading rules for Objective-C, we may want to
1333/// split the Objective-C checks into a different routine; however,
1334/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001335/// conversions, so for now they live here. IncompatibleObjC will be
1336/// set if the conversion is an allowed Objective-C conversion that
1337/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001338bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001339 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001340 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001341 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001342 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001343 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1344 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001345
Mike Stump11289f42009-09-09 15:08:12 +00001346 // Conversion from a null pointer constant to any Objective-C pointer type.
1347 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001348 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001349 ConvertedType = ToType;
1350 return true;
1351 }
1352
Douglas Gregor231d1c62008-11-27 00:15:41 +00001353 // Blocks: Block pointers can be converted to void*.
1354 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001355 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001356 ConvertedType = ToType;
1357 return true;
1358 }
1359 // Blocks: A null pointer constant can be converted to a block
1360 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001361 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001362 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001363 ConvertedType = ToType;
1364 return true;
1365 }
1366
Sebastian Redl576fd422009-05-10 18:38:11 +00001367 // If the left-hand-side is nullptr_t, the right side can be a null
1368 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001369 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001370 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001371 ConvertedType = ToType;
1372 return true;
1373 }
1374
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001375 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001376 if (!ToTypePtr)
1377 return false;
1378
1379 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001380 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001381 ConvertedType = ToType;
1382 return true;
1383 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001384
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001385 // Beyond this point, both types need to be pointers
1386 // , including objective-c pointers.
1387 QualType ToPointeeType = ToTypePtr->getPointeeType();
1388 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1389 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1390 ToType, Context);
1391 return true;
1392
1393 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001394 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001395 if (!FromTypePtr)
1396 return false;
1397
1398 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001399
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001400 // An rvalue of type "pointer to cv T," where T is an object type,
1401 // can be converted to an rvalue of type "pointer to cv void" (C++
1402 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +00001403 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001404 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001405 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001406 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001407 return true;
1408 }
1409
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001410 // When we're overloading in C, we allow a special kind of pointer
1411 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001412 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001413 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001414 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001415 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001416 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001417 return true;
1418 }
1419
Douglas Gregor5c407d92008-10-23 00:40:37 +00001420 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001421 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001422 // An rvalue of type "pointer to cv D," where D is a class type,
1423 // can be converted to an rvalue of type "pointer to cv B," where
1424 // B is a base class (clause 10) of D. If B is an inaccessible
1425 // (clause 11) or ambiguous (10.2) base class of D, a program that
1426 // necessitates this conversion is ill-formed. The result of the
1427 // conversion is a pointer to the base class sub-object of the
1428 // derived class object. The null pointer value is converted to
1429 // the null pointer value of the destination type.
1430 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001431 // Note that we do not check for ambiguity or inaccessibility
1432 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001433 if (getLangOptions().CPlusPlus &&
1434 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001435 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001436 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001437 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001438 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001439 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001440 ToType, Context);
1441 return true;
1442 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001443
Douglas Gregora119f102008-12-19 19:13:09 +00001444 return false;
1445}
1446
1447/// isObjCPointerConversion - Determines whether this is an
1448/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1449/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001450bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001451 QualType& ConvertedType,
1452 bool &IncompatibleObjC) {
1453 if (!getLangOptions().ObjC1)
1454 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001455
Steve Naroff7cae42b2009-07-10 23:34:53 +00001456 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001457 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001458 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001459 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001460
Steve Naroff7cae42b2009-07-10 23:34:53 +00001461 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001462 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001463 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001464 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001465 ConvertedType = ToType;
1466 return true;
1467 }
1468 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001469 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001470 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001471 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001472 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001473 ConvertedType = ToType;
1474 return true;
1475 }
1476 // Objective C++: We're able to convert from a pointer to an
1477 // interface to a pointer to a different interface.
1478 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001479 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1480 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1481 if (getLangOptions().CPlusPlus && LHS && RHS &&
1482 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1483 FromObjCPtr->getPointeeType()))
1484 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001485 ConvertedType = ToType;
1486 return true;
1487 }
1488
1489 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1490 // Okay: this is some kind of implicit downcast of Objective-C
1491 // interfaces, which is permitted. However, we're going to
1492 // complain about it.
1493 IncompatibleObjC = true;
1494 ConvertedType = FromType;
1495 return true;
1496 }
Mike Stump11289f42009-09-09 15:08:12 +00001497 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001498 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001499 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001500 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001501 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001502 else if (const BlockPointerType *ToBlockPtr =
1503 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001504 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001505 // to a block pointer type.
1506 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1507 ConvertedType = ToType;
1508 return true;
1509 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001510 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001511 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001512 else if (FromType->getAs<BlockPointerType>() &&
1513 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1514 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001515 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001516 ConvertedType = ToType;
1517 return true;
1518 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001519 else
Douglas Gregora119f102008-12-19 19:13:09 +00001520 return false;
1521
Douglas Gregor033f56d2008-12-23 00:53:59 +00001522 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001523 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001524 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001525 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001526 FromPointeeType = FromBlockPtr->getPointeeType();
1527 else
Douglas Gregora119f102008-12-19 19:13:09 +00001528 return false;
1529
Douglas Gregora119f102008-12-19 19:13:09 +00001530 // If we have pointers to pointers, recursively check whether this
1531 // is an Objective-C conversion.
1532 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1533 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1534 IncompatibleObjC)) {
1535 // We always complain about this conversion.
1536 IncompatibleObjC = true;
1537 ConvertedType = ToType;
1538 return true;
1539 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001540 // Allow conversion of pointee being objective-c pointer to another one;
1541 // as in I* to id.
1542 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1543 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1544 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1545 IncompatibleObjC)) {
1546 ConvertedType = ToType;
1547 return true;
1548 }
1549
Douglas Gregor033f56d2008-12-23 00:53:59 +00001550 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001551 // differences in the argument and result types are in Objective-C
1552 // pointer conversions. If so, we permit the conversion (but
1553 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001554 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001555 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001556 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001557 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001558 if (FromFunctionType && ToFunctionType) {
1559 // If the function types are exactly the same, this isn't an
1560 // Objective-C pointer conversion.
1561 if (Context.getCanonicalType(FromPointeeType)
1562 == Context.getCanonicalType(ToPointeeType))
1563 return false;
1564
1565 // Perform the quick checks that will tell us whether these
1566 // function types are obviously different.
1567 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1568 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1569 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1570 return false;
1571
1572 bool HasObjCConversion = false;
1573 if (Context.getCanonicalType(FromFunctionType->getResultType())
1574 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1575 // Okay, the types match exactly. Nothing to do.
1576 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1577 ToFunctionType->getResultType(),
1578 ConvertedType, IncompatibleObjC)) {
1579 // Okay, we have an Objective-C pointer conversion.
1580 HasObjCConversion = true;
1581 } else {
1582 // Function types are too different. Abort.
1583 return false;
1584 }
Mike Stump11289f42009-09-09 15:08:12 +00001585
Douglas Gregora119f102008-12-19 19:13:09 +00001586 // Check argument types.
1587 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1588 ArgIdx != NumArgs; ++ArgIdx) {
1589 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1590 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1591 if (Context.getCanonicalType(FromArgType)
1592 == Context.getCanonicalType(ToArgType)) {
1593 // Okay, the types match exactly. Nothing to do.
1594 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1595 ConvertedType, IncompatibleObjC)) {
1596 // Okay, we have an Objective-C pointer conversion.
1597 HasObjCConversion = true;
1598 } else {
1599 // Argument types are too different. Abort.
1600 return false;
1601 }
1602 }
1603
1604 if (HasObjCConversion) {
1605 // We had an Objective-C conversion. Allow this pointer
1606 // conversion, but complain about it.
1607 ConvertedType = ToType;
1608 IncompatibleObjC = true;
1609 return true;
1610 }
1611 }
1612
Sebastian Redl72b597d2009-01-25 19:43:20 +00001613 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001614}
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001615
1616/// FunctionArgTypesAreEqual - This routine checks two function proto types
1617/// for equlity of their argument types. Caller has already checked that
1618/// they have same number of arguments. This routine assumes that Objective-C
1619/// pointer types which only differ in their protocol qualifiers are equal.
1620bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1621 FunctionProtoType* NewType){
1622 if (!getLangOptions().ObjC1)
1623 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1624 NewType->arg_type_begin());
1625
1626 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1627 N = NewType->arg_type_begin(),
1628 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1629 QualType ToType = (*O);
1630 QualType FromType = (*N);
1631 if (ToType != FromType) {
1632 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1633 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001634 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1635 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1636 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1637 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001638 continue;
1639 }
John McCall8b07ec22010-05-15 11:32:37 +00001640 else if (const ObjCObjectPointerType *PTTo =
1641 ToType->getAs<ObjCObjectPointerType>()) {
1642 if (const ObjCObjectPointerType *PTFr =
1643 FromType->getAs<ObjCObjectPointerType>())
1644 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1645 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001646 }
1647 return false;
1648 }
1649 }
1650 return true;
1651}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001652
Douglas Gregor39c16d42008-10-24 04:54:22 +00001653/// CheckPointerConversion - Check the pointer conversion from the
1654/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001655/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001656/// conversions for which IsPointerConversion has already returned
1657/// true. It returns true and produces a diagnostic if there was an
1658/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001659bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001660 CastExpr::CastKind &Kind,
Anders Carlssona70cff62010-04-24 19:06:50 +00001661 CXXBaseSpecifierArray& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001662 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001663 QualType FromType = From->getType();
1664
Douglas Gregor4038cf42010-06-08 17:35:15 +00001665 if (CXXBoolLiteralExpr* LitBool
1666 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
1667 if (LitBool->getValue() == false)
1668 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1669 << ToType;
1670
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001671 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1672 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001673 QualType FromPointeeType = FromPtrType->getPointeeType(),
1674 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001675
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001676 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1677 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001678 // We must have a derived-to-base conversion. Check an
1679 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001680 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1681 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001682 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001683 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001684 return true;
1685
1686 // The conversion was successful.
1687 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001688 }
1689 }
Mike Stump11289f42009-09-09 15:08:12 +00001690 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001691 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001692 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001693 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001694 // Objective-C++ conversions are always okay.
1695 // FIXME: We should have a different class of conversions for the
1696 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001697 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001698 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001699
Steve Naroff7cae42b2009-07-10 23:34:53 +00001700 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001701 return false;
1702}
1703
Sebastian Redl72b597d2009-01-25 19:43:20 +00001704/// IsMemberPointerConversion - Determines whether the conversion of the
1705/// expression From, which has the (possibly adjusted) type FromType, can be
1706/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1707/// If so, returns true and places the converted type (that might differ from
1708/// ToType in its cv-qualifiers at some level) into ConvertedType.
1709bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001710 QualType ToType,
1711 bool InOverloadResolution,
1712 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001713 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001714 if (!ToTypePtr)
1715 return false;
1716
1717 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001718 if (From->isNullPointerConstant(Context,
1719 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1720 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001721 ConvertedType = ToType;
1722 return true;
1723 }
1724
1725 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001726 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001727 if (!FromTypePtr)
1728 return false;
1729
1730 // A pointer to member of B can be converted to a pointer to member of D,
1731 // where D is derived from B (C++ 4.11p2).
1732 QualType FromClass(FromTypePtr->getClass(), 0);
1733 QualType ToClass(ToTypePtr->getClass(), 0);
1734 // FIXME: What happens when these are dependent? Is this function even called?
1735
1736 if (IsDerivedFrom(ToClass, FromClass)) {
1737 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1738 ToClass.getTypePtr());
1739 return true;
1740 }
1741
1742 return false;
1743}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001744
Sebastian Redl72b597d2009-01-25 19:43:20 +00001745/// CheckMemberPointerConversion - Check the member pointer conversion from the
1746/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001747/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001748/// for which IsMemberPointerConversion has already returned true. It returns
1749/// true and produces a diagnostic if there was an error, or returns false
1750/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001751bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001752 CastExpr::CastKind &Kind,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001753 CXXBaseSpecifierArray &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001754 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001755 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001756 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001757 if (!FromPtrType) {
1758 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001759 assert(From->isNullPointerConstant(Context,
1760 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001761 "Expr must be null pointer constant!");
1762 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001763 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001764 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001765
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001766 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001767 assert(ToPtrType && "No member pointer cast has a target type "
1768 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001769
Sebastian Redled8f2002009-01-28 18:33:18 +00001770 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1771 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001772
Sebastian Redled8f2002009-01-28 18:33:18 +00001773 // FIXME: What about dependent types?
1774 assert(FromClass->isRecordType() && "Pointer into non-class.");
1775 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001776
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001777 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001778 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001779 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1780 assert(DerivationOkay &&
1781 "Should not have been called if derivation isn't OK.");
1782 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001783
Sebastian Redled8f2002009-01-28 18:33:18 +00001784 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1785 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001786 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1787 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1788 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1789 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001790 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001791
Douglas Gregor89ee6822009-02-28 01:32:25 +00001792 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001793 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1794 << FromClass << ToClass << QualType(VBase, 0)
1795 << From->getSourceRange();
1796 return true;
1797 }
1798
John McCall5b0829a2010-02-10 09:31:12 +00001799 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001800 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1801 Paths.front(),
1802 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001803
Anders Carlssond7923c62009-08-22 23:33:40 +00001804 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001805 BuildBasePathArray(Paths, BasePath);
Anders Carlssond7923c62009-08-22 23:33:40 +00001806 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001807 return false;
1808}
1809
Douglas Gregor9a657932008-10-21 23:43:52 +00001810/// IsQualificationConversion - Determines whether the conversion from
1811/// an rvalue of type FromType to ToType is a qualification conversion
1812/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001813bool
1814Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001815 FromType = Context.getCanonicalType(FromType);
1816 ToType = Context.getCanonicalType(ToType);
1817
1818 // If FromType and ToType are the same type, this is not a
1819 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001820 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001821 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001822
Douglas Gregor9a657932008-10-21 23:43:52 +00001823 // (C++ 4.4p4):
1824 // A conversion can add cv-qualifiers at levels other than the first
1825 // in multi-level pointers, subject to the following rules: [...]
1826 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001827 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001828 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001829 // Within each iteration of the loop, we check the qualifiers to
1830 // determine if this still looks like a qualification
1831 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001832 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001833 // until there are no more pointers or pointers-to-members left to
1834 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001835 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001836
1837 // -- for every j > 0, if const is in cv 1,j then const is in cv
1838 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001839 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001840 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001841
Douglas Gregor9a657932008-10-21 23:43:52 +00001842 // -- if the cv 1,j and cv 2,j are different, then const is in
1843 // every cv for 0 < k < j.
1844 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001845 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001846 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001847
Douglas Gregor9a657932008-10-21 23:43:52 +00001848 // Keep track of whether all prior cv-qualifiers in the "to" type
1849 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001850 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001851 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001852 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001853
1854 // We are left with FromType and ToType being the pointee types
1855 // after unwrapping the original FromType and ToType the same number
1856 // of types. If we unwrapped any pointers, and if FromType and
1857 // ToType have the same unqualified type (since we checked
1858 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001859 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001860}
1861
Douglas Gregor576e98c2009-01-30 23:27:23 +00001862/// Determines whether there is a user-defined conversion sequence
1863/// (C++ [over.ics.user]) that converts expression From to the type
1864/// ToType. If such a conversion exists, User will contain the
1865/// user-defined conversion sequence that performs such a conversion
1866/// and this routine will return true. Otherwise, this routine returns
1867/// false and User is unspecified.
1868///
Douglas Gregor576e98c2009-01-30 23:27:23 +00001869/// \param AllowExplicit true if the conversion should consider C++0x
1870/// "explicit" conversion functions as well as non-explicit conversion
1871/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001872OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1873 UserDefinedConversionSequence& User,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001874 OverloadCandidateSet& CandidateSet,
1875 bool AllowExplicit) {
1876 // Whether we will only visit constructors.
1877 bool ConstructorsOnly = false;
1878
1879 // If the type we are conversion to is a class type, enumerate its
1880 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001881 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001882 // C++ [over.match.ctor]p1:
1883 // When objects of class type are direct-initialized (8.5), or
1884 // copy-initialized from an expression of the same or a
1885 // derived class type (8.5), overload resolution selects the
1886 // constructor. [...] For copy-initialization, the candidate
1887 // functions are all the converting constructors (12.3.1) of
1888 // that class. The argument list is the expression-list within
1889 // the parentheses of the initializer.
1890 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1891 (From->getType()->getAs<RecordType>() &&
1892 IsDerivedFrom(From->getType(), ToType)))
1893 ConstructorsOnly = true;
1894
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001895 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1896 // We're not going to find any constructors.
1897 } else if (CXXRecordDecl *ToRecordDecl
1898 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00001899 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001900 = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor5ab11652010-04-17 22:01:05 +00001901 Context.getCanonicalType(ToType).getUnqualifiedType());
Douglas Gregor89ee6822009-02-28 01:32:25 +00001902 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001903 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001904 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001905 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00001906 NamedDecl *D = *Con;
1907 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1908
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001909 // Find the constructor (which may be a template).
1910 CXXConstructorDecl *Constructor = 0;
1911 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00001912 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001913 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001914 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001915 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1916 else
John McCalla0296f72010-03-19 07:35:19 +00001917 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001918
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001919 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001920 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001921 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00001922 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001923 /*ExplicitArgs*/ 0,
John McCall6b51f282009-11-23 01:53:49 +00001924 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001925 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001926 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001927 // Allow one user-defined conversion when user specifies a
1928 // From->ToType conversion via an static cast (c-style, etc).
John McCalla0296f72010-03-19 07:35:19 +00001929 AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001930 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001931 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001932 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001933 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001934 }
1935 }
1936
Douglas Gregor5ab11652010-04-17 22:01:05 +00001937 // Enumerate conversion functions, if we're allowed to.
1938 if (ConstructorsOnly) {
Mike Stump11289f42009-09-09 15:08:12 +00001939 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
Douglas Gregor5ab11652010-04-17 22:01:05 +00001940 PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001941 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001942 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00001943 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001944 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001945 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1946 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00001947 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001948 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001949 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001950 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00001951 DeclAccessPair FoundDecl = I.getPair();
1952 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00001953 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1954 if (isa<UsingShadowDecl>(D))
1955 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1956
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001957 CXXConversionDecl *Conv;
1958 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00001959 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1960 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001961 else
John McCallda4458e2010-03-31 01:36:47 +00001962 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001963
1964 if (AllowExplicit || !Conv->isExplicit()) {
1965 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00001966 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001967 ActingContext, From, ToType,
1968 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001969 else
John McCalla0296f72010-03-19 07:35:19 +00001970 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCallb89836b2010-01-26 01:37:31 +00001971 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001972 }
1973 }
1974 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001975 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001976
1977 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001978 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001979 case OR_Success:
1980 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001981 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001982 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1983 // C++ [over.ics.user]p1:
1984 // If the user-defined conversion is specified by a
1985 // constructor (12.3.1), the initial standard conversion
1986 // sequence converts the source type to the type required by
1987 // the argument of the constructor.
1988 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001989 QualType ThisType = Constructor->getThisType(Context);
John McCall0d1da222010-01-12 00:44:57 +00001990 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian55824512009-11-06 00:23:08 +00001991 User.EllipsisConversion = true;
1992 else {
1993 User.Before = Best->Conversions[0].Standard;
1994 User.EllipsisConversion = false;
1995 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001996 User.ConversionFunction = Constructor;
1997 User.After.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00001998 User.After.setFromType(
1999 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002000 User.After.setAllToTypes(ToType);
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002001 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002002 } else if (CXXConversionDecl *Conversion
2003 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2004 // C++ [over.ics.user]p1:
2005 //
2006 // [...] If the user-defined conversion is specified by a
2007 // conversion function (12.3.2), the initial standard
2008 // conversion sequence converts the source type to the
2009 // implicit object parameter of the conversion function.
2010 User.Before = Best->Conversions[0].Standard;
2011 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002012 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002013
2014 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00002015 // The second standard conversion sequence converts the
2016 // result of the user-defined conversion to the target type
2017 // for the sequence. Since an implicit conversion sequence
2018 // is an initialization, the special rules for
2019 // initialization by user-defined conversion apply when
2020 // selecting the best user-defined conversion for a
2021 // user-defined conversion sequence (see 13.3.3 and
2022 // 13.3.3.1).
2023 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002024 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002025 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002026 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002027 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002028 }
Mike Stump11289f42009-09-09 15:08:12 +00002029
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002030 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002031 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00002032 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002033 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002034 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002035
2036 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002037 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002038 }
2039
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002040 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002041}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002042
2043bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002044Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002045 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002046 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002047 OverloadingResult OvResult =
2048 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002049 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002050 if (OvResult == OR_Ambiguous)
2051 Diag(From->getSourceRange().getBegin(),
2052 diag::err_typecheck_ambiguous_condition)
2053 << From->getType() << ToType << From->getSourceRange();
2054 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2055 Diag(From->getSourceRange().getBegin(),
2056 diag::err_typecheck_nonviable_condition)
2057 << From->getType() << ToType << From->getSourceRange();
2058 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002059 return false;
John McCallad907772010-01-12 07:18:19 +00002060 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002061 return true;
2062}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002063
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002064/// CompareImplicitConversionSequences - Compare two implicit
2065/// conversion sequences to determine whether one is better than the
2066/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00002067ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002068Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
2069 const ImplicitConversionSequence& ICS2)
2070{
2071 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2072 // conversion sequences (as defined in 13.3.3.1)
2073 // -- a standard conversion sequence (13.3.3.1.1) is a better
2074 // conversion sequence than a user-defined conversion sequence or
2075 // an ellipsis conversion sequence, and
2076 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2077 // conversion sequence than an ellipsis conversion sequence
2078 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002079 //
John McCall0d1da222010-01-12 00:44:57 +00002080 // C++0x [over.best.ics]p10:
2081 // For the purpose of ranking implicit conversion sequences as
2082 // described in 13.3.3.2, the ambiguous conversion sequence is
2083 // treated as a user-defined sequence that is indistinguishable
2084 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002085 if (ICS1.getKindRank() < ICS2.getKindRank())
2086 return ImplicitConversionSequence::Better;
2087 else if (ICS2.getKindRank() < ICS1.getKindRank())
2088 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002089
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002090 // The following checks require both conversion sequences to be of
2091 // the same kind.
2092 if (ICS1.getKind() != ICS2.getKind())
2093 return ImplicitConversionSequence::Indistinguishable;
2094
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002095 // Two implicit conversion sequences of the same form are
2096 // indistinguishable conversion sequences unless one of the
2097 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002098 if (ICS1.isStandard())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002099 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002100 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002101 // User-defined conversion sequence U1 is a better conversion
2102 // sequence than another user-defined conversion sequence U2 if
2103 // they contain the same user-defined conversion function or
2104 // constructor and if the second standard conversion sequence of
2105 // U1 is better than the second standard conversion sequence of
2106 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002107 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002108 ICS2.UserDefined.ConversionFunction)
2109 return CompareStandardConversionSequences(ICS1.UserDefined.After,
2110 ICS2.UserDefined.After);
2111 }
2112
2113 return ImplicitConversionSequence::Indistinguishable;
2114}
2115
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002116static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2117 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2118 Qualifiers Quals;
2119 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2120 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2121 }
2122
2123 return Context.hasSameUnqualifiedType(T1, T2);
2124}
2125
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002126// Per 13.3.3.2p3, compare the given standard conversion sequences to
2127// determine if one is a proper subset of the other.
2128static ImplicitConversionSequence::CompareKind
2129compareStandardConversionSubsets(ASTContext &Context,
2130 const StandardConversionSequence& SCS1,
2131 const StandardConversionSequence& SCS2) {
2132 ImplicitConversionSequence::CompareKind Result
2133 = ImplicitConversionSequence::Indistinguishable;
2134
Douglas Gregore87561a2010-05-23 22:10:15 +00002135 // the identity conversion sequence is considered to be a subsequence of
2136 // any non-identity conversion sequence
2137 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2138 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2139 return ImplicitConversionSequence::Better;
2140 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2141 return ImplicitConversionSequence::Worse;
2142 }
2143
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002144 if (SCS1.Second != SCS2.Second) {
2145 if (SCS1.Second == ICK_Identity)
2146 Result = ImplicitConversionSequence::Better;
2147 else if (SCS2.Second == ICK_Identity)
2148 Result = ImplicitConversionSequence::Worse;
2149 else
2150 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002151 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002152 return ImplicitConversionSequence::Indistinguishable;
2153
2154 if (SCS1.Third == SCS2.Third) {
2155 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2156 : ImplicitConversionSequence::Indistinguishable;
2157 }
2158
2159 if (SCS1.Third == ICK_Identity)
2160 return Result == ImplicitConversionSequence::Worse
2161 ? ImplicitConversionSequence::Indistinguishable
2162 : ImplicitConversionSequence::Better;
2163
2164 if (SCS2.Third == ICK_Identity)
2165 return Result == ImplicitConversionSequence::Better
2166 ? ImplicitConversionSequence::Indistinguishable
2167 : ImplicitConversionSequence::Worse;
2168
2169 return ImplicitConversionSequence::Indistinguishable;
2170}
2171
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002172/// CompareStandardConversionSequences - Compare two standard
2173/// conversion sequences to determine whether one is better than the
2174/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002175ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002176Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
2177 const StandardConversionSequence& SCS2)
2178{
2179 // Standard conversion sequence S1 is a better conversion sequence
2180 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2181
2182 // -- S1 is a proper subsequence of S2 (comparing the conversion
2183 // sequences in the canonical form defined by 13.3.3.1.1,
2184 // excluding any Lvalue Transformation; the identity conversion
2185 // sequence is considered to be a subsequence of any
2186 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002187 if (ImplicitConversionSequence::CompareKind CK
2188 = compareStandardConversionSubsets(Context, SCS1, SCS2))
2189 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002190
2191 // -- the rank of S1 is better than the rank of S2 (by the rules
2192 // defined below), or, if not that,
2193 ImplicitConversionRank Rank1 = SCS1.getRank();
2194 ImplicitConversionRank Rank2 = SCS2.getRank();
2195 if (Rank1 < Rank2)
2196 return ImplicitConversionSequence::Better;
2197 else if (Rank2 < Rank1)
2198 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002199
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002200 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2201 // are indistinguishable unless one of the following rules
2202 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002203
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002204 // A conversion that is not a conversion of a pointer, or
2205 // pointer to member, to bool is better than another conversion
2206 // that is such a conversion.
2207 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2208 return SCS2.isPointerConversionToBool()
2209 ? ImplicitConversionSequence::Better
2210 : ImplicitConversionSequence::Worse;
2211
Douglas Gregor5c407d92008-10-23 00:40:37 +00002212 // C++ [over.ics.rank]p4b2:
2213 //
2214 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002215 // conversion of B* to A* is better than conversion of B* to
2216 // void*, and conversion of A* to void* is better than conversion
2217 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002218 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00002219 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00002220 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00002221 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002222 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2223 // Exactly one of the conversion sequences is a conversion to
2224 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002225 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2226 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002227 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2228 // Neither conversion sequence converts to a void pointer; compare
2229 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002230 if (ImplicitConversionSequence::CompareKind DerivedCK
2231 = CompareDerivedToBaseConversions(SCS1, SCS2))
2232 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002233 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2234 // Both conversion sequences are conversions to void
2235 // pointers. Compare the source types to determine if there's an
2236 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002237 QualType FromType1 = SCS1.getFromType();
2238 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002239
2240 // Adjust the types we're converting from via the array-to-pointer
2241 // conversion, if we need to.
2242 if (SCS1.First == ICK_Array_To_Pointer)
2243 FromType1 = Context.getArrayDecayedType(FromType1);
2244 if (SCS2.First == ICK_Array_To_Pointer)
2245 FromType2 = Context.getArrayDecayedType(FromType2);
2246
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002247 QualType FromPointee1
2248 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2249 QualType FromPointee2
2250 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002251
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002252 if (IsDerivedFrom(FromPointee2, FromPointee1))
2253 return ImplicitConversionSequence::Better;
2254 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2255 return ImplicitConversionSequence::Worse;
2256
2257 // Objective-C++: If one interface is more specific than the
2258 // other, it is the better one.
John McCall8b07ec22010-05-15 11:32:37 +00002259 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2260 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002261 if (FromIface1 && FromIface1) {
2262 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2263 return ImplicitConversionSequence::Better;
2264 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2265 return ImplicitConversionSequence::Worse;
2266 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002267 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002268
2269 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2270 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002271 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002272 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002273 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002274
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002275 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00002276 // C++0x [over.ics.rank]p3b4:
2277 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2278 // implicit object parameter of a non-static member function declared
2279 // without a ref-qualifier, and S1 binds an rvalue reference to an
2280 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00002281 // FIXME: We don't know if we're dealing with the implicit object parameter,
2282 // or if the member function in this case has a ref qualifier.
2283 // (Of course, we don't have ref qualifiers yet.)
2284 if (SCS1.RRefBinding != SCS2.RRefBinding)
2285 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2286 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00002287
2288 // C++ [over.ics.rank]p3b4:
2289 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2290 // which the references refer are the same type except for
2291 // top-level cv-qualifiers, and the type to which the reference
2292 // initialized by S2 refers is more cv-qualified than the type
2293 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002294 QualType T1 = SCS1.getToType(2);
2295 QualType T2 = SCS2.getToType(2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002296 T1 = Context.getCanonicalType(T1);
2297 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002298 Qualifiers T1Quals, T2Quals;
2299 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2300 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2301 if (UnqualT1 == UnqualT2) {
2302 // If the type is an array type, promote the element qualifiers to the type
2303 // for comparison.
2304 if (isa<ArrayType>(T1) && T1Quals)
2305 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2306 if (isa<ArrayType>(T2) && T2Quals)
2307 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002308 if (T2.isMoreQualifiedThan(T1))
2309 return ImplicitConversionSequence::Better;
2310 else if (T1.isMoreQualifiedThan(T2))
2311 return ImplicitConversionSequence::Worse;
2312 }
2313 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002314
2315 return ImplicitConversionSequence::Indistinguishable;
2316}
2317
2318/// CompareQualificationConversions - Compares two standard conversion
2319/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002320/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2321ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002322Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00002323 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002324 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002325 // -- S1 and S2 differ only in their qualification conversion and
2326 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2327 // cv-qualification signature of type T1 is a proper subset of
2328 // the cv-qualification signature of type T2, and S1 is not the
2329 // deprecated string literal array-to-pointer conversion (4.2).
2330 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2331 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2332 return ImplicitConversionSequence::Indistinguishable;
2333
2334 // FIXME: the example in the standard doesn't use a qualification
2335 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002336 QualType T1 = SCS1.getToType(2);
2337 QualType T2 = SCS2.getToType(2);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002338 T1 = Context.getCanonicalType(T1);
2339 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002340 Qualifiers T1Quals, T2Quals;
2341 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2342 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002343
2344 // If the types are the same, we won't learn anything by unwrapped
2345 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002346 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002347 return ImplicitConversionSequence::Indistinguishable;
2348
Chandler Carruth607f38e2009-12-29 07:16:59 +00002349 // If the type is an array type, promote the element qualifiers to the type
2350 // for comparison.
2351 if (isa<ArrayType>(T1) && T1Quals)
2352 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2353 if (isa<ArrayType>(T2) && T2Quals)
2354 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2355
Mike Stump11289f42009-09-09 15:08:12 +00002356 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002357 = ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002358 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002359 // Within each iteration of the loop, we check the qualifiers to
2360 // determine if this still looks like a qualification
2361 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002362 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002363 // until there are no more pointers or pointers-to-members left
2364 // to unwrap. This essentially mimics what
2365 // IsQualificationConversion does, but here we're checking for a
2366 // strict subset of qualifiers.
2367 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2368 // The qualifiers are the same, so this doesn't tell us anything
2369 // about how the sequences rank.
2370 ;
2371 else if (T2.isMoreQualifiedThan(T1)) {
2372 // T1 has fewer qualifiers, so it could be the better sequence.
2373 if (Result == ImplicitConversionSequence::Worse)
2374 // Neither has qualifiers that are a subset of the other's
2375 // qualifiers.
2376 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002377
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002378 Result = ImplicitConversionSequence::Better;
2379 } else if (T1.isMoreQualifiedThan(T2)) {
2380 // T2 has fewer qualifiers, so it could be the better sequence.
2381 if (Result == ImplicitConversionSequence::Better)
2382 // Neither has qualifiers that are a subset of the other's
2383 // qualifiers.
2384 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002385
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002386 Result = ImplicitConversionSequence::Worse;
2387 } else {
2388 // Qualifiers are disjoint.
2389 return ImplicitConversionSequence::Indistinguishable;
2390 }
2391
2392 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002393 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002394 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002395 }
2396
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002397 // Check that the winning standard conversion sequence isn't using
2398 // the deprecated string literal array to pointer conversion.
2399 switch (Result) {
2400 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002401 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002402 Result = ImplicitConversionSequence::Indistinguishable;
2403 break;
2404
2405 case ImplicitConversionSequence::Indistinguishable:
2406 break;
2407
2408 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002409 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002410 Result = ImplicitConversionSequence::Indistinguishable;
2411 break;
2412 }
2413
2414 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002415}
2416
Douglas Gregor5c407d92008-10-23 00:40:37 +00002417/// CompareDerivedToBaseConversions - Compares two standard conversion
2418/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002419/// various kinds of derived-to-base conversions (C++
2420/// [over.ics.rank]p4b3). As part of these checks, we also look at
2421/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002422ImplicitConversionSequence::CompareKind
2423Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2424 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002425 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002426 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002427 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002428 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002429
2430 // Adjust the types we're converting from via the array-to-pointer
2431 // conversion, if we need to.
2432 if (SCS1.First == ICK_Array_To_Pointer)
2433 FromType1 = Context.getArrayDecayedType(FromType1);
2434 if (SCS2.First == ICK_Array_To_Pointer)
2435 FromType2 = Context.getArrayDecayedType(FromType2);
2436
2437 // Canonicalize all of the types.
2438 FromType1 = Context.getCanonicalType(FromType1);
2439 ToType1 = Context.getCanonicalType(ToType1);
2440 FromType2 = Context.getCanonicalType(FromType2);
2441 ToType2 = Context.getCanonicalType(ToType2);
2442
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002443 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002444 //
2445 // If class B is derived directly or indirectly from class A and
2446 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002447 //
2448 // For Objective-C, we let A, B, and C also be Objective-C
2449 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002450
2451 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002452 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002453 SCS2.Second == ICK_Pointer_Conversion &&
2454 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2455 FromType1->isPointerType() && FromType2->isPointerType() &&
2456 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002457 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002458 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002459 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002460 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002461 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002462 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002463 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002464 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002465
John McCall8b07ec22010-05-15 11:32:37 +00002466 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2467 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2468 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2469 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002470
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002471 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002472 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2473 if (IsDerivedFrom(ToPointee1, ToPointee2))
2474 return ImplicitConversionSequence::Better;
2475 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2476 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002477
2478 if (ToIface1 && ToIface2) {
2479 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2480 return ImplicitConversionSequence::Better;
2481 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2482 return ImplicitConversionSequence::Worse;
2483 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002484 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002485
2486 // -- conversion of B* to A* is better than conversion of C* to A*,
2487 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2488 if (IsDerivedFrom(FromPointee2, FromPointee1))
2489 return ImplicitConversionSequence::Better;
2490 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2491 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002492
Douglas Gregor237f96c2008-11-26 23:31:11 +00002493 if (FromIface1 && FromIface2) {
2494 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2495 return ImplicitConversionSequence::Better;
2496 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2497 return ImplicitConversionSequence::Worse;
2498 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002499 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002500 }
2501
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002502 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002503 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2504 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2505 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2506 const MemberPointerType * FromMemPointer1 =
2507 FromType1->getAs<MemberPointerType>();
2508 const MemberPointerType * ToMemPointer1 =
2509 ToType1->getAs<MemberPointerType>();
2510 const MemberPointerType * FromMemPointer2 =
2511 FromType2->getAs<MemberPointerType>();
2512 const MemberPointerType * ToMemPointer2 =
2513 ToType2->getAs<MemberPointerType>();
2514 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2515 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2516 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2517 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2518 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2519 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2520 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2521 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002522 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002523 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2524 if (IsDerivedFrom(ToPointee1, ToPointee2))
2525 return ImplicitConversionSequence::Worse;
2526 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2527 return ImplicitConversionSequence::Better;
2528 }
2529 // conversion of B::* to C::* is better than conversion of A::* to C::*
2530 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2531 if (IsDerivedFrom(FromPointee1, FromPointee2))
2532 return ImplicitConversionSequence::Better;
2533 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2534 return ImplicitConversionSequence::Worse;
2535 }
2536 }
2537
Douglas Gregor5ab11652010-04-17 22:01:05 +00002538 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002539 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002540 // -- binding of an expression of type C to a reference of type
2541 // B& is better than binding an expression of type C to a
2542 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002543 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2544 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002545 if (IsDerivedFrom(ToType1, ToType2))
2546 return ImplicitConversionSequence::Better;
2547 else if (IsDerivedFrom(ToType2, ToType1))
2548 return ImplicitConversionSequence::Worse;
2549 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002550
Douglas Gregor2fe98832008-11-03 19:09:14 +00002551 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002552 // -- binding of an expression of type B to a reference of type
2553 // A& is better than binding an expression of type C to a
2554 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002555 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2556 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002557 if (IsDerivedFrom(FromType2, FromType1))
2558 return ImplicitConversionSequence::Better;
2559 else if (IsDerivedFrom(FromType1, FromType2))
2560 return ImplicitConversionSequence::Worse;
2561 }
2562 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002563
Douglas Gregor5c407d92008-10-23 00:40:37 +00002564 return ImplicitConversionSequence::Indistinguishable;
2565}
2566
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002567/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2568/// determine whether they are reference-related,
2569/// reference-compatible, reference-compatible with added
2570/// qualification, or incompatible, for use in C++ initialization by
2571/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2572/// type, and the first type (T1) is the pointee type of the reference
2573/// type being initialized.
2574Sema::ReferenceCompareResult
2575Sema::CompareReferenceRelationship(SourceLocation Loc,
2576 QualType OrigT1, QualType OrigT2,
2577 bool& DerivedToBase) {
2578 assert(!OrigT1->isReferenceType() &&
2579 "T1 must be the pointee type of the reference type");
2580 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2581
2582 QualType T1 = Context.getCanonicalType(OrigT1);
2583 QualType T2 = Context.getCanonicalType(OrigT2);
2584 Qualifiers T1Quals, T2Quals;
2585 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2586 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2587
2588 // C++ [dcl.init.ref]p4:
2589 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2590 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2591 // T1 is a base class of T2.
2592 if (UnqualT1 == UnqualT2)
2593 DerivedToBase = false;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002594 else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002595 IsDerivedFrom(UnqualT2, UnqualT1))
2596 DerivedToBase = true;
2597 else
2598 return Ref_Incompatible;
2599
2600 // At this point, we know that T1 and T2 are reference-related (at
2601 // least).
2602
2603 // If the type is an array type, promote the element qualifiers to the type
2604 // for comparison.
2605 if (isa<ArrayType>(T1) && T1Quals)
2606 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2607 if (isa<ArrayType>(T2) && T2Quals)
2608 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2609
2610 // C++ [dcl.init.ref]p4:
2611 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2612 // reference-related to T2 and cv1 is the same cv-qualification
2613 // as, or greater cv-qualification than, cv2. For purposes of
2614 // overload resolution, cases for which cv1 is greater
2615 // cv-qualification than cv2 are identified as
2616 // reference-compatible with added qualification (see 13.3.3.2).
2617 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2618 return Ref_Compatible;
2619 else if (T1.isMoreQualifiedThan(T2))
2620 return Ref_Compatible_With_Added_Qualification;
2621 else
2622 return Ref_Related;
2623}
2624
2625/// \brief Compute an implicit conversion sequence for reference
2626/// initialization.
2627static ImplicitConversionSequence
2628TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2629 SourceLocation DeclLoc,
2630 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002631 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002632 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2633
2634 // Most paths end in a failed conversion.
2635 ImplicitConversionSequence ICS;
2636 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2637
2638 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2639 QualType T2 = Init->getType();
2640
2641 // If the initializer is the address of an overloaded function, try
2642 // to resolve the overloaded function. If all goes well, T2 is the
2643 // type of the resulting function.
2644 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2645 DeclAccessPair Found;
2646 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2647 false, Found))
2648 T2 = Fn->getType();
2649 }
2650
2651 // Compute some basic properties of the types and the initializer.
2652 bool isRValRef = DeclType->isRValueReferenceType();
2653 bool DerivedToBase = false;
Douglas Gregoradc7a702010-04-16 17:45:54 +00002654 Expr::isLvalueResult InitLvalue = Init->isLvalue(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002655 Sema::ReferenceCompareResult RefRelationship
2656 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
2657
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002658
2659 // C++ [over.ics.ref]p3:
2660 // Except for an implicit object parameter, for which see 13.3.1,
2661 // a standard conversion sequence cannot be formed if it requires
2662 // binding an lvalue reference to non-const to an rvalue or
2663 // binding an rvalue reference to an lvalue.
Douglas Gregor870f3742010-04-18 09:22:00 +00002664 //
2665 // FIXME: DPG doesn't trust this code. It seems far too early to
2666 // abort because of a binding of an rvalue reference to an lvalue.
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002667 if (isRValRef && InitLvalue == Expr::LV_Valid)
2668 return ICS;
2669
Douglas Gregor870f3742010-04-18 09:22:00 +00002670 // C++0x [dcl.init.ref]p16:
2671 // A reference to type "cv1 T1" is initialized by an expression
2672 // of type "cv2 T2" as follows:
2673
2674 // -- If the initializer expression
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002675 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2676 // reference-compatible with "cv2 T2," or
2677 //
2678 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2679 if (InitLvalue == Expr::LV_Valid &&
2680 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2681 // C++ [over.ics.ref]p1:
2682 // When a parameter of reference type binds directly (8.5.3)
2683 // to an argument expression, the implicit conversion sequence
2684 // is the identity conversion, unless the argument expression
2685 // has a type that is a derived class of the parameter type,
2686 // in which case the implicit conversion sequence is a
2687 // derived-to-base Conversion (13.3.3.1).
2688 ICS.setStandard();
2689 ICS.Standard.First = ICK_Identity;
2690 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2691 ICS.Standard.Third = ICK_Identity;
2692 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2693 ICS.Standard.setToType(0, T2);
2694 ICS.Standard.setToType(1, T1);
2695 ICS.Standard.setToType(2, T1);
2696 ICS.Standard.ReferenceBinding = true;
2697 ICS.Standard.DirectBinding = true;
2698 ICS.Standard.RRefBinding = false;
2699 ICS.Standard.CopyConstructor = 0;
2700
2701 // Nothing more to do: the inaccessibility/ambiguity check for
2702 // derived-to-base conversions is suppressed when we're
2703 // computing the implicit conversion sequence (C++
2704 // [over.best.ics]p2).
2705 return ICS;
2706 }
2707
2708 // -- has a class type (i.e., T2 is a class type), where T1 is
2709 // not reference-related to T2, and can be implicitly
2710 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2711 // is reference-compatible with "cv3 T3" 92) (this
2712 // conversion is selected by enumerating the applicable
2713 // conversion functions (13.3.1.6) and choosing the best
2714 // one through overload resolution (13.3)),
2715 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
2716 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2717 RefRelationship == Sema::Ref_Incompatible) {
2718 CXXRecordDecl *T2RecordDecl
2719 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2720
2721 OverloadCandidateSet CandidateSet(DeclLoc);
2722 const UnresolvedSetImpl *Conversions
2723 = T2RecordDecl->getVisibleConversionFunctions();
2724 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2725 E = Conversions->end(); I != E; ++I) {
2726 NamedDecl *D = *I;
2727 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2728 if (isa<UsingShadowDecl>(D))
2729 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2730
2731 FunctionTemplateDecl *ConvTemplate
2732 = dyn_cast<FunctionTemplateDecl>(D);
2733 CXXConversionDecl *Conv;
2734 if (ConvTemplate)
2735 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2736 else
2737 Conv = cast<CXXConversionDecl>(D);
2738
2739 // If the conversion function doesn't return a reference type,
2740 // it can't be considered for this conversion.
2741 if (Conv->getConversionType()->isLValueReferenceType() &&
2742 (AllowExplicit || !Conv->isExplicit())) {
2743 if (ConvTemplate)
2744 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2745 Init, DeclType, CandidateSet);
2746 else
2747 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2748 DeclType, CandidateSet);
2749 }
2750 }
2751
2752 OverloadCandidateSet::iterator Best;
2753 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2754 case OR_Success:
2755 // C++ [over.ics.ref]p1:
2756 //
2757 // [...] If the parameter binds directly to the result of
2758 // applying a conversion function to the argument
2759 // expression, the implicit conversion sequence is a
2760 // user-defined conversion sequence (13.3.3.1.2), with the
2761 // second standard conversion sequence either an identity
2762 // conversion or, if the conversion function returns an
2763 // entity of a type that is a derived class of the parameter
2764 // type, a derived-to-base Conversion.
2765 if (!Best->FinalConversion.DirectBinding)
2766 break;
2767
2768 ICS.setUserDefined();
2769 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2770 ICS.UserDefined.After = Best->FinalConversion;
2771 ICS.UserDefined.ConversionFunction = Best->Function;
2772 ICS.UserDefined.EllipsisConversion = false;
2773 assert(ICS.UserDefined.After.ReferenceBinding &&
2774 ICS.UserDefined.After.DirectBinding &&
2775 "Expected a direct reference binding!");
2776 return ICS;
2777
2778 case OR_Ambiguous:
2779 ICS.setAmbiguous();
2780 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2781 Cand != CandidateSet.end(); ++Cand)
2782 if (Cand->Viable)
2783 ICS.Ambiguous.addConversion(Cand->Function);
2784 return ICS;
2785
2786 case OR_No_Viable_Function:
2787 case OR_Deleted:
2788 // There was no suitable conversion, or we found a deleted
2789 // conversion; continue with other checks.
2790 break;
2791 }
2792 }
2793
2794 // -- Otherwise, the reference shall be to a non-volatile const
2795 // type (i.e., cv1 shall be const), or the reference shall be an
2796 // rvalue reference and the initializer expression shall be an rvalue.
Douglas Gregor870f3742010-04-18 09:22:00 +00002797 //
2798 // We actually handle one oddity of C++ [over.ics.ref] at this
2799 // point, which is that, due to p2 (which short-circuits reference
2800 // binding by only attempting a simple conversion for non-direct
2801 // bindings) and p3's strange wording, we allow a const volatile
2802 // reference to bind to an rvalue. Hence the check for the presence
2803 // of "const" rather than checking for "const" being the only
2804 // qualifier.
2805 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002806 return ICS;
2807
Douglas Gregorf93df192010-04-18 08:46:23 +00002808 // -- if T2 is a class type and
2809 // -- the initializer expression is an rvalue and "cv1 T1"
2810 // is reference-compatible with "cv2 T2," or
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002811 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002812 // -- T1 is not reference-related to T2 and the initializer
2813 // expression can be implicitly converted to an rvalue
2814 // of type "cv3 T3" (this conversion is selected by
2815 // enumerating the applicable conversion functions
2816 // (13.3.1.6) and choosing the best one through overload
2817 // resolution (13.3)),
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002818 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002819 // then the reference is bound to the initializer
2820 // expression rvalue in the first case and to the object
2821 // that is the result of the conversion in the second case
2822 // (or, in either case, to the appropriate base class
2823 // subobject of the object).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002824 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002825 // We're only checking the first case here, which is a direct
2826 // binding in C++0x but not in C++03.
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002827 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
2828 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2829 ICS.setStandard();
2830 ICS.Standard.First = ICK_Identity;
2831 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2832 ICS.Standard.Third = ICK_Identity;
2833 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2834 ICS.Standard.setToType(0, T2);
2835 ICS.Standard.setToType(1, T1);
2836 ICS.Standard.setToType(2, T1);
2837 ICS.Standard.ReferenceBinding = true;
Douglas Gregorf93df192010-04-18 08:46:23 +00002838 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002839 ICS.Standard.RRefBinding = isRValRef;
2840 ICS.Standard.CopyConstructor = 0;
2841 return ICS;
2842 }
2843
2844 // -- Otherwise, a temporary of type "cv1 T1" is created and
2845 // initialized from the initializer expression using the
2846 // rules for a non-reference copy initialization (8.5). The
2847 // reference is then bound to the temporary. If T1 is
2848 // reference-related to T2, cv1 must be the same
2849 // cv-qualification as, or greater cv-qualification than,
2850 // cv2; otherwise, the program is ill-formed.
2851 if (RefRelationship == Sema::Ref_Related) {
2852 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2853 // we would be reference-compatible or reference-compatible with
2854 // added qualification. But that wasn't the case, so the reference
2855 // initialization fails.
2856 return ICS;
2857 }
2858
2859 // If at least one of the types is a class type, the types are not
2860 // related, and we aren't allowed any user conversions, the
2861 // reference binding fails. This case is important for breaking
2862 // recursion, since TryImplicitConversion below will attempt to
2863 // create a temporary through the use of a copy constructor.
2864 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2865 (T1->isRecordType() || T2->isRecordType()))
2866 return ICS;
2867
2868 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002869 // When a parameter of reference type is not bound directly to
2870 // an argument expression, the conversion sequence is the one
2871 // required to convert the argument expression to the
2872 // underlying type of the reference according to
2873 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2874 // to copy-initializing a temporary of the underlying type with
2875 // the argument expression. Any difference in top-level
2876 // cv-qualification is subsumed by the initialization itself
2877 // and does not constitute a conversion.
2878 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2879 /*AllowExplicit=*/false,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002880 /*InOverloadResolution=*/false);
2881
2882 // Of course, that's still a reference binding.
2883 if (ICS.isStandard()) {
2884 ICS.Standard.ReferenceBinding = true;
2885 ICS.Standard.RRefBinding = isRValRef;
2886 } else if (ICS.isUserDefined()) {
2887 ICS.UserDefined.After.ReferenceBinding = true;
2888 ICS.UserDefined.After.RRefBinding = isRValRef;
2889 }
2890 return ICS;
2891}
2892
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002893/// TryCopyInitialization - Try to copy-initialize a value of type
2894/// ToType from the expression From. Return the implicit conversion
2895/// sequence required to pass this argument, which may be a bad
2896/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002897/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00002898/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002899static ImplicitConversionSequence
2900TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00002901 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002902 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002903 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002904 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002905 /*FIXME:*/From->getLocStart(),
2906 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002907 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002908
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002909 return S.TryImplicitConversion(From, ToType,
2910 SuppressUserConversions,
2911 /*AllowExplicit=*/false,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002912 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002913}
2914
Douglas Gregor436424c2008-11-18 23:14:02 +00002915/// TryObjectArgumentInitialization - Try to initialize the object
2916/// parameter of the given member function (@c Method) from the
2917/// expression @p From.
2918ImplicitConversionSequence
John McCall47000992010-01-14 03:28:57 +00002919Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall6e9f8f62009-12-03 04:06:58 +00002920 CXXMethodDecl *Method,
2921 CXXRecordDecl *ActingContext) {
2922 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002923 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2924 // const volatile object.
2925 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2926 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2927 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002928
2929 // Set up the conversion sequence as a "bad" conversion, to allow us
2930 // to exit early.
2931 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00002932
2933 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00002934 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002935 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002936 FromType = PT->getPointeeType();
2937
2938 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002939
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002940 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002941 // where X is the class of which the function is a member
2942 // (C++ [over.match.funcs]p4). However, when finding an implicit
2943 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002944 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002945 // (C++ [over.match.funcs]p5). We perform a simplified version of
2946 // reference binding here, that allows class rvalues to bind to
2947 // non-constant references.
2948
2949 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2950 // with the implicit object parameter (C++ [over.match.funcs]p5).
2951 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002952 if (ImplicitParamType.getCVRQualifiers()
2953 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00002954 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00002955 ICS.setBad(BadConversionSequence::bad_qualifiers,
2956 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002957 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002958 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002959
2960 // Check that we have either the same type or a derived type. It
2961 // affects the conversion rank.
2962 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00002963 ImplicitConversionKind SecondKind;
2964 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2965 SecondKind = ICK_Identity;
2966 } else if (IsDerivedFrom(FromType, ClassType))
2967 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00002968 else {
John McCall65eb8792010-02-25 01:37:24 +00002969 ICS.setBad(BadConversionSequence::unrelated_class,
2970 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002971 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002972 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002973
2974 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00002975 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00002976 ICS.Standard.setAsIdentityConversion();
2977 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00002978 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002979 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002980 ICS.Standard.ReferenceBinding = true;
2981 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002982 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002983 return ICS;
2984}
2985
2986/// PerformObjectArgumentInitialization - Perform initialization of
2987/// the implicit object parameter for the given Method with the given
2988/// expression.
2989bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002990Sema::PerformObjectArgumentInitialization(Expr *&From,
2991 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002992 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002993 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002994 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002995 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002996 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002997
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002998 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002999 FromRecordType = PT->getPointeeType();
3000 DestType = Method->getThisType(Context);
3001 } else {
3002 FromRecordType = From->getType();
3003 DestType = ImplicitParamRecordType;
3004 }
3005
John McCall6e9f8f62009-12-03 04:06:58 +00003006 // Note that we always use the true parent context when performing
3007 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003008 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00003009 = TryObjectArgumentInitialization(From->getType(), Method,
3010 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00003011 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00003012 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003013 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003014 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003015
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003016 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00003017 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00003018
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003019 if (!Context.hasSameType(From->getType(), DestType))
Anders Carlsson0c509ee2010-04-24 16:57:13 +00003020 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
3021 /*isLvalue=*/!From->getType()->isPointerType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003022 return false;
3023}
3024
Douglas Gregor5fb53972009-01-14 15:45:31 +00003025/// TryContextuallyConvertToBool - Attempt to contextually convert the
3026/// expression From to bool (C++0x [conv]p3).
3027ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003028 // FIXME: This is pretty broken.
Mike Stump11289f42009-09-09 15:08:12 +00003029 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003030 // FIXME: Are these flags correct?
3031 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003032 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00003033 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003034}
3035
3036/// PerformContextuallyConvertToBool - Perform a contextual conversion
3037/// of the expression From to bool (C++0x [conv]p3).
3038bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
3039 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00003040 if (!ICS.isBad())
3041 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003042
Fariborz Jahanian76197412009-11-18 18:26:29 +00003043 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003044 return Diag(From->getSourceRange().getBegin(),
3045 diag::err_typecheck_bool_condition)
3046 << From->getType() << From->getSourceRange();
3047 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003048}
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003049
3050/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3051/// expression From to 'id'.
3052ImplicitConversionSequence Sema::TryContextuallyConvertToObjCId(Expr *From) {
John McCall8b07ec22010-05-15 11:32:37 +00003053 QualType Ty = Context.getObjCIdType();
3054 return TryImplicitConversion(From, Ty,
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003055 // FIXME: Are these flags correct?
3056 /*SuppressUserConversions=*/false,
3057 /*AllowExplicit=*/true,
3058 /*InOverloadResolution=*/false);
3059}
3060
3061/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3062/// of the expression From to 'id'.
3063bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCall8b07ec22010-05-15 11:32:37 +00003064 QualType Ty = Context.getObjCIdType();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003065 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(From);
3066 if (!ICS.isBad())
3067 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3068 return true;
3069}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003070
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003071/// \brief Attempt to convert the given expression to an integral or
3072/// enumeration type.
3073///
3074/// This routine will attempt to convert an expression of class type to an
3075/// integral or enumeration type, if that class type only has a single
3076/// conversion to an integral or enumeration type.
3077///
3078/// \param From The expression we're converting from.
3079///
3080/// \returns The expression converted to an integral or enumeration type,
3081/// if successful, or an invalid expression.
3082Sema::OwningExprResult
3083Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, ExprArg FromE,
3084 const PartialDiagnostic &NotIntDiag,
3085 const PartialDiagnostic &IncompleteDiag,
3086 const PartialDiagnostic &ExplicitConvDiag,
3087 const PartialDiagnostic &ExplicitConvNote,
3088 const PartialDiagnostic &AmbigDiag,
3089 const PartialDiagnostic &AmbigNote) {
3090 Expr *From = static_cast<Expr *>(FromE.get());
3091
3092 // We can't perform any more checking for type-dependent expressions.
3093 if (From->isTypeDependent())
3094 return move(FromE);
3095
3096 // If the expression already has integral or enumeration type, we're golden.
3097 QualType T = From->getType();
3098 if (T->isIntegralOrEnumerationType())
3099 return move(FromE);
3100
3101 // FIXME: Check for missing '()' if T is a function type?
3102
3103 // If we don't have a class type in C++, there's no way we can get an
3104 // expression of integral or enumeration type.
3105 const RecordType *RecordTy = T->getAs<RecordType>();
3106 if (!RecordTy || !getLangOptions().CPlusPlus) {
3107 Diag(Loc, NotIntDiag)
3108 << T << From->getSourceRange();
3109 return ExprError();
3110 }
3111
3112 // We must have a complete class type.
3113 if (RequireCompleteType(Loc, T, IncompleteDiag))
3114 return ExprError();
3115
3116 // Look for a conversion to an integral or enumeration type.
3117 UnresolvedSet<4> ViableConversions;
3118 UnresolvedSet<4> ExplicitConversions;
3119 const UnresolvedSetImpl *Conversions
3120 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3121
3122 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3123 E = Conversions->end();
3124 I != E;
3125 ++I) {
3126 if (CXXConversionDecl *Conversion
3127 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3128 if (Conversion->getConversionType().getNonReferenceType()
3129 ->isIntegralOrEnumerationType()) {
3130 if (Conversion->isExplicit())
3131 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3132 else
3133 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3134 }
3135 }
3136
3137 switch (ViableConversions.size()) {
3138 case 0:
3139 if (ExplicitConversions.size() == 1) {
3140 DeclAccessPair Found = ExplicitConversions[0];
3141 CXXConversionDecl *Conversion
3142 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3143
3144 // The user probably meant to invoke the given explicit
3145 // conversion; use it.
3146 QualType ConvTy
3147 = Conversion->getConversionType().getNonReferenceType();
3148 std::string TypeStr;
3149 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3150
3151 Diag(Loc, ExplicitConvDiag)
3152 << T << ConvTy
3153 << FixItHint::CreateInsertion(From->getLocStart(),
3154 "static_cast<" + TypeStr + ">(")
3155 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3156 ")");
3157 Diag(Conversion->getLocation(), ExplicitConvNote)
3158 << ConvTy->isEnumeralType() << ConvTy;
3159
3160 // If we aren't in a SFINAE context, build a call to the
3161 // explicit conversion function.
3162 if (isSFINAEContext())
3163 return ExprError();
3164
3165 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
3166 From = BuildCXXMemberCallExpr(FromE.takeAs<Expr>(), Found, Conversion);
3167 FromE = Owned(From);
3168 }
3169
3170 // We'll complain below about a non-integral condition type.
3171 break;
3172
3173 case 1: {
3174 // Apply this conversion.
3175 DeclAccessPair Found = ViableConversions[0];
3176 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
3177 From = BuildCXXMemberCallExpr(FromE.takeAs<Expr>(), Found,
3178 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
3179 FromE = Owned(From);
3180 break;
3181 }
3182
3183 default:
3184 Diag(Loc, AmbigDiag)
3185 << T << From->getSourceRange();
3186 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3187 CXXConversionDecl *Conv
3188 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3189 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3190 Diag(Conv->getLocation(), AmbigNote)
3191 << ConvTy->isEnumeralType() << ConvTy;
3192 }
3193 return ExprError();
3194 }
3195
3196 if (!From->getType()->isIntegralOrEnumerationType()) {
3197 Diag(Loc, NotIntDiag)
3198 << From->getType() << From->getSourceRange();
3199 return ExprError();
3200 }
3201
3202 return move(FromE);
3203}
3204
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003205/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003206/// candidate functions, using the given function call arguments. If
3207/// @p SuppressUserConversions, then don't allow user-defined
3208/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003209///
3210/// \para PartialOverloading true if we are performing "partial" overloading
3211/// based on an incomplete set of function arguments. This feature is used by
3212/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003213void
3214Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003215 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003216 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003217 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003218 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003219 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003220 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003221 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003222 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003223 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003224 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003225
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003226 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003227 if (!isa<CXXConstructorDecl>(Method)) {
3228 // If we get here, it's because we're calling a member function
3229 // that is named without a member access expression (e.g.,
3230 // "this->f") that was either written explicitly or created
3231 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003232 // function, e.g., X::f(). We use an empty type for the implied
3233 // object argument (C++ [over.call.func]p3), and the acting context
3234 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003235 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00003236 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003237 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003238 return;
3239 }
3240 // We treat a constructor like a non-member function, since its object
3241 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003242 }
3243
Douglas Gregorff7028a2009-11-13 23:59:09 +00003244 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003245 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003246
Douglas Gregor27381f32009-11-23 12:27:39 +00003247 // Overload resolution is always an unevaluated context.
3248 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3249
Douglas Gregorffe14e32009-11-14 01:20:54 +00003250 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3251 // C++ [class.copy]p3:
3252 // A member function template is never instantiated to perform the copy
3253 // of a class object to an object of its class type.
3254 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3255 if (NumArgs == 1 &&
3256 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003257 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3258 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003259 return;
3260 }
3261
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003262 // Add this candidate
3263 CandidateSet.push_back(OverloadCandidate());
3264 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003265 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003266 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003267 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003268 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003269 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003270
3271 unsigned NumArgsInProto = Proto->getNumArgs();
3272
3273 // (C++ 13.3.2p2): A candidate function having fewer than m
3274 // parameters is viable only if it has an ellipsis in its parameter
3275 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00003276 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3277 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003278 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003279 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003280 return;
3281 }
3282
3283 // (C++ 13.3.2p2): A candidate function having more than m parameters
3284 // is viable only if the (m+1)st parameter has a default argument
3285 // (8.3.6). For the purposes of overload resolution, the
3286 // parameter list is truncated on the right, so that there are
3287 // exactly m parameters.
3288 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003289 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003290 // Not enough arguments.
3291 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003292 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003293 return;
3294 }
3295
3296 // Determine the implicit conversion sequences for each of the
3297 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003298 Candidate.Conversions.resize(NumArgs);
3299 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3300 if (ArgIdx < NumArgsInProto) {
3301 // (C++ 13.3.2p3): for F to be a viable function, there shall
3302 // exist for each argument an implicit conversion sequence
3303 // (13.3.3.1) that converts that argument to the corresponding
3304 // parameter of F.
3305 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003306 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003307 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00003308 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003309 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003310 if (Candidate.Conversions[ArgIdx].isBad()) {
3311 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003312 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003313 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003314 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003315 } else {
3316 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3317 // argument for which there is no corresponding parameter is
3318 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003319 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003320 }
3321 }
3322}
3323
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003324/// \brief Add all of the function declarations in the given function set to
3325/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003326void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003327 Expr **Args, unsigned NumArgs,
3328 OverloadCandidateSet& CandidateSet,
3329 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003330 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003331 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3332 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003333 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003334 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003335 cast<CXXMethodDecl>(FD)->getParent(),
3336 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003337 CandidateSet, SuppressUserConversions);
3338 else
John McCalla0296f72010-03-19 07:35:19 +00003339 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003340 SuppressUserConversions);
3341 } else {
John McCalla0296f72010-03-19 07:35:19 +00003342 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003343 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3344 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003345 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003346 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003347 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003348 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003349 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003350 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003351 else
John McCalla0296f72010-03-19 07:35:19 +00003352 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003353 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003354 Args, NumArgs, CandidateSet,
3355 SuppressUserConversions);
3356 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003357 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003358}
3359
John McCallf0f1cf02009-11-17 07:50:12 +00003360/// AddMethodCandidate - Adds a named decl (which is some kind of
3361/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003362void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003363 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00003364 Expr **Args, unsigned NumArgs,
3365 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003366 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003367 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003368 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003369
3370 if (isa<UsingShadowDecl>(Decl))
3371 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3372
3373 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3374 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3375 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003376 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3377 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003378 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003379 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003380 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003381 } else {
John McCalla0296f72010-03-19 07:35:19 +00003382 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00003383 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003384 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003385 }
3386}
3387
Douglas Gregor436424c2008-11-18 23:14:02 +00003388/// AddMethodCandidate - Adds the given C++ member function to the set
3389/// of candidate functions, using the given function call arguments
3390/// and the object argument (@c Object). For example, in a call
3391/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3392/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3393/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003394/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003395void
John McCalla0296f72010-03-19 07:35:19 +00003396Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003397 CXXRecordDecl *ActingContext, QualType ObjectType,
3398 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003399 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003400 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003401 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003402 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003403 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003404 assert(!isa<CXXConstructorDecl>(Method) &&
3405 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003406
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003407 if (!CandidateSet.isNewCandidate(Method))
3408 return;
3409
Douglas Gregor27381f32009-11-23 12:27:39 +00003410 // Overload resolution is always an unevaluated context.
3411 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3412
Douglas Gregor436424c2008-11-18 23:14:02 +00003413 // Add this candidate
3414 CandidateSet.push_back(OverloadCandidate());
3415 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003416 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003417 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003418 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003419 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003420
3421 unsigned NumArgsInProto = Proto->getNumArgs();
3422
3423 // (C++ 13.3.2p2): A candidate function having fewer than m
3424 // parameters is viable only if it has an ellipsis in its parameter
3425 // list (8.3.5).
3426 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3427 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003428 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003429 return;
3430 }
3431
3432 // (C++ 13.3.2p2): A candidate function having more than m parameters
3433 // is viable only if the (m+1)st parameter has a default argument
3434 // (8.3.6). For the purposes of overload resolution, the
3435 // parameter list is truncated on the right, so that there are
3436 // exactly m parameters.
3437 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3438 if (NumArgs < MinRequiredArgs) {
3439 // Not enough arguments.
3440 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003441 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003442 return;
3443 }
3444
3445 Candidate.Viable = true;
3446 Candidate.Conversions.resize(NumArgs + 1);
3447
John McCall6e9f8f62009-12-03 04:06:58 +00003448 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003449 // The implicit object argument is ignored.
3450 Candidate.IgnoreObjectArgument = true;
3451 else {
3452 // Determine the implicit conversion sequence for the object
3453 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00003454 Candidate.Conversions[0]
3455 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003456 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003457 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003458 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003459 return;
3460 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003461 }
3462
3463 // Determine the implicit conversion sequences for each of the
3464 // arguments.
3465 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3466 if (ArgIdx < NumArgsInProto) {
3467 // (C++ 13.3.2p3): for F to be a viable function, there shall
3468 // exist for each argument an implicit conversion sequence
3469 // (13.3.3.1) that converts that argument to the corresponding
3470 // parameter of F.
3471 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003472 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003473 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003474 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003475 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003476 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003477 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003478 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003479 break;
3480 }
3481 } else {
3482 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3483 // argument for which there is no corresponding parameter is
3484 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003485 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003486 }
3487 }
3488}
Douglas Gregor3626a5c2010-05-08 17:41:32 +00003489
Douglas Gregor97628d62009-08-21 00:16:32 +00003490/// \brief Add a C++ member function template as a candidate to the candidate
3491/// set, using template argument deduction to produce an appropriate member
3492/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003493void
Douglas Gregor97628d62009-08-21 00:16:32 +00003494Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003495 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003496 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003497 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003498 QualType ObjectType,
3499 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003500 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003501 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003502 if (!CandidateSet.isNewCandidate(MethodTmpl))
3503 return;
3504
Douglas Gregor97628d62009-08-21 00:16:32 +00003505 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003506 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003507 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003508 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003509 // candidate functions in the usual way.113) A given name can refer to one
3510 // or more function templates and also to a set of overloaded non-template
3511 // functions. In such a case, the candidate functions generated from each
3512 // function template are combined with the set of non-template candidate
3513 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003514 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003515 FunctionDecl *Specialization = 0;
3516 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003517 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003518 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003519 CandidateSet.push_back(OverloadCandidate());
3520 OverloadCandidate &Candidate = CandidateSet.back();
3521 Candidate.FoundDecl = FoundDecl;
3522 Candidate.Function = MethodTmpl->getTemplatedDecl();
3523 Candidate.Viable = false;
3524 Candidate.FailureKind = ovl_fail_bad_deduction;
3525 Candidate.IsSurrogate = false;
3526 Candidate.IgnoreObjectArgument = false;
3527 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3528 Info);
3529 return;
3530 }
Mike Stump11289f42009-09-09 15:08:12 +00003531
Douglas Gregor97628d62009-08-21 00:16:32 +00003532 // Add the function template specialization produced by template argument
3533 // deduction as a candidate.
3534 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003535 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003536 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003537 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003538 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003539 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003540}
3541
Douglas Gregor05155d82009-08-21 23:19:43 +00003542/// \brief Add a C++ function template specialization as a candidate
3543/// in the candidate set, using template argument deduction to produce
3544/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003545void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003546Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003547 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003548 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003549 Expr **Args, unsigned NumArgs,
3550 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003551 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003552 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3553 return;
3554
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003555 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003556 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003557 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003558 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003559 // candidate functions in the usual way.113) A given name can refer to one
3560 // or more function templates and also to a set of overloaded non-template
3561 // functions. In such a case, the candidate functions generated from each
3562 // function template are combined with the set of non-template candidate
3563 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003564 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003565 FunctionDecl *Specialization = 0;
3566 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003567 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003568 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003569 CandidateSet.push_back(OverloadCandidate());
3570 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003571 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003572 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3573 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003574 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003575 Candidate.IsSurrogate = false;
3576 Candidate.IgnoreObjectArgument = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003577 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3578 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003579 return;
3580 }
Mike Stump11289f42009-09-09 15:08:12 +00003581
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003582 // Add the function template specialization produced by template argument
3583 // deduction as a candidate.
3584 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003585 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003586 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003587}
Mike Stump11289f42009-09-09 15:08:12 +00003588
Douglas Gregora1f013e2008-11-07 22:36:19 +00003589/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003590/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003591/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003592/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003593/// (which may or may not be the same type as the type that the
3594/// conversion function produces).
3595void
3596Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003597 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003598 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003599 Expr *From, QualType ToType,
3600 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003601 assert(!Conversion->getDescribedFunctionTemplate() &&
3602 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003603 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003604 if (!CandidateSet.isNewCandidate(Conversion))
3605 return;
3606
Douglas Gregor27381f32009-11-23 12:27:39 +00003607 // Overload resolution is always an unevaluated context.
3608 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3609
Douglas Gregora1f013e2008-11-07 22:36:19 +00003610 // Add this candidate
3611 CandidateSet.push_back(OverloadCandidate());
3612 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003613 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003614 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003615 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003616 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003617 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003618 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003619 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003620
Douglas Gregor436424c2008-11-18 23:14:02 +00003621 // Determine the implicit conversion sequence for the implicit
3622 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00003623 Candidate.Viable = true;
3624 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00003625 Candidate.Conversions[0]
3626 = TryObjectArgumentInitialization(From->getType(), Conversion,
3627 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00003628 // Conversion functions to a different type in the base class is visible in
3629 // the derived class. So, a derived to base conversion should not participate
3630 // in overload resolution.
3631 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
3632 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00003633 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003634 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003635 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003636 return;
3637 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003638
3639 // We won't go through a user-define type conversion function to convert a
3640 // derived to base as such conversions are given Conversion Rank. They only
3641 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3642 QualType FromCanon
3643 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3644 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3645 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3646 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003647 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003648 return;
3649 }
3650
Douglas Gregora1f013e2008-11-07 22:36:19 +00003651 // To determine what the conversion from the result of calling the
3652 // conversion function to the type we're eventually trying to
3653 // convert to (ToType), we need to synthesize a call to the
3654 // conversion function and attempt copy initialization from it. This
3655 // makes sure that we get the right semantics with respect to
3656 // lvalues/rvalues and the type. Fortunately, we can allocate this
3657 // call on the stack and we don't need its arguments to be
3658 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003659 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003660 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00003661 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00003662 CastExpr::CK_FunctionToPointerDecay,
Anders Carlsson0c509ee2010-04-24 16:57:13 +00003663 &ConversionRef, CXXBaseSpecifierArray(), false);
Mike Stump11289f42009-09-09 15:08:12 +00003664
3665 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003666 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3667 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00003668 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003669 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003670 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003671 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003672 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003673 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003674 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003675
John McCall0d1da222010-01-12 00:44:57 +00003676 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003677 case ImplicitConversionSequence::StandardConversion:
3678 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003679
3680 // C++ [over.ics.user]p3:
3681 // If the user-defined conversion is specified by a specialization of a
3682 // conversion function template, the second standard conversion sequence
3683 // shall have exact match rank.
3684 if (Conversion->getPrimaryTemplate() &&
3685 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3686 Candidate.Viable = false;
3687 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3688 }
3689
Douglas Gregora1f013e2008-11-07 22:36:19 +00003690 break;
3691
3692 case ImplicitConversionSequence::BadConversion:
3693 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003694 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003695 break;
3696
3697 default:
Mike Stump11289f42009-09-09 15:08:12 +00003698 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003699 "Can only end up with a standard conversion sequence or failure");
3700 }
3701}
3702
Douglas Gregor05155d82009-08-21 23:19:43 +00003703/// \brief Adds a conversion function template specialization
3704/// candidate to the overload set, using template argument deduction
3705/// to deduce the template arguments of the conversion function
3706/// template from the type that we are converting to (C++
3707/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003708void
Douglas Gregor05155d82009-08-21 23:19:43 +00003709Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003710 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003711 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003712 Expr *From, QualType ToType,
3713 OverloadCandidateSet &CandidateSet) {
3714 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3715 "Only conversion function templates permitted here");
3716
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003717 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3718 return;
3719
John McCallbc077cf2010-02-08 23:07:23 +00003720 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003721 CXXConversionDecl *Specialization = 0;
3722 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003723 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003724 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003725 CandidateSet.push_back(OverloadCandidate());
3726 OverloadCandidate &Candidate = CandidateSet.back();
3727 Candidate.FoundDecl = FoundDecl;
3728 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3729 Candidate.Viable = false;
3730 Candidate.FailureKind = ovl_fail_bad_deduction;
3731 Candidate.IsSurrogate = false;
3732 Candidate.IgnoreObjectArgument = false;
3733 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3734 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00003735 return;
3736 }
Mike Stump11289f42009-09-09 15:08:12 +00003737
Douglas Gregor05155d82009-08-21 23:19:43 +00003738 // Add the conversion function template specialization produced by
3739 // template argument deduction as a candidate.
3740 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003741 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00003742 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003743}
3744
Douglas Gregorab7897a2008-11-19 22:57:39 +00003745/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3746/// converts the given @c Object to a function pointer via the
3747/// conversion function @c Conversion, and then attempts to call it
3748/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3749/// the type of function that we'll eventually be calling.
3750void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003751 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003752 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003753 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00003754 QualType ObjectType,
3755 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00003756 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003757 if (!CandidateSet.isNewCandidate(Conversion))
3758 return;
3759
Douglas Gregor27381f32009-11-23 12:27:39 +00003760 // Overload resolution is always an unevaluated context.
3761 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3762
Douglas Gregorab7897a2008-11-19 22:57:39 +00003763 CandidateSet.push_back(OverloadCandidate());
3764 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003765 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003766 Candidate.Function = 0;
3767 Candidate.Surrogate = Conversion;
3768 Candidate.Viable = true;
3769 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003770 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003771 Candidate.Conversions.resize(NumArgs + 1);
3772
3773 // Determine the implicit conversion sequence for the implicit
3774 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003775 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00003776 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003777 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003778 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003779 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00003780 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003781 return;
3782 }
3783
3784 // The first conversion is actually a user-defined conversion whose
3785 // first conversion is ObjectInit's standard conversion (which is
3786 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00003787 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003788 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003789 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003790 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00003791 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00003792 = Candidate.Conversions[0].UserDefined.Before;
3793 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3794
Mike Stump11289f42009-09-09 15:08:12 +00003795 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00003796 unsigned NumArgsInProto = Proto->getNumArgs();
3797
3798 // (C++ 13.3.2p2): A candidate function having fewer than m
3799 // parameters is viable only if it has an ellipsis in its parameter
3800 // list (8.3.5).
3801 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3802 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003803 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003804 return;
3805 }
3806
3807 // Function types don't have any default arguments, so just check if
3808 // we have enough arguments.
3809 if (NumArgs < NumArgsInProto) {
3810 // Not enough arguments.
3811 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003812 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003813 return;
3814 }
3815
3816 // Determine the implicit conversion sequences for each of the
3817 // arguments.
3818 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3819 if (ArgIdx < NumArgsInProto) {
3820 // (C++ 13.3.2p3): for F to be a viable function, there shall
3821 // exist for each argument an implicit conversion sequence
3822 // (13.3.3.1) that converts that argument to the corresponding
3823 // parameter of F.
3824 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003825 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003826 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003827 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00003828 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00003829 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003830 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003831 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003832 break;
3833 }
3834 } else {
3835 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3836 // argument for which there is no corresponding parameter is
3837 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003838 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003839 }
3840 }
3841}
3842
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003843/// \brief Add overload candidates for overloaded operators that are
3844/// member functions.
3845///
3846/// Add the overloaded operator candidates that are member functions
3847/// for the operator Op that was used in an operator expression such
3848/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3849/// CandidateSet will store the added overload candidates. (C++
3850/// [over.match.oper]).
3851void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3852 SourceLocation OpLoc,
3853 Expr **Args, unsigned NumArgs,
3854 OverloadCandidateSet& CandidateSet,
3855 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003856 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3857
3858 // C++ [over.match.oper]p3:
3859 // For a unary operator @ with an operand of a type whose
3860 // cv-unqualified version is T1, and for a binary operator @ with
3861 // a left operand of a type whose cv-unqualified version is T1 and
3862 // a right operand of a type whose cv-unqualified version is T2,
3863 // three sets of candidate functions, designated member
3864 // candidates, non-member candidates and built-in candidates, are
3865 // constructed as follows:
3866 QualType T1 = Args[0]->getType();
3867 QualType T2;
3868 if (NumArgs > 1)
3869 T2 = Args[1]->getType();
3870
3871 // -- If T1 is a class type, the set of member candidates is the
3872 // result of the qualified lookup of T1::operator@
3873 // (13.3.1.1.1); otherwise, the set of member candidates is
3874 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003875 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003876 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003877 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003878 return;
Mike Stump11289f42009-09-09 15:08:12 +00003879
John McCall27b18f82009-11-17 02:14:36 +00003880 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3881 LookupQualifiedName(Operators, T1Rec->getDecl());
3882 Operators.suppressDiagnostics();
3883
Mike Stump11289f42009-09-09 15:08:12 +00003884 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003885 OperEnd = Operators.end();
3886 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00003887 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00003888 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00003889 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00003890 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00003891 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003892}
3893
Douglas Gregora11693b2008-11-12 17:17:38 +00003894/// AddBuiltinCandidate - Add a candidate for a built-in
3895/// operator. ResultTy and ParamTys are the result and parameter types
3896/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00003897/// arguments being passed to the candidate. IsAssignmentOperator
3898/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00003899/// operator. NumContextualBoolArguments is the number of arguments
3900/// (at the beginning of the argument list) that will be contextually
3901/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00003902void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00003903 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00003904 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003905 bool IsAssignmentOperator,
3906 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00003907 // Overload resolution is always an unevaluated context.
3908 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3909
Douglas Gregora11693b2008-11-12 17:17:38 +00003910 // Add this candidate
3911 CandidateSet.push_back(OverloadCandidate());
3912 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003913 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00003914 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00003915 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003916 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00003917 Candidate.BuiltinTypes.ResultTy = ResultTy;
3918 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3919 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3920
3921 // Determine the implicit conversion sequences for each of the
3922 // arguments.
3923 Candidate.Viable = true;
3924 Candidate.Conversions.resize(NumArgs);
3925 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00003926 // C++ [over.match.oper]p4:
3927 // For the built-in assignment operators, conversions of the
3928 // left operand are restricted as follows:
3929 // -- no temporaries are introduced to hold the left operand, and
3930 // -- no user-defined conversions are applied to the left
3931 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00003932 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00003933 //
3934 // We block these conversions by turning off user-defined
3935 // conversions, since that is the only way that initialization of
3936 // a reference to a non-class type can occur from something that
3937 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003938 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00003939 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00003940 "Contextual conversion to bool requires bool type");
3941 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3942 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003943 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003944 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00003945 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00003946 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003947 }
John McCall0d1da222010-01-12 00:44:57 +00003948 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003949 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003950 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003951 break;
3952 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003953 }
3954}
3955
3956/// BuiltinCandidateTypeSet - A set of types that will be used for the
3957/// candidate operator functions for built-in operators (C++
3958/// [over.built]). The types are separated into pointer types and
3959/// enumeration types.
3960class BuiltinCandidateTypeSet {
3961 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003962 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00003963
3964 /// PointerTypes - The set of pointer types that will be used in the
3965 /// built-in candidates.
3966 TypeSet PointerTypes;
3967
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003968 /// MemberPointerTypes - The set of member pointer types that will be
3969 /// used in the built-in candidates.
3970 TypeSet MemberPointerTypes;
3971
Douglas Gregora11693b2008-11-12 17:17:38 +00003972 /// EnumerationTypes - The set of enumeration types that will be
3973 /// used in the built-in candidates.
3974 TypeSet EnumerationTypes;
3975
Douglas Gregorcbfbca12010-05-19 03:21:00 +00003976 /// \brief The set of vector types that will be used in the built-in
3977 /// candidates.
3978 TypeSet VectorTypes;
3979
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003980 /// Sema - The semantic analysis instance where we are building the
3981 /// candidate type set.
3982 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003983
Douglas Gregora11693b2008-11-12 17:17:38 +00003984 /// Context - The AST context in which we will build the type sets.
3985 ASTContext &Context;
3986
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003987 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3988 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003989 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003990
3991public:
3992 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003993 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003994
Mike Stump11289f42009-09-09 15:08:12 +00003995 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003996 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003997
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003998 void AddTypesConvertedFrom(QualType Ty,
3999 SourceLocation Loc,
4000 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004001 bool AllowExplicitConversions,
4002 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004003
4004 /// pointer_begin - First pointer type found;
4005 iterator pointer_begin() { return PointerTypes.begin(); }
4006
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004007 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004008 iterator pointer_end() { return PointerTypes.end(); }
4009
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004010 /// member_pointer_begin - First member pointer type found;
4011 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4012
4013 /// member_pointer_end - Past the last member pointer type found;
4014 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4015
Douglas Gregora11693b2008-11-12 17:17:38 +00004016 /// enumeration_begin - First enumeration type found;
4017 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4018
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004019 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004020 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004021
4022 iterator vector_begin() { return VectorTypes.begin(); }
4023 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregora11693b2008-11-12 17:17:38 +00004024};
4025
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004026/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004027/// the set of pointer types along with any more-qualified variants of
4028/// that type. For example, if @p Ty is "int const *", this routine
4029/// will add "int const *", "int const volatile *", "int const
4030/// restrict *", and "int const volatile restrict *" to the set of
4031/// pointer types. Returns true if the add of @p Ty itself succeeded,
4032/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004033///
4034/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004035bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004036BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4037 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004038
Douglas Gregora11693b2008-11-12 17:17:38 +00004039 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004040 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004041 return false;
4042
John McCall8ccfcb52009-09-24 19:53:00 +00004043 const PointerType *PointerTy = Ty->getAs<PointerType>();
4044 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00004045
John McCall8ccfcb52009-09-24 19:53:00 +00004046 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004047 // Don't add qualified variants of arrays. For one, they're not allowed
4048 // (the qualifier would sink to the element type), and for another, the
4049 // only overload situation where it matters is subscript or pointer +- int,
4050 // and those shouldn't have qualifier variants anyway.
4051 if (PointeeTy->isArrayType())
4052 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004053 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00004054 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00004055 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004056 bool hasVolatile = VisibleQuals.hasVolatile();
4057 bool hasRestrict = VisibleQuals.hasRestrict();
4058
John McCall8ccfcb52009-09-24 19:53:00 +00004059 // Iterate through all strict supersets of BaseCVR.
4060 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4061 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004062 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4063 // in the types.
4064 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4065 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00004066 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4067 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00004068 }
4069
4070 return true;
4071}
4072
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004073/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4074/// to the set of pointer types along with any more-qualified variants of
4075/// that type. For example, if @p Ty is "int const *", this routine
4076/// will add "int const *", "int const volatile *", "int const
4077/// restrict *", and "int const volatile restrict *" to the set of
4078/// pointer types. Returns true if the add of @p Ty itself succeeded,
4079/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004080///
4081/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004082bool
4083BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4084 QualType Ty) {
4085 // Insert this type.
4086 if (!MemberPointerTypes.insert(Ty))
4087 return false;
4088
John McCall8ccfcb52009-09-24 19:53:00 +00004089 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4090 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004091
John McCall8ccfcb52009-09-24 19:53:00 +00004092 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004093 // Don't add qualified variants of arrays. For one, they're not allowed
4094 // (the qualifier would sink to the element type), and for another, the
4095 // only overload situation where it matters is subscript or pointer +- int,
4096 // and those shouldn't have qualifier variants anyway.
4097 if (PointeeTy->isArrayType())
4098 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004099 const Type *ClassTy = PointerTy->getClass();
4100
4101 // Iterate through all strict supersets of the pointee type's CVR
4102 // qualifiers.
4103 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4104 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4105 if ((CVR | BaseCVR) != CVR) continue;
4106
4107 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4108 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004109 }
4110
4111 return true;
4112}
4113
Douglas Gregora11693b2008-11-12 17:17:38 +00004114/// AddTypesConvertedFrom - Add each of the types to which the type @p
4115/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004116/// primarily interested in pointer types and enumeration types. We also
4117/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004118/// AllowUserConversions is true if we should look at the conversion
4119/// functions of a class type, and AllowExplicitConversions if we
4120/// should also include the explicit conversion functions of a class
4121/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004122void
Douglas Gregor5fb53972009-01-14 15:45:31 +00004123BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004124 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004125 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004126 bool AllowExplicitConversions,
4127 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004128 // Only deal with canonical types.
4129 Ty = Context.getCanonicalType(Ty);
4130
4131 // Look through reference types; they aren't part of the type of an
4132 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004133 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00004134 Ty = RefTy->getPointeeType();
4135
4136 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004137 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00004138
Sebastian Redl65ae2002009-11-05 16:36:20 +00004139 // If we're dealing with an array type, decay to the pointer.
4140 if (Ty->isArrayType())
4141 Ty = SemaRef.Context.getArrayDecayedType(Ty);
4142
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004143 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004144 QualType PointeeTy = PointerTy->getPointeeType();
4145
4146 // Insert our type, and its more-qualified variants, into the set
4147 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004148 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00004149 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004150 } else if (Ty->isMemberPointerType()) {
4151 // Member pointers are far easier, since the pointee can't be converted.
4152 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4153 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00004154 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00004155 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004156 } else if (Ty->isVectorType()) {
4157 VectorTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004158 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004159 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004160 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004161 // No conversion functions in incomplete types.
4162 return;
4163 }
Mike Stump11289f42009-09-09 15:08:12 +00004164
Douglas Gregora11693b2008-11-12 17:17:38 +00004165 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00004166 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00004167 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00004168 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004169 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004170 NamedDecl *D = I.getDecl();
4171 if (isa<UsingShadowDecl>(D))
4172 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004173
Mike Stump11289f42009-09-09 15:08:12 +00004174 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00004175 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00004176 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00004177 continue;
4178
John McCallda4458e2010-03-31 01:36:47 +00004179 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004180 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004181 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004182 VisibleQuals);
4183 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004184 }
4185 }
4186 }
4187}
4188
Douglas Gregor84605ae2009-08-24 13:43:27 +00004189/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4190/// the volatile- and non-volatile-qualified assignment operators for the
4191/// given type to the candidate set.
4192static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4193 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004194 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004195 unsigned NumArgs,
4196 OverloadCandidateSet &CandidateSet) {
4197 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004198
Douglas Gregor84605ae2009-08-24 13:43:27 +00004199 // T& operator=(T&, T)
4200 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4201 ParamTypes[1] = T;
4202 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4203 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004204
Douglas Gregor84605ae2009-08-24 13:43:27 +00004205 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4206 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004207 ParamTypes[0]
4208 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004209 ParamTypes[1] = T;
4210 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004211 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004212 }
4213}
Mike Stump11289f42009-09-09 15:08:12 +00004214
Sebastian Redl1054fae2009-10-25 17:03:50 +00004215/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4216/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004217static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4218 Qualifiers VRQuals;
4219 const RecordType *TyRec;
4220 if (const MemberPointerType *RHSMPType =
4221 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004222 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004223 else
4224 TyRec = ArgExpr->getType()->getAs<RecordType>();
4225 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004226 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004227 VRQuals.addVolatile();
4228 VRQuals.addRestrict();
4229 return VRQuals;
4230 }
4231
4232 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004233 if (!ClassDecl->hasDefinition())
4234 return VRQuals;
4235
John McCallad371252010-01-20 00:46:10 +00004236 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004237 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004238
John McCallad371252010-01-20 00:46:10 +00004239 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004240 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004241 NamedDecl *D = I.getDecl();
4242 if (isa<UsingShadowDecl>(D))
4243 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4244 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004245 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4246 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4247 CanTy = ResTypeRef->getPointeeType();
4248 // Need to go down the pointer/mempointer chain and add qualifiers
4249 // as see them.
4250 bool done = false;
4251 while (!done) {
4252 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4253 CanTy = ResTypePtr->getPointeeType();
4254 else if (const MemberPointerType *ResTypeMPtr =
4255 CanTy->getAs<MemberPointerType>())
4256 CanTy = ResTypeMPtr->getPointeeType();
4257 else
4258 done = true;
4259 if (CanTy.isVolatileQualified())
4260 VRQuals.addVolatile();
4261 if (CanTy.isRestrictQualified())
4262 VRQuals.addRestrict();
4263 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4264 return VRQuals;
4265 }
4266 }
4267 }
4268 return VRQuals;
4269}
4270
Douglas Gregord08452f2008-11-19 15:42:04 +00004271/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4272/// operator overloads to the candidate set (C++ [over.built]), based
4273/// on the operator @p Op and the arguments given. For example, if the
4274/// operator is a binary '+', this routine might add "int
4275/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00004276void
Mike Stump11289f42009-09-09 15:08:12 +00004277Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004278 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00004279 Expr **Args, unsigned NumArgs,
4280 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004281 // The set of "promoted arithmetic types", which are the arithmetic
4282 // types are that preserved by promotion (C++ [over.built]p2). Note
4283 // that the first few of these types are the promoted integral
4284 // types; these types need to be first.
4285 // FIXME: What about complex?
4286 const unsigned FirstIntegralType = 0;
4287 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00004288 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00004289 LastPromotedIntegralType = 13;
4290 const unsigned FirstPromotedArithmeticType = 7,
4291 LastPromotedArithmeticType = 16;
4292 const unsigned NumArithmeticTypes = 16;
4293 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00004294 Context.BoolTy, Context.CharTy, Context.WCharTy,
4295// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00004296 Context.SignedCharTy, Context.ShortTy,
4297 Context.UnsignedCharTy, Context.UnsignedShortTy,
4298 Context.IntTy, Context.LongTy, Context.LongLongTy,
4299 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
4300 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
4301 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00004302 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
4303 "Invalid first promoted integral type");
4304 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4305 == Context.UnsignedLongLongTy &&
4306 "Invalid last promoted integral type");
4307 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
4308 "Invalid first promoted arithmetic type");
4309 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4310 == Context.LongDoubleTy &&
4311 "Invalid last promoted arithmetic type");
4312
Douglas Gregora11693b2008-11-12 17:17:38 +00004313 // Find all of the types that the arguments can convert to, but only
4314 // if the operator we're looking at has built-in operator candidates
4315 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004316 Qualifiers VisibleTypeConversionsQuals;
4317 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004318 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4319 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4320
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004321 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004322 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4323 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4324 OpLoc,
4325 true,
4326 (Op == OO_Exclaim ||
4327 Op == OO_AmpAmp ||
4328 Op == OO_PipePipe),
4329 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004330
4331 bool isComparison = false;
4332 switch (Op) {
4333 case OO_None:
4334 case NUM_OVERLOADED_OPERATORS:
4335 assert(false && "Expected an overloaded operator");
4336 break;
4337
Douglas Gregord08452f2008-11-19 15:42:04 +00004338 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00004339 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00004340 goto UnaryStar;
4341 else
4342 goto BinaryStar;
4343 break;
4344
4345 case OO_Plus: // '+' is either unary or binary
4346 if (NumArgs == 1)
4347 goto UnaryPlus;
4348 else
4349 goto BinaryPlus;
4350 break;
4351
4352 case OO_Minus: // '-' is either unary or binary
4353 if (NumArgs == 1)
4354 goto UnaryMinus;
4355 else
4356 goto BinaryMinus;
4357 break;
4358
4359 case OO_Amp: // '&' is either unary or binary
4360 if (NumArgs == 1)
4361 goto UnaryAmp;
4362 else
4363 goto BinaryAmp;
4364
4365 case OO_PlusPlus:
4366 case OO_MinusMinus:
4367 // C++ [over.built]p3:
4368 //
4369 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4370 // is either volatile or empty, there exist candidate operator
4371 // functions of the form
4372 //
4373 // VQ T& operator++(VQ T&);
4374 // T operator++(VQ T&, int);
4375 //
4376 // C++ [over.built]p4:
4377 //
4378 // For every pair (T, VQ), where T is an arithmetic type other
4379 // than bool, and VQ is either volatile or empty, there exist
4380 // candidate operator functions of the form
4381 //
4382 // VQ T& operator--(VQ T&);
4383 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00004384 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004385 Arith < NumArithmeticTypes; ++Arith) {
4386 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00004387 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004388 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00004389
4390 // Non-volatile version.
4391 if (NumArgs == 1)
4392 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4393 else
4394 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004395 // heuristic to reduce number of builtin candidates in the set.
4396 // Add volatile version only if there are conversions to a volatile type.
4397 if (VisibleTypeConversionsQuals.hasVolatile()) {
4398 // Volatile version
4399 ParamTypes[0]
4400 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4401 if (NumArgs == 1)
4402 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4403 else
4404 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4405 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004406 }
4407
4408 // C++ [over.built]p5:
4409 //
4410 // For every pair (T, VQ), where T is a cv-qualified or
4411 // cv-unqualified object type, and VQ is either volatile or
4412 // empty, there exist candidate operator functions of the form
4413 //
4414 // T*VQ& operator++(T*VQ&);
4415 // T*VQ& operator--(T*VQ&);
4416 // T* operator++(T*VQ&, int);
4417 // T* operator--(T*VQ&, int);
4418 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4419 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4420 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004421 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00004422 continue;
4423
Mike Stump11289f42009-09-09 15:08:12 +00004424 QualType ParamTypes[2] = {
4425 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00004426 };
Mike Stump11289f42009-09-09 15:08:12 +00004427
Douglas Gregord08452f2008-11-19 15:42:04 +00004428 // Without volatile
4429 if (NumArgs == 1)
4430 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4431 else
4432 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4433
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004434 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4435 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004436 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00004437 ParamTypes[0]
4438 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00004439 if (NumArgs == 1)
4440 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4441 else
4442 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4443 }
4444 }
4445 break;
4446
4447 UnaryStar:
4448 // C++ [over.built]p6:
4449 // For every cv-qualified or cv-unqualified object type T, there
4450 // exist candidate operator functions of the form
4451 //
4452 // T& operator*(T*);
4453 //
4454 // C++ [over.built]p7:
4455 // For every function type T, there exist candidate operator
4456 // functions of the form
4457 // T& operator*(T*);
4458 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4459 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4460 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004461 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004462 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00004463 &ParamTy, Args, 1, CandidateSet);
4464 }
4465 break;
4466
4467 UnaryPlus:
4468 // C++ [over.built]p8:
4469 // For every type T, there exist candidate operator functions of
4470 // the form
4471 //
4472 // T* operator+(T*);
4473 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4474 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4475 QualType ParamTy = *Ptr;
4476 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4477 }
Mike Stump11289f42009-09-09 15:08:12 +00004478
Douglas Gregord08452f2008-11-19 15:42:04 +00004479 // Fall through
4480
4481 UnaryMinus:
4482 // C++ [over.built]p9:
4483 // For every promoted arithmetic type T, there exist candidate
4484 // operator functions of the form
4485 //
4486 // T operator+(T);
4487 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00004488 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004489 Arith < LastPromotedArithmeticType; ++Arith) {
4490 QualType ArithTy = ArithmeticTypes[Arith];
4491 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4492 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004493
4494 // Extension: We also add these operators for vector types.
4495 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4496 VecEnd = CandidateTypes.vector_end();
4497 Vec != VecEnd; ++Vec) {
4498 QualType VecTy = *Vec;
4499 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4500 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004501 break;
4502
4503 case OO_Tilde:
4504 // C++ [over.built]p10:
4505 // For every promoted integral type T, there exist candidate
4506 // operator functions of the form
4507 //
4508 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00004509 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004510 Int < LastPromotedIntegralType; ++Int) {
4511 QualType IntTy = ArithmeticTypes[Int];
4512 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4513 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004514
4515 // Extension: We also add this operator for vector types.
4516 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4517 VecEnd = CandidateTypes.vector_end();
4518 Vec != VecEnd; ++Vec) {
4519 QualType VecTy = *Vec;
4520 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4521 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004522 break;
4523
Douglas Gregora11693b2008-11-12 17:17:38 +00004524 case OO_New:
4525 case OO_Delete:
4526 case OO_Array_New:
4527 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00004528 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00004529 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00004530 break;
4531
4532 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00004533 UnaryAmp:
4534 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00004535 // C++ [over.match.oper]p3:
4536 // -- For the operator ',', the unary operator '&', or the
4537 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00004538 break;
4539
Douglas Gregor84605ae2009-08-24 13:43:27 +00004540 case OO_EqualEqual:
4541 case OO_ExclaimEqual:
4542 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00004543 // For every pointer to member type T, there exist candidate operator
4544 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00004545 //
4546 // bool operator==(T,T);
4547 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00004548 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00004549 MemPtr = CandidateTypes.member_pointer_begin(),
4550 MemPtrEnd = CandidateTypes.member_pointer_end();
4551 MemPtr != MemPtrEnd;
4552 ++MemPtr) {
4553 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4554 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4555 }
Mike Stump11289f42009-09-09 15:08:12 +00004556
Douglas Gregor84605ae2009-08-24 13:43:27 +00004557 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004558
Douglas Gregora11693b2008-11-12 17:17:38 +00004559 case OO_Less:
4560 case OO_Greater:
4561 case OO_LessEqual:
4562 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004563 // C++ [over.built]p15:
4564 //
4565 // For every pointer or enumeration type T, there exist
4566 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004567 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004568 // bool operator<(T, T);
4569 // bool operator>(T, T);
4570 // bool operator<=(T, T);
4571 // bool operator>=(T, T);
4572 // bool operator==(T, T);
4573 // bool operator!=(T, T);
4574 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4575 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4576 QualType ParamTypes[2] = { *Ptr, *Ptr };
4577 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4578 }
Mike Stump11289f42009-09-09 15:08:12 +00004579 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00004580 = CandidateTypes.enumeration_begin();
4581 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4582 QualType ParamTypes[2] = { *Enum, *Enum };
4583 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4584 }
4585
4586 // Fall through.
4587 isComparison = true;
4588
Douglas Gregord08452f2008-11-19 15:42:04 +00004589 BinaryPlus:
4590 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00004591 if (!isComparison) {
4592 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4593
4594 // C++ [over.built]p13:
4595 //
4596 // For every cv-qualified or cv-unqualified object type T
4597 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004598 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004599 // T* operator+(T*, ptrdiff_t);
4600 // T& operator[](T*, ptrdiff_t); [BELOW]
4601 // T* operator-(T*, ptrdiff_t);
4602 // T* operator+(ptrdiff_t, T*);
4603 // T& operator[](ptrdiff_t, T*); [BELOW]
4604 //
4605 // C++ [over.built]p14:
4606 //
4607 // For every T, where T is a pointer to object type, there
4608 // exist candidate operator functions of the form
4609 //
4610 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00004611 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00004612 = CandidateTypes.pointer_begin();
4613 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4614 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4615
4616 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4617 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4618
4619 if (Op == OO_Plus) {
4620 // T* operator+(ptrdiff_t, T*);
4621 ParamTypes[0] = ParamTypes[1];
4622 ParamTypes[1] = *Ptr;
4623 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4624 } else {
4625 // ptrdiff_t operator-(T, T);
4626 ParamTypes[1] = *Ptr;
4627 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4628 Args, 2, CandidateSet);
4629 }
4630 }
4631 }
4632 // Fall through
4633
Douglas Gregora11693b2008-11-12 17:17:38 +00004634 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00004635 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00004636 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00004637 // C++ [over.built]p12:
4638 //
4639 // For every pair of promoted arithmetic types L and R, there
4640 // exist candidate operator functions of the form
4641 //
4642 // LR operator*(L, R);
4643 // LR operator/(L, R);
4644 // LR operator+(L, R);
4645 // LR operator-(L, R);
4646 // bool operator<(L, R);
4647 // bool operator>(L, R);
4648 // bool operator<=(L, R);
4649 // bool operator>=(L, R);
4650 // bool operator==(L, R);
4651 // bool operator!=(L, R);
4652 //
4653 // where LR is the result of the usual arithmetic conversions
4654 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004655 //
4656 // C++ [over.built]p24:
4657 //
4658 // For every pair of promoted arithmetic types L and R, there exist
4659 // candidate operator functions of the form
4660 //
4661 // LR operator?(bool, L, R);
4662 //
4663 // where LR is the result of the usual arithmetic conversions
4664 // between types L and R.
4665 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004666 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004667 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004668 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004669 Right < LastPromotedArithmeticType; ++Right) {
4670 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004671 QualType Result
4672 = isComparison
4673 ? Context.BoolTy
4674 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004675 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4676 }
4677 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004678
4679 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
4680 // conditional operator for vector types.
4681 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4682 Vec1End = CandidateTypes.vector_end();
4683 Vec1 != Vec1End; ++Vec1)
4684 for (BuiltinCandidateTypeSet::iterator
4685 Vec2 = CandidateTypes.vector_begin(),
4686 Vec2End = CandidateTypes.vector_end();
4687 Vec2 != Vec2End; ++Vec2) {
4688 QualType LandR[2] = { *Vec1, *Vec2 };
4689 QualType Result;
4690 if (isComparison)
4691 Result = Context.BoolTy;
4692 else {
4693 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
4694 Result = *Vec1;
4695 else
4696 Result = *Vec2;
4697 }
4698
4699 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4700 }
4701
Douglas Gregora11693b2008-11-12 17:17:38 +00004702 break;
4703
4704 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00004705 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00004706 case OO_Caret:
4707 case OO_Pipe:
4708 case OO_LessLess:
4709 case OO_GreaterGreater:
4710 // C++ [over.built]p17:
4711 //
4712 // For every pair of promoted integral types L and R, there
4713 // exist candidate operator functions of the form
4714 //
4715 // LR operator%(L, R);
4716 // LR operator&(L, R);
4717 // LR operator^(L, R);
4718 // LR operator|(L, R);
4719 // L operator<<(L, R);
4720 // L operator>>(L, R);
4721 //
4722 // where LR is the result of the usual arithmetic conversions
4723 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00004724 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004725 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004726 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004727 Right < LastPromotedIntegralType; ++Right) {
4728 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4729 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4730 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004731 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004732 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4733 }
4734 }
4735 break;
4736
4737 case OO_Equal:
4738 // C++ [over.built]p20:
4739 //
4740 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00004741 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00004742 // empty, there exist candidate operator functions of the form
4743 //
4744 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004745 for (BuiltinCandidateTypeSet::iterator
4746 Enum = CandidateTypes.enumeration_begin(),
4747 EnumEnd = CandidateTypes.enumeration_end();
4748 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00004749 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004750 CandidateSet);
4751 for (BuiltinCandidateTypeSet::iterator
4752 MemPtr = CandidateTypes.member_pointer_begin(),
4753 MemPtrEnd = CandidateTypes.member_pointer_end();
4754 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00004755 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004756 CandidateSet);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004757
4758 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00004759
4760 case OO_PlusEqual:
4761 case OO_MinusEqual:
4762 // C++ [over.built]p19:
4763 //
4764 // For every pair (T, VQ), where T is any type and VQ is either
4765 // volatile or empty, there exist candidate operator functions
4766 // of the form
4767 //
4768 // T*VQ& operator=(T*VQ&, T*);
4769 //
4770 // C++ [over.built]p21:
4771 //
4772 // For every pair (T, VQ), where T is a cv-qualified or
4773 // cv-unqualified object type and VQ is either volatile or
4774 // empty, there exist candidate operator functions of the form
4775 //
4776 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4777 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4778 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4779 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4780 QualType ParamTypes[2];
4781 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4782
4783 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004784 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004785 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4786 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004787
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004788 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4789 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004790 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00004791 ParamTypes[0]
4792 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00004793 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4794 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00004795 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004796 }
4797 // Fall through.
4798
4799 case OO_StarEqual:
4800 case OO_SlashEqual:
4801 // C++ [over.built]p18:
4802 //
4803 // For every triple (L, VQ, R), where L is an arithmetic type,
4804 // VQ is either volatile or empty, and R is a promoted
4805 // arithmetic type, there exist candidate operator functions of
4806 // the form
4807 //
4808 // VQ L& operator=(VQ L&, R);
4809 // VQ L& operator*=(VQ L&, R);
4810 // VQ L& operator/=(VQ L&, R);
4811 // VQ L& operator+=(VQ L&, R);
4812 // VQ L& operator-=(VQ L&, R);
4813 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004814 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004815 Right < LastPromotedArithmeticType; ++Right) {
4816 QualType ParamTypes[2];
4817 ParamTypes[1] = ArithmeticTypes[Right];
4818
4819 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004820 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004821 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4822 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004823
4824 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004825 if (VisibleTypeConversionsQuals.hasVolatile()) {
4826 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4827 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4828 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4829 /*IsAssigmentOperator=*/Op == OO_Equal);
4830 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004831 }
4832 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004833
4834 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
4835 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4836 Vec1End = CandidateTypes.vector_end();
4837 Vec1 != Vec1End; ++Vec1)
4838 for (BuiltinCandidateTypeSet::iterator
4839 Vec2 = CandidateTypes.vector_begin(),
4840 Vec2End = CandidateTypes.vector_end();
4841 Vec2 != Vec2End; ++Vec2) {
4842 QualType ParamTypes[2];
4843 ParamTypes[1] = *Vec2;
4844 // Add this built-in operator as a candidate (VQ is empty).
4845 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
4846 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4847 /*IsAssigmentOperator=*/Op == OO_Equal);
4848
4849 // Add this built-in operator as a candidate (VQ is 'volatile').
4850 if (VisibleTypeConversionsQuals.hasVolatile()) {
4851 ParamTypes[0] = Context.getVolatileType(*Vec1);
4852 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4853 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4854 /*IsAssigmentOperator=*/Op == OO_Equal);
4855 }
4856 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004857 break;
4858
4859 case OO_PercentEqual:
4860 case OO_LessLessEqual:
4861 case OO_GreaterGreaterEqual:
4862 case OO_AmpEqual:
4863 case OO_CaretEqual:
4864 case OO_PipeEqual:
4865 // C++ [over.built]p22:
4866 //
4867 // For every triple (L, VQ, R), where L is an integral type, VQ
4868 // is either volatile or empty, and R is a promoted integral
4869 // type, there exist candidate operator functions of the form
4870 //
4871 // VQ L& operator%=(VQ L&, R);
4872 // VQ L& operator<<=(VQ L&, R);
4873 // VQ L& operator>>=(VQ L&, R);
4874 // VQ L& operator&=(VQ L&, R);
4875 // VQ L& operator^=(VQ L&, R);
4876 // VQ L& operator|=(VQ L&, R);
4877 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004878 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004879 Right < LastPromotedIntegralType; ++Right) {
4880 QualType ParamTypes[2];
4881 ParamTypes[1] = ArithmeticTypes[Right];
4882
4883 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004884 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004885 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00004886 if (VisibleTypeConversionsQuals.hasVolatile()) {
4887 // Add this built-in operator as a candidate (VQ is 'volatile').
4888 ParamTypes[0] = ArithmeticTypes[Left];
4889 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4890 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4891 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4892 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004893 }
4894 }
4895 break;
4896
Douglas Gregord08452f2008-11-19 15:42:04 +00004897 case OO_Exclaim: {
4898 // C++ [over.operator]p23:
4899 //
4900 // There also exist candidate operator functions of the form
4901 //
Mike Stump11289f42009-09-09 15:08:12 +00004902 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00004903 // bool operator&&(bool, bool); [BELOW]
4904 // bool operator||(bool, bool); [BELOW]
4905 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00004906 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4907 /*IsAssignmentOperator=*/false,
4908 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004909 break;
4910 }
4911
Douglas Gregora11693b2008-11-12 17:17:38 +00004912 case OO_AmpAmp:
4913 case OO_PipePipe: {
4914 // C++ [over.operator]p23:
4915 //
4916 // There also exist candidate operator functions of the form
4917 //
Douglas Gregord08452f2008-11-19 15:42:04 +00004918 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00004919 // bool operator&&(bool, bool);
4920 // bool operator||(bool, bool);
4921 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00004922 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4923 /*IsAssignmentOperator=*/false,
4924 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00004925 break;
4926 }
4927
4928 case OO_Subscript:
4929 // C++ [over.built]p13:
4930 //
4931 // For every cv-qualified or cv-unqualified object type T there
4932 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004933 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004934 // T* operator+(T*, ptrdiff_t); [ABOVE]
4935 // T& operator[](T*, ptrdiff_t);
4936 // T* operator-(T*, ptrdiff_t); [ABOVE]
4937 // T* operator+(ptrdiff_t, T*); [ABOVE]
4938 // T& operator[](ptrdiff_t, T*);
4939 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4940 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4941 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004942 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004943 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00004944
4945 // T& operator[](T*, ptrdiff_t)
4946 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4947
4948 // T& operator[](ptrdiff_t, T*);
4949 ParamTypes[0] = ParamTypes[1];
4950 ParamTypes[1] = *Ptr;
4951 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004952 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004953 break;
4954
4955 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004956 // C++ [over.built]p11:
4957 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4958 // C1 is the same type as C2 or is a derived class of C2, T is an object
4959 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4960 // there exist candidate operator functions of the form
4961 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4962 // where CV12 is the union of CV1 and CV2.
4963 {
4964 for (BuiltinCandidateTypeSet::iterator Ptr =
4965 CandidateTypes.pointer_begin();
4966 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4967 QualType C1Ty = (*Ptr);
4968 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004969 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004970 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004971 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004972 if (!isa<RecordType>(C1))
4973 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004974 // heuristic to reduce number of builtin candidates in the set.
4975 // Add volatile/restrict version only if there are conversions to a
4976 // volatile/restrict type.
4977 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4978 continue;
4979 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4980 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004981 }
4982 for (BuiltinCandidateTypeSet::iterator
4983 MemPtr = CandidateTypes.member_pointer_begin(),
4984 MemPtrEnd = CandidateTypes.member_pointer_end();
4985 MemPtr != MemPtrEnd; ++MemPtr) {
4986 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4987 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00004988 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004989 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4990 break;
4991 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4992 // build CV12 T&
4993 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004994 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4995 T.isVolatileQualified())
4996 continue;
4997 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4998 T.isRestrictQualified())
4999 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005000 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005001 QualType ResultTy = Context.getLValueReferenceType(T);
5002 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5003 }
5004 }
5005 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005006 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005007
5008 case OO_Conditional:
5009 // Note that we don't consider the first argument, since it has been
5010 // contextually converted to bool long ago. The candidates below are
5011 // therefore added as binary.
5012 //
5013 // C++ [over.built]p24:
5014 // For every type T, where T is a pointer or pointer-to-member type,
5015 // there exist candidate operator functions of the form
5016 //
5017 // T operator?(bool, T, T);
5018 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00005019 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
5020 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
5021 QualType ParamTypes[2] = { *Ptr, *Ptr };
5022 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5023 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005024 for (BuiltinCandidateTypeSet::iterator Ptr =
5025 CandidateTypes.member_pointer_begin(),
5026 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
5027 QualType ParamTypes[2] = { *Ptr, *Ptr };
5028 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5029 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005030 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00005031 }
5032}
5033
Douglas Gregore254f902009-02-04 00:32:51 +00005034/// \brief Add function candidates found via argument-dependent lookup
5035/// to the set of overloading candidates.
5036///
5037/// This routine performs argument-dependent name lookup based on the
5038/// given function name (which may also be an operator name) and adds
5039/// all of the overload candidates found by ADL to the overload
5040/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00005041void
Douglas Gregore254f902009-02-04 00:32:51 +00005042Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00005043 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00005044 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00005045 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005046 OverloadCandidateSet& CandidateSet,
5047 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00005048 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00005049
John McCall91f61fc2010-01-26 06:04:06 +00005050 // FIXME: This approach for uniquing ADL results (and removing
5051 // redundant candidates from the set) relies on pointer-equality,
5052 // which means we need to key off the canonical decl. However,
5053 // always going back to the canonical decl might not get us the
5054 // right set of default arguments. What default arguments are
5055 // we supposed to consider on ADL candidates, anyway?
5056
Douglas Gregorcabea402009-09-22 15:41:20 +00005057 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00005058 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00005059
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005060 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005061 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5062 CandEnd = CandidateSet.end();
5063 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00005064 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00005065 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00005066 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00005067 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00005068 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005069
5070 // For each of the ADL candidates we found, add it to the overload
5071 // set.
John McCall8fe68082010-01-26 07:16:45 +00005072 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00005073 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00005074 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00005075 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00005076 continue;
5077
John McCalla0296f72010-03-19 07:35:19 +00005078 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005079 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005080 } else
John McCall4c4c1df2010-01-26 03:27:55 +00005081 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00005082 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00005083 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00005084 }
Douglas Gregore254f902009-02-04 00:32:51 +00005085}
5086
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005087/// isBetterOverloadCandidate - Determines whether the first overload
5088/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00005089bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005090Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCallbc077cf2010-02-08 23:07:23 +00005091 const OverloadCandidate& Cand2,
5092 SourceLocation Loc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005093 // Define viable functions to be better candidates than non-viable
5094 // functions.
5095 if (!Cand2.Viable)
5096 return Cand1.Viable;
5097 else if (!Cand1.Viable)
5098 return false;
5099
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005100 // C++ [over.match.best]p1:
5101 //
5102 // -- if F is a static member function, ICS1(F) is defined such
5103 // that ICS1(F) is neither better nor worse than ICS1(G) for
5104 // any function G, and, symmetrically, ICS1(G) is neither
5105 // better nor worse than ICS1(F).
5106 unsigned StartArg = 0;
5107 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5108 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005109
Douglas Gregord3cb3562009-07-07 23:38:56 +00005110 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005111 // A viable function F1 is defined to be a better function than another
5112 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00005113 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005114 unsigned NumArgs = Cand1.Conversions.size();
5115 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5116 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005117 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005118 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
5119 Cand2.Conversions[ArgIdx])) {
5120 case ImplicitConversionSequence::Better:
5121 // Cand1 has a better conversion sequence.
5122 HasBetterConversion = true;
5123 break;
5124
5125 case ImplicitConversionSequence::Worse:
5126 // Cand1 can't be better than Cand2.
5127 return false;
5128
5129 case ImplicitConversionSequence::Indistinguishable:
5130 // Do nothing.
5131 break;
5132 }
5133 }
5134
Mike Stump11289f42009-09-09 15:08:12 +00005135 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00005136 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005137 if (HasBetterConversion)
5138 return true;
5139
Mike Stump11289f42009-09-09 15:08:12 +00005140 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00005141 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00005142 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00005143 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5144 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005145
5146 // -- F1 and F2 are function template specializations, and the function
5147 // template for F1 is more specialized than the template for F2
5148 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00005149 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00005150 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5151 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00005152 if (FunctionTemplateDecl *BetterTemplate
5153 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5154 Cand2.Function->getPrimaryTemplate(),
John McCallbc077cf2010-02-08 23:07:23 +00005155 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00005156 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5157 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00005158 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005159
Douglas Gregora1f013e2008-11-07 22:36:19 +00005160 // -- the context is an initialization by user-defined conversion
5161 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5162 // from the return type of F1 to the destination type (i.e.,
5163 // the type of the entity being initialized) is a better
5164 // conversion sequence than the standard conversion sequence
5165 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00005166 if (Cand1.Function && Cand2.Function &&
5167 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00005168 isa<CXXConversionDecl>(Cand2.Function)) {
5169 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
5170 Cand2.FinalConversion)) {
5171 case ImplicitConversionSequence::Better:
5172 // Cand1 has a better conversion sequence.
5173 return true;
5174
5175 case ImplicitConversionSequence::Worse:
5176 // Cand1 can't be better than Cand2.
5177 return false;
5178
5179 case ImplicitConversionSequence::Indistinguishable:
5180 // Do nothing
5181 break;
5182 }
5183 }
5184
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005185 return false;
5186}
5187
Mike Stump11289f42009-09-09 15:08:12 +00005188/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005189/// within an overload candidate set.
5190///
5191/// \param CandidateSet the set of candidate functions.
5192///
5193/// \param Loc the location of the function name (or operator symbol) for
5194/// which overload resolution occurs.
5195///
Mike Stump11289f42009-09-09 15:08:12 +00005196/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005197/// function, Best points to the candidate function found.
5198///
5199/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005200OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
5201 SourceLocation Loc,
5202 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005203 // Find the best viable function.
5204 Best = CandidateSet.end();
5205 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5206 Cand != CandidateSet.end(); ++Cand) {
5207 if (Cand->Viable) {
John McCallbc077cf2010-02-08 23:07:23 +00005208 if (Best == CandidateSet.end() ||
5209 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005210 Best = Cand;
5211 }
5212 }
5213
5214 // If we didn't find any viable functions, abort.
5215 if (Best == CandidateSet.end())
5216 return OR_No_Viable_Function;
5217
5218 // Make sure that this function is better than every other viable
5219 // function. If not, we have an ambiguity.
5220 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5221 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00005222 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005223 Cand != Best &&
John McCallbc077cf2010-02-08 23:07:23 +00005224 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005225 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005226 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005227 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005228 }
Mike Stump11289f42009-09-09 15:08:12 +00005229
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005230 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00005231 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005232 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005233 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00005234 return OR_Deleted;
5235
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005236 // C++ [basic.def.odr]p2:
5237 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00005238 // when referred to from a potentially-evaluated expression. [Note: this
5239 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005240 // (clause 13), user-defined conversions (12.3.2), allocation function for
5241 // placement new (5.3.4), as well as non-default initialization (8.5).
5242 if (Best->Function)
5243 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005244 return OR_Success;
5245}
5246
John McCall53262c92010-01-12 02:15:36 +00005247namespace {
5248
5249enum OverloadCandidateKind {
5250 oc_function,
5251 oc_method,
5252 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005253 oc_function_template,
5254 oc_method_template,
5255 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00005256 oc_implicit_default_constructor,
5257 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005258 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00005259};
5260
John McCalle1ac8d12010-01-13 00:25:19 +00005261OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5262 FunctionDecl *Fn,
5263 std::string &Description) {
5264 bool isTemplate = false;
5265
5266 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5267 isTemplate = true;
5268 Description = S.getTemplateArgumentBindingsText(
5269 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5270 }
John McCallfd0b2f82010-01-06 09:43:14 +00005271
5272 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00005273 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005274 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005275
John McCall53262c92010-01-12 02:15:36 +00005276 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5277 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005278 }
5279
5280 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5281 // This actually gets spelled 'candidate function' for now, but
5282 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00005283 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005284 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00005285
5286 assert(Meth->isCopyAssignment()
5287 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00005288 return oc_implicit_copy_assignment;
5289 }
5290
John McCalle1ac8d12010-01-13 00:25:19 +00005291 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00005292}
5293
5294} // end anonymous namespace
5295
5296// Notes the location of an overload candidate.
5297void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00005298 std::string FnDesc;
5299 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5300 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5301 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00005302}
5303
John McCall0d1da222010-01-12 00:44:57 +00005304/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5305/// "lead" diagnostic; it will be given two arguments, the source and
5306/// target types of the conversion.
5307void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
5308 SourceLocation CaretLoc,
5309 const PartialDiagnostic &PDiag) {
5310 Diag(CaretLoc, PDiag)
5311 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
5312 for (AmbiguousConversionSequence::const_iterator
5313 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
5314 NoteOverloadCandidate(*I);
5315 }
John McCall12f97bc2010-01-08 04:41:39 +00005316}
5317
John McCall0d1da222010-01-12 00:44:57 +00005318namespace {
5319
John McCall6a61b522010-01-13 09:16:55 +00005320void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5321 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5322 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00005323 assert(Cand->Function && "for now, candidate must be a function");
5324 FunctionDecl *Fn = Cand->Function;
5325
5326 // There's a conversion slot for the object argument if this is a
5327 // non-constructor method. Note that 'I' corresponds the
5328 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00005329 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00005330 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00005331 if (I == 0)
5332 isObjectArgument = true;
5333 else
5334 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00005335 }
5336
John McCalle1ac8d12010-01-13 00:25:19 +00005337 std::string FnDesc;
5338 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5339
John McCall6a61b522010-01-13 09:16:55 +00005340 Expr *FromExpr = Conv.Bad.FromExpr;
5341 QualType FromTy = Conv.Bad.getFromType();
5342 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00005343
John McCallfb7ad0f2010-02-02 02:42:52 +00005344 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00005345 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00005346 Expr *E = FromExpr->IgnoreParens();
5347 if (isa<UnaryOperator>(E))
5348 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00005349 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00005350
5351 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5352 << (unsigned) FnKind << FnDesc
5353 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5354 << ToTy << Name << I+1;
5355 return;
5356 }
5357
John McCall6d174642010-01-23 08:10:49 +00005358 // Do some hand-waving analysis to see if the non-viability is due
5359 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00005360 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5361 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5362 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5363 CToTy = RT->getPointeeType();
5364 else {
5365 // TODO: detect and diagnose the full richness of const mismatches.
5366 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5367 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5368 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5369 }
5370
5371 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5372 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5373 // It is dumb that we have to do this here.
5374 while (isa<ArrayType>(CFromTy))
5375 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5376 while (isa<ArrayType>(CToTy))
5377 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5378
5379 Qualifiers FromQs = CFromTy.getQualifiers();
5380 Qualifiers ToQs = CToTy.getQualifiers();
5381
5382 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5383 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5384 << (unsigned) FnKind << FnDesc
5385 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5386 << FromTy
5387 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5388 << (unsigned) isObjectArgument << I+1;
5389 return;
5390 }
5391
5392 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5393 assert(CVR && "unexpected qualifiers mismatch");
5394
5395 if (isObjectArgument) {
5396 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5397 << (unsigned) FnKind << FnDesc
5398 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5399 << FromTy << (CVR - 1);
5400 } else {
5401 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5402 << (unsigned) FnKind << FnDesc
5403 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5404 << FromTy << (CVR - 1) << I+1;
5405 }
5406 return;
5407 }
5408
John McCall6d174642010-01-23 08:10:49 +00005409 // Diagnose references or pointers to incomplete types differently,
5410 // since it's far from impossible that the incompleteness triggered
5411 // the failure.
5412 QualType TempFromTy = FromTy.getNonReferenceType();
5413 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5414 TempFromTy = PTy->getPointeeType();
5415 if (TempFromTy->isIncompleteType()) {
5416 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5417 << (unsigned) FnKind << FnDesc
5418 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5419 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5420 return;
5421 }
5422
John McCall47000992010-01-14 03:28:57 +00005423 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00005424 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5425 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00005426 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00005427 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00005428}
5429
5430void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5431 unsigned NumFormalArgs) {
5432 // TODO: treat calls to a missing default constructor as a special case
5433
5434 FunctionDecl *Fn = Cand->Function;
5435 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5436
5437 unsigned MinParams = Fn->getMinRequiredArguments();
5438
5439 // at least / at most / exactly
Douglas Gregor02eb4832010-05-08 18:13:28 +00005440 // FIXME: variadic templates "at most" should account for parameter packs
John McCall6a61b522010-01-13 09:16:55 +00005441 unsigned mode, modeCount;
5442 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005443 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5444 (Cand->FailureKind == ovl_fail_bad_deduction &&
5445 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCall6a61b522010-01-13 09:16:55 +00005446 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5447 mode = 0; // "at least"
5448 else
5449 mode = 2; // "exactly"
5450 modeCount = MinParams;
5451 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005452 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5453 (Cand->FailureKind == ovl_fail_bad_deduction &&
5454 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00005455 if (MinParams != FnTy->getNumArgs())
5456 mode = 1; // "at most"
5457 else
5458 mode = 2; // "exactly"
5459 modeCount = FnTy->getNumArgs();
5460 }
5461
5462 std::string Description;
5463 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5464
5465 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregor02eb4832010-05-08 18:13:28 +00005466 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5467 << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00005468}
5469
John McCall8b9ed552010-02-01 18:53:26 +00005470/// Diagnose a failed template-argument deduction.
5471void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5472 Expr **Args, unsigned NumArgs) {
5473 FunctionDecl *Fn = Cand->Function; // pattern
5474
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005475 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005476 NamedDecl *ParamD;
5477 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5478 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5479 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00005480 switch (Cand->DeductionFailure.Result) {
5481 case Sema::TDK_Success:
5482 llvm_unreachable("TDK_success while diagnosing bad deduction");
5483
5484 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00005485 assert(ParamD && "no parameter found for incomplete deduction result");
5486 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5487 << ParamD->getDeclName();
5488 return;
5489 }
5490
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005491 case Sema::TDK_Inconsistent:
5492 case Sema::TDK_InconsistentQuals: {
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005493 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005494 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005495 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005496 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005497 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005498 which = 1;
5499 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005500 which = 2;
5501 }
5502
5503 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5504 << which << ParamD->getDeclName()
5505 << *Cand->DeductionFailure.getFirstArg()
5506 << *Cand->DeductionFailure.getSecondArg();
5507 return;
5508 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00005509
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005510 case Sema::TDK_InvalidExplicitArguments:
5511 assert(ParamD && "no parameter found for invalid explicit arguments");
5512 if (ParamD->getDeclName())
5513 S.Diag(Fn->getLocation(),
5514 diag::note_ovl_candidate_explicit_arg_mismatch_named)
5515 << ParamD->getDeclName();
5516 else {
5517 int index = 0;
5518 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5519 index = TTP->getIndex();
5520 else if (NonTypeTemplateParmDecl *NTTP
5521 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5522 index = NTTP->getIndex();
5523 else
5524 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
5525 S.Diag(Fn->getLocation(),
5526 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
5527 << (index + 1);
5528 }
5529 return;
5530
Douglas Gregor02eb4832010-05-08 18:13:28 +00005531 case Sema::TDK_TooManyArguments:
5532 case Sema::TDK_TooFewArguments:
5533 DiagnoseArityMismatch(S, Cand, NumArgs);
5534 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00005535
5536 case Sema::TDK_InstantiationDepth:
5537 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
5538 return;
5539
5540 case Sema::TDK_SubstitutionFailure: {
5541 std::string ArgString;
5542 if (TemplateArgumentList *Args
5543 = Cand->DeductionFailure.getTemplateArgumentList())
5544 ArgString = S.getTemplateArgumentBindingsText(
5545 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
5546 *Args);
5547 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
5548 << ArgString;
5549 return;
5550 }
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005551
John McCall8b9ed552010-02-01 18:53:26 +00005552 // TODO: diagnose these individually, then kill off
5553 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00005554 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00005555 case Sema::TDK_FailedOverloadResolution:
5556 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
5557 return;
5558 }
5559}
5560
5561/// Generates a 'note' diagnostic for an overload candidate. We've
5562/// already generated a primary error at the call site.
5563///
5564/// It really does need to be a single diagnostic with its caret
5565/// pointed at the candidate declaration. Yes, this creates some
5566/// major challenges of technical writing. Yes, this makes pointing
5567/// out problems with specific arguments quite awkward. It's still
5568/// better than generating twenty screens of text for every failed
5569/// overload.
5570///
5571/// It would be great to be able to express per-candidate problems
5572/// more richly for those diagnostic clients that cared, but we'd
5573/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00005574void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
5575 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00005576 FunctionDecl *Fn = Cand->Function;
5577
John McCall12f97bc2010-01-08 04:41:39 +00005578 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00005579 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00005580 std::string FnDesc;
5581 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00005582
5583 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00005584 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00005585 return;
John McCall12f97bc2010-01-08 04:41:39 +00005586 }
5587
John McCalle1ac8d12010-01-13 00:25:19 +00005588 // We don't really have anything else to say about viable candidates.
5589 if (Cand->Viable) {
5590 S.NoteOverloadCandidate(Fn);
5591 return;
5592 }
John McCall0d1da222010-01-12 00:44:57 +00005593
John McCall6a61b522010-01-13 09:16:55 +00005594 switch (Cand->FailureKind) {
5595 case ovl_fail_too_many_arguments:
5596 case ovl_fail_too_few_arguments:
5597 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00005598
John McCall6a61b522010-01-13 09:16:55 +00005599 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00005600 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5601
John McCallfe796dd2010-01-23 05:17:32 +00005602 case ovl_fail_trivial_conversion:
5603 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005604 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00005605 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005606
John McCall65eb8792010-02-25 01:37:24 +00005607 case ovl_fail_bad_conversion: {
5608 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5609 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00005610 if (Cand->Conversions[I].isBad())
5611 return DiagnoseBadConversion(S, Cand, I);
5612
5613 // FIXME: this currently happens when we're called from SemaInit
5614 // when user-conversion overload fails. Figure out how to handle
5615 // those conditions and diagnose them well.
5616 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005617 }
John McCall65eb8792010-02-25 01:37:24 +00005618 }
John McCalld3224162010-01-08 00:58:21 +00005619}
5620
5621void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5622 // Desugar the type of the surrogate down to a function type,
5623 // retaining as many typedefs as possible while still showing
5624 // the function type (and, therefore, its parameter types).
5625 QualType FnType = Cand->Surrogate->getConversionType();
5626 bool isLValueReference = false;
5627 bool isRValueReference = false;
5628 bool isPointer = false;
5629 if (const LValueReferenceType *FnTypeRef =
5630 FnType->getAs<LValueReferenceType>()) {
5631 FnType = FnTypeRef->getPointeeType();
5632 isLValueReference = true;
5633 } else if (const RValueReferenceType *FnTypeRef =
5634 FnType->getAs<RValueReferenceType>()) {
5635 FnType = FnTypeRef->getPointeeType();
5636 isRValueReference = true;
5637 }
5638 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5639 FnType = FnTypePtr->getPointeeType();
5640 isPointer = true;
5641 }
5642 // Desugar down to a function type.
5643 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5644 // Reconstruct the pointer/reference as appropriate.
5645 if (isPointer) FnType = S.Context.getPointerType(FnType);
5646 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5647 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5648
5649 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5650 << FnType;
5651}
5652
5653void NoteBuiltinOperatorCandidate(Sema &S,
5654 const char *Opc,
5655 SourceLocation OpLoc,
5656 OverloadCandidate *Cand) {
5657 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5658 std::string TypeStr("operator");
5659 TypeStr += Opc;
5660 TypeStr += "(";
5661 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5662 if (Cand->Conversions.size() == 1) {
5663 TypeStr += ")";
5664 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5665 } else {
5666 TypeStr += ", ";
5667 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5668 TypeStr += ")";
5669 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5670 }
5671}
5672
5673void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5674 OverloadCandidate *Cand) {
5675 unsigned NoOperands = Cand->Conversions.size();
5676 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5677 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00005678 if (ICS.isBad()) break; // all meaningless after first invalid
5679 if (!ICS.isAmbiguous()) continue;
5680
5681 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00005682 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00005683 }
5684}
5685
John McCall3712d9e2010-01-15 23:32:50 +00005686SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5687 if (Cand->Function)
5688 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00005689 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00005690 return Cand->Surrogate->getLocation();
5691 return SourceLocation();
5692}
5693
John McCallad2587a2010-01-12 00:48:53 +00005694struct CompareOverloadCandidatesForDisplay {
5695 Sema &S;
5696 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00005697
5698 bool operator()(const OverloadCandidate *L,
5699 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00005700 // Fast-path this check.
5701 if (L == R) return false;
5702
John McCall12f97bc2010-01-08 04:41:39 +00005703 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00005704 if (L->Viable) {
5705 if (!R->Viable) return true;
5706
5707 // TODO: introduce a tri-valued comparison for overload
5708 // candidates. Would be more worthwhile if we had a sort
5709 // that could exploit it.
John McCallbc077cf2010-02-08 23:07:23 +00005710 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5711 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00005712 } else if (R->Viable)
5713 return false;
John McCall12f97bc2010-01-08 04:41:39 +00005714
John McCall3712d9e2010-01-15 23:32:50 +00005715 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00005716
John McCall3712d9e2010-01-15 23:32:50 +00005717 // Criteria by which we can sort non-viable candidates:
5718 if (!L->Viable) {
5719 // 1. Arity mismatches come after other candidates.
5720 if (L->FailureKind == ovl_fail_too_many_arguments ||
5721 L->FailureKind == ovl_fail_too_few_arguments)
5722 return false;
5723 if (R->FailureKind == ovl_fail_too_many_arguments ||
5724 R->FailureKind == ovl_fail_too_few_arguments)
5725 return true;
John McCall12f97bc2010-01-08 04:41:39 +00005726
John McCallfe796dd2010-01-23 05:17:32 +00005727 // 2. Bad conversions come first and are ordered by the number
5728 // of bad conversions and quality of good conversions.
5729 if (L->FailureKind == ovl_fail_bad_conversion) {
5730 if (R->FailureKind != ovl_fail_bad_conversion)
5731 return true;
5732
5733 // If there's any ordering between the defined conversions...
5734 // FIXME: this might not be transitive.
5735 assert(L->Conversions.size() == R->Conversions.size());
5736
5737 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00005738 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5739 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCallfe796dd2010-01-23 05:17:32 +00005740 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5741 R->Conversions[I])) {
5742 case ImplicitConversionSequence::Better:
5743 leftBetter++;
5744 break;
5745
5746 case ImplicitConversionSequence::Worse:
5747 leftBetter--;
5748 break;
5749
5750 case ImplicitConversionSequence::Indistinguishable:
5751 break;
5752 }
5753 }
5754 if (leftBetter > 0) return true;
5755 if (leftBetter < 0) return false;
5756
5757 } else if (R->FailureKind == ovl_fail_bad_conversion)
5758 return false;
5759
John McCall3712d9e2010-01-15 23:32:50 +00005760 // TODO: others?
5761 }
5762
5763 // Sort everything else by location.
5764 SourceLocation LLoc = GetLocationForCandidate(L);
5765 SourceLocation RLoc = GetLocationForCandidate(R);
5766
5767 // Put candidates without locations (e.g. builtins) at the end.
5768 if (LLoc.isInvalid()) return false;
5769 if (RLoc.isInvalid()) return true;
5770
5771 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00005772 }
5773};
5774
John McCallfe796dd2010-01-23 05:17:32 +00005775/// CompleteNonViableCandidate - Normally, overload resolution only
5776/// computes up to the first
5777void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5778 Expr **Args, unsigned NumArgs) {
5779 assert(!Cand->Viable);
5780
5781 // Don't do anything on failures other than bad conversion.
5782 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5783
5784 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00005785 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00005786 unsigned ConvCount = Cand->Conversions.size();
5787 while (true) {
5788 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5789 ConvIdx++;
5790 if (Cand->Conversions[ConvIdx - 1].isBad())
5791 break;
5792 }
5793
5794 if (ConvIdx == ConvCount)
5795 return;
5796
John McCall65eb8792010-02-25 01:37:24 +00005797 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
5798 "remaining conversion is initialized?");
5799
Douglas Gregoradc7a702010-04-16 17:45:54 +00005800 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00005801 // operation somehow.
5802 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00005803
5804 const FunctionProtoType* Proto;
5805 unsigned ArgIdx = ConvIdx;
5806
5807 if (Cand->IsSurrogate) {
5808 QualType ConvType
5809 = Cand->Surrogate->getConversionType().getNonReferenceType();
5810 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5811 ConvType = ConvPtrType->getPointeeType();
5812 Proto = ConvType->getAs<FunctionProtoType>();
5813 ArgIdx--;
5814 } else if (Cand->Function) {
5815 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
5816 if (isa<CXXMethodDecl>(Cand->Function) &&
5817 !isa<CXXConstructorDecl>(Cand->Function))
5818 ArgIdx--;
5819 } else {
5820 // Builtin binary operator with a bad first conversion.
5821 assert(ConvCount <= 3);
5822 for (; ConvIdx != ConvCount; ++ConvIdx)
5823 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005824 = TryCopyInitialization(S, Args[ConvIdx],
5825 Cand->BuiltinTypes.ParamTypes[ConvIdx],
5826 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005827 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00005828 return;
5829 }
5830
5831 // Fill in the rest of the conversions.
5832 unsigned NumArgsInProto = Proto->getNumArgs();
5833 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
5834 if (ArgIdx < NumArgsInProto)
5835 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005836 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
5837 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005838 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00005839 else
5840 Cand->Conversions[ConvIdx].setEllipsis();
5841 }
5842}
5843
John McCalld3224162010-01-08 00:58:21 +00005844} // end anonymous namespace
5845
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005846/// PrintOverloadCandidates - When overload resolution fails, prints
5847/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00005848/// set.
Mike Stump11289f42009-09-09 15:08:12 +00005849void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005850Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00005851 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00005852 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005853 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00005854 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00005855 // Sort the candidates by viability and position. Sorting directly would
5856 // be prohibitive, so we make a set of pointers and sort those.
5857 llvm::SmallVector<OverloadCandidate*, 32> Cands;
5858 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
5859 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5860 LastCand = CandidateSet.end();
John McCallfe796dd2010-01-23 05:17:32 +00005861 Cand != LastCand; ++Cand) {
5862 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00005863 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00005864 else if (OCD == OCD_AllCandidates) {
5865 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00005866 if (Cand->Function || Cand->IsSurrogate)
5867 Cands.push_back(Cand);
5868 // Otherwise, this a non-viable builtin candidate. We do not, in general,
5869 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00005870 }
5871 }
5872
John McCallad2587a2010-01-12 00:48:53 +00005873 std::sort(Cands.begin(), Cands.end(),
5874 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00005875
John McCall0d1da222010-01-12 00:44:57 +00005876 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00005877
John McCall12f97bc2010-01-08 04:41:39 +00005878 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00005879 const Diagnostic::OverloadsShown ShowOverloads = Diags.getShowOverloads();
5880 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00005881 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
5882 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00005883
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00005884 // Set an arbitrary limit on the number of candidate functions we'll spam
5885 // the user with. FIXME: This limit should depend on details of the
5886 // candidate list.
5887 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
5888 break;
5889 }
5890 ++CandsShown;
5891
John McCalld3224162010-01-08 00:58:21 +00005892 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00005893 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00005894 else if (Cand->IsSurrogate)
5895 NoteSurrogateCandidate(*this, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00005896 else {
5897 assert(Cand->Viable &&
5898 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00005899 // Generally we only see ambiguities including viable builtin
5900 // operators if overload resolution got screwed up by an
5901 // ambiguous user-defined conversion.
5902 //
5903 // FIXME: It's quite possible for different conversions to see
5904 // different ambiguities, though.
5905 if (!ReportedAmbiguousConversions) {
5906 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
5907 ReportedAmbiguousConversions = true;
5908 }
John McCalld3224162010-01-08 00:58:21 +00005909
John McCall0d1da222010-01-12 00:44:57 +00005910 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00005911 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00005912 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005913 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00005914
5915 if (I != E)
Jeffrey Yasskin5d474d02010-06-11 06:58:43 +00005916 Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005917}
5918
John McCalla0296f72010-03-19 07:35:19 +00005919static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00005920 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00005921 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005922
John McCalla0296f72010-03-19 07:35:19 +00005923 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005924}
5925
Douglas Gregorcd695e52008-11-10 20:40:00 +00005926/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
5927/// an overloaded function (C++ [over.over]), where @p From is an
5928/// expression with overloaded function type and @p ToType is the type
5929/// we're trying to resolve to. For example:
5930///
5931/// @code
5932/// int f(double);
5933/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00005934///
Douglas Gregorcd695e52008-11-10 20:40:00 +00005935/// int (*pfd)(double) = f; // selects f(double)
5936/// @endcode
5937///
5938/// This routine returns the resulting FunctionDecl if it could be
5939/// resolved, and NULL otherwise. When @p Complain is true, this
5940/// routine will emit diagnostics if there is an error.
5941FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005942Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00005943 bool Complain,
5944 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005945 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005946 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005947 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00005948 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005949 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00005950 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005951 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005952 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005953 FunctionType = MemTypePtr->getPointeeType();
5954 IsMember = true;
5955 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005956
Douglas Gregorcd695e52008-11-10 20:40:00 +00005957 // C++ [over.over]p1:
5958 // [...] [Note: any redundant set of parentheses surrounding the
5959 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00005960 // C++ [over.over]p1:
5961 // [...] The overloaded function name can be preceded by the &
5962 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005963 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5964 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
5965 if (OvlExpr->hasExplicitTemplateArgs()) {
5966 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5967 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005968 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00005969
5970 // We expect a pointer or reference to function, or a function pointer.
5971 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
5972 if (!FunctionType->isFunctionType()) {
5973 if (Complain)
5974 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
5975 << OvlExpr->getName() << ToType;
5976
5977 return 0;
5978 }
5979
5980 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005981
Douglas Gregorcd695e52008-11-10 20:40:00 +00005982 // Look through all of the overloaded functions, searching for one
5983 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00005984 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005985 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
5986
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005987 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00005988 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5989 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005990 // Look through any using declarations to find the underlying function.
5991 NamedDecl *Fn = (*I)->getUnderlyingDecl();
5992
Douglas Gregorcd695e52008-11-10 20:40:00 +00005993 // C++ [over.over]p3:
5994 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00005995 // targets of type "pointer-to-function" or "reference-to-function."
5996 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005997 // type "pointer-to-member-function."
5998 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00005999
Mike Stump11289f42009-09-09 15:08:12 +00006000 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006001 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00006002 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006003 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00006004 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006005 // static when converting to member pointer.
6006 if (Method->isStatic() == IsMember)
6007 continue;
6008 } else if (IsMember)
6009 continue;
Mike Stump11289f42009-09-09 15:08:12 +00006010
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006011 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006012 // If the name is a function template, template argument deduction is
6013 // done (14.8.2.2), and if the argument deduction succeeds, the
6014 // resulting template argument list is used to generate a single
6015 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006016 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006017 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00006018 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006019 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00006020 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00006021 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00006022 FunctionType, Specialization, Info)) {
6023 // FIXME: make a note of the failed deduction for diagnostics.
6024 (void)Result;
6025 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006026 // FIXME: If the match isn't exact, shouldn't we just drop this as
6027 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00006028 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00006029 == Context.getCanonicalType(Specialization->getType()));
John McCalla0296f72010-03-19 07:35:19 +00006030 Matches.push_back(std::make_pair(I.getPair(),
6031 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor9b146582009-07-08 20:55:45 +00006032 }
John McCalld14a8642009-11-21 08:51:07 +00006033
6034 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00006035 }
Mike Stump11289f42009-09-09 15:08:12 +00006036
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006037 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006038 // Skip non-static functions when converting to pointer, and static
6039 // when converting to member pointer.
6040 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00006041 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00006042
6043 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00006044 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00006045 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006046 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006047 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00006048
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006049 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00006050 QualType ResultTy;
6051 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6052 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6053 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00006054 Matches.push_back(std::make_pair(I.getPair(),
6055 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006056 FoundNonTemplateFunction = true;
6057 }
Mike Stump11289f42009-09-09 15:08:12 +00006058 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006059 }
6060
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006061 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00006062 if (Matches.empty()) {
6063 if (Complain) {
6064 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6065 << OvlExpr->getName() << FunctionType;
6066 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6067 E = OvlExpr->decls_end();
6068 I != E; ++I)
6069 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6070 NoteOverloadCandidate(F);
6071 }
6072
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006073 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00006074 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006075 FunctionDecl *Result = Matches[0].second;
John McCall16df1e52010-03-30 21:47:33 +00006076 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006077 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCall58cc69d2010-01-27 01:50:18 +00006078 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00006079 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006080 return Result;
6081 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006082
6083 // C++ [over.over]p4:
6084 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00006085 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006086 // [...] and any given function template specialization F1 is
6087 // eliminated if the set contains a second function template
6088 // specialization whose function template is more specialized
6089 // than the function template of F1 according to the partial
6090 // ordering rules of 14.5.5.2.
6091
6092 // The algorithm specified above is quadratic. We instead use a
6093 // two-pass algorithm (similar to the one used to identify the
6094 // best viable function in an overload set) that identifies the
6095 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00006096
6097 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6098 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6099 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00006100
6101 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00006102 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006103 TPOC_Other, From->getLocStart(),
6104 PDiag(),
6105 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006106 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00006107 PDiag(diag::note_ovl_candidate)
6108 << (unsigned) oc_function_template);
John McCalla0296f72010-03-19 07:35:19 +00006109 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCall58cc69d2010-01-27 01:50:18 +00006110 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00006111 FoundResult = Matches[Result - MatchesCopy.begin()].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00006112 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00006113 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall4fa0d5f2010-05-06 18:15:07 +00006114 DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc());
6115 }
John McCall58cc69d2010-01-27 01:50:18 +00006116 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006117 }
Mike Stump11289f42009-09-09 15:08:12 +00006118
Douglas Gregorfae1d712009-09-26 03:56:17 +00006119 // [...] any function template specializations in the set are
6120 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00006121 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00006122 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00006123 ++I;
6124 else {
John McCalla0296f72010-03-19 07:35:19 +00006125 Matches[I] = Matches[--N];
6126 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00006127 }
6128 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00006129
Mike Stump11289f42009-09-09 15:08:12 +00006130 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006131 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00006132 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006133 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00006134 FoundResult = Matches[0].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00006135 if (Complain) {
John McCalla0296f72010-03-19 07:35:19 +00006136 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
John McCall4fa0d5f2010-05-06 18:15:07 +00006137 DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc());
6138 }
John McCalla0296f72010-03-19 07:35:19 +00006139 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006140 }
Mike Stump11289f42009-09-09 15:08:12 +00006141
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006142 // FIXME: We should probably return the same thing that BestViableFunction
6143 // returns (even if we issue the diagnostics here).
6144 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006145 << Matches[0].second->getDeclName();
6146 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6147 NoteOverloadCandidate(Matches[I].second);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006148 return 0;
6149}
6150
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006151/// \brief Given an expression that refers to an overloaded function, try to
6152/// resolve that overloaded function expression down to a single function.
6153///
6154/// This routine can only resolve template-ids that refer to a single function
6155/// template, where that template-id refers to a single template whose template
6156/// arguments are either provided by the template-id or have defaults,
6157/// as described in C++0x [temp.arg.explicit]p3.
6158FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6159 // C++ [over.over]p1:
6160 // [...] [Note: any redundant set of parentheses surrounding the
6161 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006162 // C++ [over.over]p1:
6163 // [...] The overloaded function name can be preceded by the &
6164 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00006165
6166 if (From->getType() != Context.OverloadTy)
6167 return 0;
6168
6169 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006170
6171 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00006172 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006173 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00006174
6175 TemplateArgumentListInfo ExplicitTemplateArgs;
6176 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006177
6178 // Look through all of the overloaded functions, searching for one
6179 // whose type matches exactly.
6180 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00006181 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6182 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006183 // C++0x [temp.arg.explicit]p3:
6184 // [...] In contexts where deduction is done and fails, or in contexts
6185 // where deduction is not done, if a template argument list is
6186 // specified and it, along with any default template arguments,
6187 // identifies a single function template specialization, then the
6188 // template-id is an lvalue for the function template specialization.
6189 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
6190
6191 // C++ [over.over]p2:
6192 // If the name is a function template, template argument deduction is
6193 // done (14.8.2.2), and if the argument deduction succeeds, the
6194 // resulting template argument list is used to generate a single
6195 // function template specialization, which is added to the set of
6196 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006197 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006198 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006199 if (TemplateDeductionResult Result
6200 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6201 Specialization, Info)) {
6202 // FIXME: make a note of the failed deduction for diagnostics.
6203 (void)Result;
6204 continue;
6205 }
6206
6207 // Multiple matches; we can't resolve to a single declaration.
6208 if (Matched)
6209 return 0;
6210
6211 Matched = Specialization;
6212 }
6213
6214 return Matched;
6215}
6216
Douglas Gregorcabea402009-09-22 15:41:20 +00006217/// \brief Add a single candidate to the overload set.
6218static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00006219 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00006220 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006221 Expr **Args, unsigned NumArgs,
6222 OverloadCandidateSet &CandidateSet,
6223 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00006224 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00006225 if (isa<UsingShadowDecl>(Callee))
6226 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6227
Douglas Gregorcabea402009-09-22 15:41:20 +00006228 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00006229 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00006230 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006231 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006232 return;
John McCalld14a8642009-11-21 08:51:07 +00006233 }
6234
6235 if (FunctionTemplateDecl *FuncTemplate
6236 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00006237 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6238 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006239 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00006240 return;
6241 }
6242
6243 assert(false && "unhandled case in overloaded call candidate");
6244
6245 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00006246}
6247
6248/// \brief Add the overload candidates named by callee and/or found by argument
6249/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00006250void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00006251 Expr **Args, unsigned NumArgs,
6252 OverloadCandidateSet &CandidateSet,
6253 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00006254
6255#ifndef NDEBUG
6256 // Verify that ArgumentDependentLookup is consistent with the rules
6257 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00006258 //
Douglas Gregorcabea402009-09-22 15:41:20 +00006259 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6260 // and let Y be the lookup set produced by argument dependent
6261 // lookup (defined as follows). If X contains
6262 //
6263 // -- a declaration of a class member, or
6264 //
6265 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00006266 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00006267 //
6268 // -- a declaration that is neither a function or a function
6269 // template
6270 //
6271 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00006272
John McCall57500772009-12-16 12:17:52 +00006273 if (ULE->requiresADL()) {
6274 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6275 E = ULE->decls_end(); I != E; ++I) {
6276 assert(!(*I)->getDeclContext()->isRecord());
6277 assert(isa<UsingShadowDecl>(*I) ||
6278 !(*I)->getDeclContext()->isFunctionOrMethod());
6279 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00006280 }
6281 }
6282#endif
6283
John McCall57500772009-12-16 12:17:52 +00006284 // It would be nice to avoid this copy.
6285 TemplateArgumentListInfo TABuffer;
6286 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6287 if (ULE->hasExplicitTemplateArgs()) {
6288 ULE->copyTemplateArgumentsInto(TABuffer);
6289 ExplicitTemplateArgs = &TABuffer;
6290 }
6291
6292 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6293 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00006294 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006295 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00006296 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00006297
John McCall57500772009-12-16 12:17:52 +00006298 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00006299 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6300 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006301 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006302 CandidateSet,
6303 PartialOverloading);
6304}
John McCalld681c392009-12-16 08:11:27 +00006305
John McCall57500772009-12-16 12:17:52 +00006306static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
6307 Expr **Args, unsigned NumArgs) {
6308 Fn->Destroy(SemaRef.Context);
6309 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
6310 Args[Arg]->Destroy(SemaRef.Context);
6311 return SemaRef.ExprError();
6312}
6313
John McCalld681c392009-12-16 08:11:27 +00006314/// Attempts to recover from a call where no functions were found.
6315///
6316/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00006317static Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006318BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00006319 UnresolvedLookupExpr *ULE,
6320 SourceLocation LParenLoc,
6321 Expr **Args, unsigned NumArgs,
6322 SourceLocation *CommaLocs,
6323 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00006324
6325 CXXScopeSpec SS;
6326 if (ULE->getQualifier()) {
6327 SS.setScopeRep(ULE->getQualifier());
6328 SS.setRange(ULE->getQualifierRange());
6329 }
6330
John McCall57500772009-12-16 12:17:52 +00006331 TemplateArgumentListInfo TABuffer;
6332 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6333 if (ULE->hasExplicitTemplateArgs()) {
6334 ULE->copyTemplateArgumentsInto(TABuffer);
6335 ExplicitTemplateArgs = &TABuffer;
6336 }
6337
John McCalld681c392009-12-16 08:11:27 +00006338 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6339 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00006340 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCall57500772009-12-16 12:17:52 +00006341 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCalld681c392009-12-16 08:11:27 +00006342
John McCall57500772009-12-16 12:17:52 +00006343 assert(!R.empty() && "lookup results empty despite recovery");
6344
6345 // Build an implicit member call if appropriate. Just drop the
6346 // casts and such from the call, we don't really care.
6347 Sema::OwningExprResult NewFn = SemaRef.ExprError();
6348 if ((*R.begin())->isCXXClassMember())
6349 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6350 else if (ExplicitTemplateArgs)
6351 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6352 else
6353 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6354
6355 if (NewFn.isInvalid())
6356 return Destroy(SemaRef, Fn, Args, NumArgs);
6357
6358 Fn->Destroy(SemaRef.Context);
6359
6360 // This shouldn't cause an infinite loop because we're giving it
6361 // an expression with non-empty lookup results, which should never
6362 // end up here.
6363 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
6364 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
6365 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006366}
Douglas Gregor4038cf42010-06-08 17:35:15 +00006367
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006368/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00006369/// (which eventually refers to the declaration Func) and the call
6370/// arguments Args/NumArgs, attempt to resolve the function call down
6371/// to a specific function. If overload resolution succeeds, returns
6372/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00006373/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006374/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00006375Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006376Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00006377 SourceLocation LParenLoc,
6378 Expr **Args, unsigned NumArgs,
6379 SourceLocation *CommaLocs,
6380 SourceLocation RParenLoc) {
6381#ifndef NDEBUG
6382 if (ULE->requiresADL()) {
6383 // To do ADL, we must have found an unqualified name.
6384 assert(!ULE->getQualifier() && "qualified name with ADL");
6385
6386 // We don't perform ADL for implicit declarations of builtins.
6387 // Verify that this was correctly set up.
6388 FunctionDecl *F;
6389 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6390 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6391 F->getBuiltinID() && F->isImplicit())
6392 assert(0 && "performing ADL for builtin");
6393
6394 // We don't perform ADL in C.
6395 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6396 }
6397#endif
6398
John McCallbc077cf2010-02-08 23:07:23 +00006399 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00006400
John McCall57500772009-12-16 12:17:52 +00006401 // Add the functions denoted by the callee to the set of candidate
6402 // functions, including those from argument-dependent lookup.
6403 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00006404
6405 // If we found nothing, try to recover.
6406 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6407 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00006408 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006409 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall57500772009-12-16 12:17:52 +00006410 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006411
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006412 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006413 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00006414 case OR_Success: {
6415 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00006416 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006417 DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00006418 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00006419 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6420 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006421
6422 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00006423 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006424 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00006425 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006426 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006427 break;
6428
6429 case OR_Ambiguous:
6430 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00006431 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006432 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006433 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006434
6435 case OR_Deleted:
6436 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6437 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00006438 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00006439 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006440 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006441 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006442 }
6443
6444 // Overload resolution failed. Destroy all of the subexpressions and
6445 // return NULL.
6446 Fn->Destroy(Context);
6447 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
6448 Args[Arg]->Destroy(Context);
John McCall57500772009-12-16 12:17:52 +00006449 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006450}
6451
John McCall4c4c1df2010-01-26 03:27:55 +00006452static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00006453 return Functions.size() > 1 ||
6454 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6455}
6456
Douglas Gregor084d8552009-03-13 23:49:33 +00006457/// \brief Create a unary operation that may resolve to an overloaded
6458/// operator.
6459///
6460/// \param OpLoc The location of the operator itself (e.g., '*').
6461///
6462/// \param OpcIn The UnaryOperator::Opcode that describes this
6463/// operator.
6464///
6465/// \param Functions The set of non-member functions that will be
6466/// considered by overload resolution. The caller needs to build this
6467/// set based on the context using, e.g.,
6468/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6469/// set should not contain any member functions; those will be added
6470/// by CreateOverloadedUnaryOp().
6471///
6472/// \param input The input argument.
John McCall4c4c1df2010-01-26 03:27:55 +00006473Sema::OwningExprResult
6474Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6475 const UnresolvedSetImpl &Fns,
6476 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006477 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
6478 Expr *Input = (Expr *)input.get();
6479
6480 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6481 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6482 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6483
6484 Expr *Args[2] = { Input, 0 };
6485 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00006486
Douglas Gregor084d8552009-03-13 23:49:33 +00006487 // For post-increment and post-decrement, add the implicit '0' as
6488 // the second argument, so that we know this is a post-increment or
6489 // post-decrement.
6490 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
6491 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00006492 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00006493 SourceLocation());
6494 NumArgs = 2;
6495 }
6496
6497 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00006498 if (Fns.empty())
6499 return Owned(new (Context) UnaryOperator(input.takeAs<Expr>(),
6500 Opc,
6501 Context.DependentTy,
6502 OpLoc));
6503
John McCall58cc69d2010-01-27 01:50:18 +00006504 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006505 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006506 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006507 0, SourceRange(), OpName, OpLoc,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006508 /*ADL*/ true, IsOverloaded(Fns),
6509 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00006510 input.release();
6511 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6512 &Args[0], NumArgs,
6513 Context.DependentTy,
6514 OpLoc));
6515 }
6516
6517 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006518 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006519
6520 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006521 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00006522
6523 // Add operator candidates that are member functions.
6524 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6525
John McCall4c4c1df2010-01-26 03:27:55 +00006526 // Add candidates from ADL.
6527 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00006528 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00006529 /*ExplicitTemplateArgs*/ 0,
6530 CandidateSet);
6531
Douglas Gregor084d8552009-03-13 23:49:33 +00006532 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006533 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00006534
6535 // Perform overload resolution.
6536 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006537 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006538 case OR_Success: {
6539 // We found a built-in operator or an overloaded operator.
6540 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00006541
Douglas Gregor084d8552009-03-13 23:49:33 +00006542 if (FnDecl) {
6543 // We matched an overloaded operator. Build a call to that
6544 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00006545
Douglas Gregor084d8552009-03-13 23:49:33 +00006546 // Convert the arguments.
6547 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00006548 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006549
John McCall16df1e52010-03-30 21:47:33 +00006550 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6551 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00006552 return ExprError();
6553 } else {
6554 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00006555 OwningExprResult InputInit
6556 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006557 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00006558 SourceLocation(),
6559 move(input));
6560 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00006561 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006562
Douglas Gregore6600372009-12-23 17:40:29 +00006563 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006564 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00006565 }
6566
John McCall4fa0d5f2010-05-06 18:15:07 +00006567 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6568
Douglas Gregor084d8552009-03-13 23:49:33 +00006569 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006570 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00006571
Douglas Gregor084d8552009-03-13 23:49:33 +00006572 // Build the actual expression node.
6573 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6574 SourceLocation());
6575 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00006576
Douglas Gregor084d8552009-03-13 23:49:33 +00006577 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00006578 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006579 ExprOwningPtr<CallExpr> TheCall(this,
6580 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00006581 Args, NumArgs, ResultTy, OpLoc));
John McCall4fa0d5f2010-05-06 18:15:07 +00006582
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006583 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6584 FnDecl))
6585 return ExprError();
6586
6587 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00006588 } else {
6589 // We matched a built-in operator. Convert the arguments, then
6590 // break out so that we will build the appropriate built-in
6591 // operator node.
6592 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006593 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00006594 return ExprError();
6595
6596 break;
6597 }
6598 }
6599
6600 case OR_No_Viable_Function:
6601 // No viable function; fall through to handling this as a
6602 // built-in operator, which will produce an error message for us.
6603 break;
6604
6605 case OR_Ambiguous:
6606 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6607 << UnaryOperator::getOpcodeStr(Opc)
6608 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006609 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006610 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006611 return ExprError();
6612
6613 case OR_Deleted:
6614 Diag(OpLoc, diag::err_ovl_deleted_oper)
6615 << Best->Function->isDeleted()
6616 << UnaryOperator::getOpcodeStr(Opc)
6617 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006618 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00006619 return ExprError();
6620 }
6621
6622 // Either we found no viable overloaded operator or we matched a
6623 // built-in operator. In either case, fall through to trying to
6624 // build a built-in operation.
6625 input.release();
6626 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
6627}
6628
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006629/// \brief Create a binary operation that may resolve to an overloaded
6630/// operator.
6631///
6632/// \param OpLoc The location of the operator itself (e.g., '+').
6633///
6634/// \param OpcIn The BinaryOperator::Opcode that describes this
6635/// operator.
6636///
6637/// \param Functions The set of non-member functions that will be
6638/// considered by overload resolution. The caller needs to build this
6639/// set based on the context using, e.g.,
6640/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6641/// set should not contain any member functions; those will be added
6642/// by CreateOverloadedBinOp().
6643///
6644/// \param LHS Left-hand argument.
6645/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00006646Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006647Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006648 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00006649 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006650 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006651 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00006652 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006653
6654 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6655 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6656 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6657
6658 // If either side is type-dependent, create an appropriate dependent
6659 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00006660 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00006661 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006662 // If there are no functions to store, just build a dependent
6663 // BinaryOperator or CompoundAssignment.
6664 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
6665 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6666 Context.DependentTy, OpLoc));
6667
6668 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6669 Context.DependentTy,
6670 Context.DependentTy,
6671 Context.DependentTy,
6672 OpLoc));
6673 }
John McCall4c4c1df2010-01-26 03:27:55 +00006674
6675 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00006676 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006677 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006678 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006679 0, SourceRange(), OpName, OpLoc,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006680 /*ADL*/ true, IsOverloaded(Fns),
6681 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006682 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00006683 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006684 Context.DependentTy,
6685 OpLoc));
6686 }
6687
6688 // If this is the .* operator, which is not overloadable, just
6689 // create a built-in binary operator.
6690 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00006691 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006692
Sebastian Redl6a96bf72009-11-18 23:10:33 +00006693 // If this is the assignment operator, we only perform overload resolution
6694 // if the left-hand side is a class or enumeration type. This is actually
6695 // a hack. The standard requires that we do overload resolution between the
6696 // various built-in candidates, but as DR507 points out, this can lead to
6697 // problems. So we do it this way, which pretty much follows what GCC does.
6698 // Note that we go the traditional code path for compound assignment forms.
6699 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00006700 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006701
Douglas Gregor084d8552009-03-13 23:49:33 +00006702 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006703 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006704
6705 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006706 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006707
6708 // Add operator candidates that are member functions.
6709 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6710
John McCall4c4c1df2010-01-26 03:27:55 +00006711 // Add candidates from ADL.
6712 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6713 Args, 2,
6714 /*ExplicitTemplateArgs*/ 0,
6715 CandidateSet);
6716
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006717 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006718 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006719
6720 // Perform overload resolution.
6721 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006722 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00006723 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006724 // We found a built-in operator or an overloaded operator.
6725 FunctionDecl *FnDecl = Best->Function;
6726
6727 if (FnDecl) {
6728 // We matched an overloaded operator. Build a call to that
6729 // operator.
6730
6731 // Convert the arguments.
6732 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00006733 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00006734 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006735
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006736 OwningExprResult Arg1
6737 = PerformCopyInitialization(
6738 InitializedEntity::InitializeParameter(
6739 FnDecl->getParamDecl(0)),
6740 SourceLocation(),
6741 Owned(Args[1]));
6742 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006743 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006744
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006745 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006746 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006747 return ExprError();
6748
6749 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006750 } else {
6751 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006752 OwningExprResult Arg0
6753 = PerformCopyInitialization(
6754 InitializedEntity::InitializeParameter(
6755 FnDecl->getParamDecl(0)),
6756 SourceLocation(),
6757 Owned(Args[0]));
6758 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006759 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006760
6761 OwningExprResult Arg1
6762 = PerformCopyInitialization(
6763 InitializedEntity::InitializeParameter(
6764 FnDecl->getParamDecl(1)),
6765 SourceLocation(),
6766 Owned(Args[1]));
6767 if (Arg1.isInvalid())
6768 return ExprError();
6769 Args[0] = LHS = Arg0.takeAs<Expr>();
6770 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006771 }
6772
John McCall4fa0d5f2010-05-06 18:15:07 +00006773 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6774
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006775 // Determine the result type
6776 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00006777 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006778 ResultTy = ResultTy.getNonReferenceType();
6779
6780 // Build the actual expression node.
6781 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00006782 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006783 UsualUnaryConversions(FnExpr);
6784
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006785 ExprOwningPtr<CXXOperatorCallExpr>
6786 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6787 Args, 2, ResultTy,
6788 OpLoc));
6789
6790 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6791 FnDecl))
6792 return ExprError();
6793
6794 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006795 } else {
6796 // We matched a built-in operator. Convert the arguments, then
6797 // break out so that we will build the appropriate built-in
6798 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00006799 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006800 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00006801 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006802 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006803 return ExprError();
6804
6805 break;
6806 }
6807 }
6808
Douglas Gregor66950a32009-09-30 21:46:01 +00006809 case OR_No_Viable_Function: {
6810 // C++ [over.match.oper]p9:
6811 // If the operator is the operator , [...] and there are no
6812 // viable functions, then the operator is assumed to be the
6813 // built-in operator and interpreted according to clause 5.
6814 if (Opc == BinaryOperator::Comma)
6815 break;
6816
Sebastian Redl027de2a2009-05-21 11:50:50 +00006817 // For class as left operand for assignment or compound assigment operator
6818 // do not fall through to handling in built-in, but report that no overloaded
6819 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00006820 OwningExprResult Result = ExprError();
6821 if (Args[0]->getType()->isRecordType() &&
6822 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00006823 Diag(OpLoc, diag::err_ovl_no_viable_oper)
6824 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006825 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00006826 } else {
6827 // No viable function; try to create a built-in operation, which will
6828 // produce an error. Then, show the non-viable candidates.
6829 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00006830 }
Douglas Gregor66950a32009-09-30 21:46:01 +00006831 assert(Result.isInvalid() &&
6832 "C++ binary operator overloading is missing candidates!");
6833 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00006834 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006835 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00006836 return move(Result);
6837 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006838
6839 case OR_Ambiguous:
6840 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6841 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006842 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006843 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006844 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006845 return ExprError();
6846
6847 case OR_Deleted:
6848 Diag(OpLoc, diag::err_ovl_deleted_oper)
6849 << Best->Function->isDeleted()
6850 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006851 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006852 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006853 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00006854 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006855
Douglas Gregor66950a32009-09-30 21:46:01 +00006856 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00006857 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006858}
6859
Sebastian Redladba46e2009-10-29 20:17:01 +00006860Action::OwningExprResult
6861Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
6862 SourceLocation RLoc,
6863 ExprArg Base, ExprArg Idx) {
6864 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
6865 static_cast<Expr*>(Idx.get()) };
6866 DeclarationName OpName =
6867 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
6868
6869 // If either side is type-dependent, create an appropriate dependent
6870 // expression.
6871 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
6872
John McCall58cc69d2010-01-27 01:50:18 +00006873 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006874 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006875 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006876 0, SourceRange(), OpName, LLoc,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006877 /*ADL*/ true, /*Overloaded*/ false,
6878 UnresolvedSetIterator(),
6879 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00006880 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00006881
6882 Base.release();
6883 Idx.release();
6884 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
6885 Args, 2,
6886 Context.DependentTy,
6887 RLoc));
6888 }
6889
6890 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006891 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006892
6893 // Subscript can only be overloaded as a member function.
6894
6895 // Add operator candidates that are member functions.
6896 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6897
6898 // Add builtin operator candidates.
6899 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6900
6901 // Perform overload resolution.
6902 OverloadCandidateSet::iterator Best;
6903 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
6904 case OR_Success: {
6905 // We found a built-in operator or an overloaded operator.
6906 FunctionDecl *FnDecl = Best->Function;
6907
6908 if (FnDecl) {
6909 // We matched an overloaded operator. Build a call to that
6910 // operator.
6911
John McCalla0296f72010-03-19 07:35:19 +00006912 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006913 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00006914
Sebastian Redladba46e2009-10-29 20:17:01 +00006915 // Convert the arguments.
6916 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006917 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006918 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00006919 return ExprError();
6920
Anders Carlssona68e51e2010-01-29 18:37:50 +00006921 // Convert the arguments.
6922 OwningExprResult InputInit
6923 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6924 FnDecl->getParamDecl(0)),
6925 SourceLocation(),
6926 Owned(Args[1]));
6927 if (InputInit.isInvalid())
6928 return ExprError();
6929
6930 Args[1] = InputInit.takeAs<Expr>();
6931
Sebastian Redladba46e2009-10-29 20:17:01 +00006932 // Determine the result type
6933 QualType ResultTy
6934 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
6935 ResultTy = ResultTy.getNonReferenceType();
6936
6937 // Build the actual expression node.
6938 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6939 LLoc);
6940 UsualUnaryConversions(FnExpr);
6941
6942 Base.release();
6943 Idx.release();
6944 ExprOwningPtr<CXXOperatorCallExpr>
6945 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
6946 FnExpr, Args, 2,
6947 ResultTy, RLoc));
6948
6949 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
6950 FnDecl))
6951 return ExprError();
6952
6953 return MaybeBindToTemporary(TheCall.release());
6954 } else {
6955 // We matched a built-in operator. Convert the arguments, then
6956 // break out so that we will build the appropriate built-in
6957 // operator node.
6958 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006959 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00006960 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006961 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00006962 return ExprError();
6963
6964 break;
6965 }
6966 }
6967
6968 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00006969 if (CandidateSet.empty())
6970 Diag(LLoc, diag::err_ovl_no_oper)
6971 << Args[0]->getType() << /*subscript*/ 0
6972 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6973 else
6974 Diag(LLoc, diag::err_ovl_no_viable_subscript)
6975 << Args[0]->getType()
6976 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006977 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00006978 "[]", LLoc);
6979 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00006980 }
6981
6982 case OR_Ambiguous:
6983 Diag(LLoc, diag::err_ovl_ambiguous_oper)
6984 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006985 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00006986 "[]", LLoc);
6987 return ExprError();
6988
6989 case OR_Deleted:
6990 Diag(LLoc, diag::err_ovl_deleted_oper)
6991 << Best->Function->isDeleted() << "[]"
6992 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006993 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00006994 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006995 return ExprError();
6996 }
6997
6998 // We matched a built-in operator; build it.
6999 Base.release();
7000 Idx.release();
7001 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
7002 Owned(Args[1]), RLoc);
7003}
7004
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007005/// BuildCallToMemberFunction - Build a call to a member
7006/// function. MemExpr is the expression that refers to the member
7007/// function (and includes the object parameter), Args/NumArgs are the
7008/// arguments to the function call (not including the object
7009/// parameter). The caller needs to validate that the member
7010/// expression refers to a member function or an overloaded member
7011/// function.
John McCall2d74de92009-12-01 22:10:20 +00007012Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00007013Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7014 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007015 unsigned NumArgs, SourceLocation *CommaLocs,
7016 SourceLocation RParenLoc) {
7017 // Dig out the member expression. This holds both the object
7018 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00007019 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7020
John McCall10eae182009-11-30 22:42:35 +00007021 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007022 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00007023 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007024 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00007025 if (isa<MemberExpr>(NakedMemExpr)) {
7026 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00007027 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00007028 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007029 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00007030 } else {
7031 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007032 Qualifier = UnresExpr->getQualifier();
7033
John McCall6e9f8f62009-12-03 04:06:58 +00007034 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00007035
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007036 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00007037 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00007038
John McCall2d74de92009-12-01 22:10:20 +00007039 // FIXME: avoid copy.
7040 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7041 if (UnresExpr->hasExplicitTemplateArgs()) {
7042 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7043 TemplateArgs = &TemplateArgsBuffer;
7044 }
7045
John McCall10eae182009-11-30 22:42:35 +00007046 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7047 E = UnresExpr->decls_end(); I != E; ++I) {
7048
John McCall6e9f8f62009-12-03 04:06:58 +00007049 NamedDecl *Func = *I;
7050 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7051 if (isa<UsingShadowDecl>(Func))
7052 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7053
John McCall10eae182009-11-30 22:42:35 +00007054 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00007055 // If explicit template arguments were provided, we can't call a
7056 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00007057 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00007058 continue;
7059
John McCalla0296f72010-03-19 07:35:19 +00007060 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00007061 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007062 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007063 } else {
John McCall10eae182009-11-30 22:42:35 +00007064 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00007065 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007066 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007067 CandidateSet,
7068 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007069 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007070 }
Mike Stump11289f42009-09-09 15:08:12 +00007071
John McCall10eae182009-11-30 22:42:35 +00007072 DeclarationName DeclName = UnresExpr->getMemberName();
7073
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007074 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00007075 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007076 case OR_Success:
7077 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007078 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00007079 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007080 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007081 break;
7082
7083 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00007084 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007085 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007086 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007087 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007088 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007089 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007090
7091 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00007092 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007093 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007094 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007095 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007096 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007097
7098 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00007099 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00007100 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00007101 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007102 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007103 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007104 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007105 }
7106
John McCall16df1e52010-03-30 21:47:33 +00007107 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00007108
John McCall2d74de92009-12-01 22:10:20 +00007109 // If overload resolution picked a static member, build a
7110 // non-member call based on that function.
7111 if (Method->isStatic()) {
7112 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7113 Args, NumArgs, RParenLoc);
7114 }
7115
John McCall10eae182009-11-30 22:42:35 +00007116 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007117 }
7118
7119 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00007120 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00007121 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00007122 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007123 Method->getResultType().getNonReferenceType(),
7124 RParenLoc));
7125
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007126 // Check for a valid return type.
7127 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
7128 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00007129 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007130
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007131 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00007132 // We only need to do this if there was actually an overload; otherwise
7133 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00007134 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00007135 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00007136 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7137 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00007138 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007139 MemExpr->setBase(ObjectArg);
7140
7141 // Convert the rest of the arguments
Douglas Gregorc8be9522010-05-04 18:18:31 +00007142 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00007143 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007144 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00007145 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007146
Anders Carlssonbc4c1072009-08-16 01:56:34 +00007147 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00007148 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00007149
John McCall2d74de92009-12-01 22:10:20 +00007150 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007151}
7152
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007153/// BuildCallToObjectOfClassType - Build a call to an object of class
7154/// type (C++ [over.call.object]), which can end up invoking an
7155/// overloaded function call operator (@c operator()) or performing a
7156/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00007157Sema::ExprResult
7158Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00007159 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007160 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00007161 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007162 SourceLocation RParenLoc) {
7163 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007164 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00007165
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007166 // C++ [over.call.object]p1:
7167 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00007168 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007169 // candidate functions includes at least the function call
7170 // operators of T. The function call operators of T are obtained by
7171 // ordinary lookup of the name operator() in the context of
7172 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00007173 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00007174 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007175
7176 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007177 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007178 << Object->getSourceRange()))
7179 return true;
7180
John McCall27b18f82009-11-17 02:14:36 +00007181 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7182 LookupQualifiedName(R, Record->getDecl());
7183 R.suppressDiagnostics();
7184
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007185 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00007186 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007187 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00007188 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00007189 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00007190 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007191
Douglas Gregorab7897a2008-11-19 22:57:39 +00007192 // C++ [over.call.object]p2:
7193 // In addition, for each conversion function declared in T of the
7194 // form
7195 //
7196 // operator conversion-type-id () cv-qualifier;
7197 //
7198 // where cv-qualifier is the same cv-qualification as, or a
7199 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00007200 // denotes the type "pointer to function of (P1,...,Pn) returning
7201 // R", or the type "reference to pointer to function of
7202 // (P1,...,Pn) returning R", or the type "reference to function
7203 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00007204 // is also considered as a candidate function. Similarly,
7205 // surrogate call functions are added to the set of candidate
7206 // functions for each conversion function declared in an
7207 // accessible base class provided the function is not hidden
7208 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00007209 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00007210 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00007211 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00007212 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00007213 NamedDecl *D = *I;
7214 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7215 if (isa<UsingShadowDecl>(D))
7216 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7217
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007218 // Skip over templated conversion functions; they aren't
7219 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00007220 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007221 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007222
John McCall6e9f8f62009-12-03 04:06:58 +00007223 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00007224
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007225 // Strip the reference type (if any) and then the pointer type (if
7226 // any) to get down to what might be a function type.
7227 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7228 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7229 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007230
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007231 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00007232 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00007233 Object->getType(), Args, NumArgs,
7234 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007235 }
Mike Stump11289f42009-09-09 15:08:12 +00007236
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007237 // Perform overload resolution.
7238 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007239 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007240 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00007241 // Overload resolution succeeded; we'll build the appropriate call
7242 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007243 break;
7244
7245 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00007246 if (CandidateSet.empty())
7247 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7248 << Object->getType() << /*call*/ 1
7249 << Object->getSourceRange();
7250 else
7251 Diag(Object->getSourceRange().getBegin(),
7252 diag::err_ovl_no_viable_object_call)
7253 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007254 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007255 break;
7256
7257 case OR_Ambiguous:
7258 Diag(Object->getSourceRange().getBegin(),
7259 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007260 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007261 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007262 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007263
7264 case OR_Deleted:
7265 Diag(Object->getSourceRange().getBegin(),
7266 diag::err_ovl_deleted_object_call)
7267 << Best->Function->isDeleted()
7268 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007269 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007270 break;
Mike Stump11289f42009-09-09 15:08:12 +00007271 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007272
Douglas Gregorab7897a2008-11-19 22:57:39 +00007273 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007274 // We had an error; delete all of the subexpressions and return
7275 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00007276 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007277 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00007278 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007279 return true;
7280 }
7281
Douglas Gregorab7897a2008-11-19 22:57:39 +00007282 if (Best->Function == 0) {
7283 // Since there is no function declaration, this is one of the
7284 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00007285 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00007286 = cast<CXXConversionDecl>(
7287 Best->Conversions[0].UserDefined.ConversionFunction);
7288
John McCalla0296f72010-03-19 07:35:19 +00007289 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007290 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007291
Douglas Gregorab7897a2008-11-19 22:57:39 +00007292 // We selected one of the surrogate functions that converts the
7293 // object parameter to a function pointer. Perform the conversion
7294 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00007295
7296 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007297 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00007298 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7299 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007300
Fariborz Jahanian774cf792009-09-28 18:35:46 +00007301 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007302 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
Douglas Gregore5e775b2010-04-13 15:50:39 +00007303 CommaLocs, RParenLoc).result();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007304 }
7305
John McCalla0296f72010-03-19 07:35:19 +00007306 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007307 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007308
Douglas Gregorab7897a2008-11-19 22:57:39 +00007309 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7310 // that calls this method, using Object for the implicit object
7311 // parameter and passing along the remaining arguments.
7312 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00007313 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007314
7315 unsigned NumArgsInProto = Proto->getNumArgs();
7316 unsigned NumArgsToCheck = NumArgs;
7317
7318 // Build the full argument list for the method call (the
7319 // implicit object parameter is placed at the beginning of the
7320 // list).
7321 Expr **MethodArgs;
7322 if (NumArgs < NumArgsInProto) {
7323 NumArgsToCheck = NumArgsInProto;
7324 MethodArgs = new Expr*[NumArgsInProto + 1];
7325 } else {
7326 MethodArgs = new Expr*[NumArgs + 1];
7327 }
7328 MethodArgs[0] = Object;
7329 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7330 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00007331
7332 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00007333 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007334 UsualUnaryConversions(NewFn);
7335
7336 // Once we've built TheCall, all of the expressions are properly
7337 // owned.
7338 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00007339 ExprOwningPtr<CXXOperatorCallExpr>
7340 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007341 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00007342 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007343 delete [] MethodArgs;
7344
Anders Carlsson3d5829c2009-10-13 21:49:31 +00007345 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
7346 Method))
7347 return true;
7348
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007349 // We may have default arguments. If so, we need to allocate more
7350 // slots in the call for them.
7351 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00007352 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007353 else if (NumArgs > NumArgsInProto)
7354 NumArgsToCheck = NumArgsInProto;
7355
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007356 bool IsError = false;
7357
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007358 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007359 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007360 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007361 TheCall->setArg(0, Object);
7362
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007363
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007364 // Check the argument types.
7365 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007366 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007367 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007368 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00007369
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007370 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007371
7372 OwningExprResult InputInit
7373 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7374 Method->getParamDecl(i)),
7375 SourceLocation(), Owned(Arg));
7376
7377 IsError |= InputInit.isInvalid();
7378 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007379 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00007380 OwningExprResult DefArg
7381 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7382 if (DefArg.isInvalid()) {
7383 IsError = true;
7384 break;
7385 }
7386
7387 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007388 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007389
7390 TheCall->setArg(i + 1, Arg);
7391 }
7392
7393 // If this is a variadic call, handle args passed through "...".
7394 if (Proto->isVariadic()) {
7395 // Promote the arguments (C99 6.5.2.2p7).
7396 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7397 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00007398 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007399 TheCall->setArg(i + 1, Arg);
7400 }
7401 }
7402
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007403 if (IsError) return true;
7404
Anders Carlssonbc4c1072009-08-16 01:56:34 +00007405 if (CheckFunctionCall(Method, TheCall.get()))
7406 return true;
7407
Douglas Gregore5e775b2010-04-13 15:50:39 +00007408 return MaybeBindToTemporary(TheCall.release()).result();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007409}
7410
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007411/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00007412/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007413/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00007414Sema::OwningExprResult
7415Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
7416 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007417 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00007418
John McCallbc077cf2010-02-08 23:07:23 +00007419 SourceLocation Loc = Base->getExprLoc();
7420
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007421 // C++ [over.ref]p1:
7422 //
7423 // [...] An expression x->m is interpreted as (x.operator->())->m
7424 // for a class object x of type T if T::operator->() exists and if
7425 // the operator is selected as the best match function by the
7426 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007427 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00007428 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007429 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00007430
John McCallbc077cf2010-02-08 23:07:23 +00007431 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00007432 PDiag(diag::err_typecheck_incomplete_tag)
7433 << Base->getSourceRange()))
7434 return ExprError();
7435
John McCall27b18f82009-11-17 02:14:36 +00007436 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7437 LookupQualifiedName(R, BaseRecord->getDecl());
7438 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00007439
7440 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00007441 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007442 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007443 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00007444 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007445
7446 // Perform overload resolution.
7447 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007448 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007449 case OR_Success:
7450 // Overload resolution succeeded; we'll build the call below.
7451 break;
7452
7453 case OR_No_Viable_Function:
7454 if (CandidateSet.empty())
7455 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00007456 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007457 else
7458 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00007459 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007460 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007461 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007462
7463 case OR_Ambiguous:
7464 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00007465 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007466 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007467 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007468
7469 case OR_Deleted:
7470 Diag(OpLoc, diag::err_ovl_deleted_oper)
7471 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00007472 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007473 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007474 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007475 }
7476
John McCalla0296f72010-03-19 07:35:19 +00007477 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007478 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00007479
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007480 // Convert the object parameter.
7481 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007482 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7483 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00007484 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00007485
7486 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00007487 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007488
7489 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00007490 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7491 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007492 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007493
7494 QualType ResultTy = Method->getResultType().getNonReferenceType();
7495 ExprOwningPtr<CXXOperatorCallExpr>
7496 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7497 &Base, 1, ResultTy, OpLoc));
7498
7499 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
7500 Method))
7501 return ExprError();
7502 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007503}
7504
Douglas Gregorcd695e52008-11-10 20:40:00 +00007505/// FixOverloadedFunctionReference - E is an expression that refers to
7506/// a C++ overloaded function (possibly with some parentheses and
7507/// perhaps a '&' around it). We have resolved the overloaded function
7508/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007509/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00007510Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00007511 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00007512 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007513 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7514 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007515 if (SubExpr == PE->getSubExpr())
7516 return PE->Retain();
7517
7518 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7519 }
7520
7521 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007522 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7523 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00007524 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00007525 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00007526 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00007527 if (SubExpr == ICE->getSubExpr())
7528 return ICE->Retain();
7529
7530 return new (Context) ImplicitCastExpr(ICE->getType(),
7531 ICE->getCastKind(),
Anders Carlsson0c509ee2010-04-24 16:57:13 +00007532 SubExpr, CXXBaseSpecifierArray(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00007533 ICE->isLvalueCast());
7534 }
7535
7536 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00007537 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00007538 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007539 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7540 if (Method->isStatic()) {
7541 // Do nothing: static member functions aren't any different
7542 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00007543 } else {
John McCalle66edc12009-11-24 19:00:30 +00007544 // Fix the sub expression, which really has to be an
7545 // UnresolvedLookupExpr holding an overloaded member function
7546 // or template.
John McCall16df1e52010-03-30 21:47:33 +00007547 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7548 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00007549 if (SubExpr == UnOp->getSubExpr())
7550 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00007551
John McCalld14a8642009-11-21 08:51:07 +00007552 assert(isa<DeclRefExpr>(SubExpr)
7553 && "fixed to something other than a decl ref");
7554 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7555 && "fixed to a member ref with no nested name qualifier");
7556
7557 // We have taken the address of a pointer to member
7558 // function. Perform the computation here so that we get the
7559 // appropriate pointer to member type.
7560 QualType ClassType
7561 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7562 QualType MemPtrType
7563 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7564
7565 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7566 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007567 }
7568 }
John McCall16df1e52010-03-30 21:47:33 +00007569 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7570 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007571 if (SubExpr == UnOp->getSubExpr())
7572 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007573
Douglas Gregor51c538b2009-11-20 19:42:02 +00007574 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7575 Context.getPointerType(SubExpr->getType()),
7576 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00007577 }
John McCalld14a8642009-11-21 08:51:07 +00007578
7579 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00007580 // FIXME: avoid copy.
7581 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00007582 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00007583 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7584 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00007585 }
7586
John McCalld14a8642009-11-21 08:51:07 +00007587 return DeclRefExpr::Create(Context,
7588 ULE->getQualifier(),
7589 ULE->getQualifierRange(),
7590 Fn,
7591 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00007592 Fn->getType(),
7593 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00007594 }
7595
John McCall10eae182009-11-30 22:42:35 +00007596 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00007597 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00007598 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7599 if (MemExpr->hasExplicitTemplateArgs()) {
7600 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7601 TemplateArgs = &TemplateArgsBuffer;
7602 }
John McCall6b51f282009-11-23 01:53:49 +00007603
John McCall2d74de92009-12-01 22:10:20 +00007604 Expr *Base;
7605
7606 // If we're filling in
7607 if (MemExpr->isImplicitAccess()) {
7608 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7609 return DeclRefExpr::Create(Context,
7610 MemExpr->getQualifier(),
7611 MemExpr->getQualifierRange(),
7612 Fn,
7613 MemExpr->getMemberLoc(),
7614 Fn->getType(),
7615 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00007616 } else {
7617 SourceLocation Loc = MemExpr->getMemberLoc();
7618 if (MemExpr->getQualifier())
7619 Loc = MemExpr->getQualifierRange().getBegin();
7620 Base = new (Context) CXXThisExpr(Loc,
7621 MemExpr->getBaseType(),
7622 /*isImplicit=*/true);
7623 }
John McCall2d74de92009-12-01 22:10:20 +00007624 } else
7625 Base = MemExpr->getBase()->Retain();
7626
7627 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007628 MemExpr->isArrow(),
7629 MemExpr->getQualifier(),
7630 MemExpr->getQualifierRange(),
7631 Fn,
John McCall16df1e52010-03-30 21:47:33 +00007632 Found,
John McCall6b51f282009-11-23 01:53:49 +00007633 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00007634 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007635 Fn->getType());
7636 }
7637
Douglas Gregor51c538b2009-11-20 19:42:02 +00007638 assert(false && "Invalid reference to overloaded function");
7639 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00007640}
7641
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007642Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCalla8ae2222010-04-06 21:38:20 +00007643 DeclAccessPair Found,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007644 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00007645 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007646}
7647
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007648} // end namespace clang