blob: 8a0732702b94965620a1acdef9955adfc3d27b73 [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
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000014#include "clang/Sema/Sema.h"
15#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000017#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000018#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000023#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000025#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000027#include <algorithm>
28
29namespace clang {
30
31/// GetConversionCategory - Retrieve the implicit conversion
32/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000033ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000034GetConversionCategory(ImplicitConversionKind Kind) {
35 static const ImplicitConversionCategory
36 Category[(int)ICK_Num_Conversion_Kinds] = {
37 ICC_Identity,
38 ICC_Lvalue_Transformation,
39 ICC_Lvalue_Transformation,
40 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000041 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000042 ICC_Qualification_Adjustment,
43 ICC_Promotion,
44 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000045 ICC_Promotion,
46 ICC_Conversion,
47 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000048 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000053 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000054 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +000055 ICC_Conversion,
56 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000057 ICC_Conversion
58 };
59 return Category[(int)Kind];
60}
61
62/// GetConversionRank - Retrieve the implicit conversion rank
63/// corresponding to the given implicit conversion kind.
64ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
65 static const ImplicitConversionRank
66 Rank[(int)ICK_Num_Conversion_Kinds] = {
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Exact_Match,
70 ICR_Exact_Match,
71 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000072 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000073 ICR_Promotion,
74 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000075 ICR_Promotion,
76 ICR_Conversion,
77 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000078 ICR_Conversion,
79 ICR_Conversion,
80 ICR_Conversion,
81 ICR_Conversion,
82 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000083 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000084 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +000085 ICR_Conversion,
86 ICR_Conversion,
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +000087 ICR_Complex_Real_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +000088 };
89 return Rank[(int)Kind];
90}
91
92/// GetImplicitConversionName - Return the name of this kind of
93/// implicit conversion.
94const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +000095 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000096 "No conversion",
97 "Lvalue-to-rvalue",
98 "Array-to-pointer",
99 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000100 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000101 "Qualification",
102 "Integral promotion",
103 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000104 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000105 "Integral conversion",
106 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000107 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000108 "Floating-integral conversion",
109 "Pointer conversion",
110 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000111 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000112 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000113 "Derived-to-base conversion",
114 "Vector conversion",
115 "Vector splat",
116 "Complex-real conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000117 };
118 return Name[Kind];
119}
120
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000121/// StandardConversionSequence - Set the standard conversion
122/// sequence to the identity conversion.
123void StandardConversionSequence::setAsIdentityConversion() {
124 First = ICK_Identity;
125 Second = ICK_Identity;
126 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000127 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000128 ReferenceBinding = false;
129 DirectBinding = false;
Sebastian Redlf69a94a2009-03-29 22:46:24 +0000130 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000131 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000132}
133
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000134/// getRank - Retrieve the rank of this standard conversion sequence
135/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
136/// implicit conversions.
137ImplicitConversionRank StandardConversionSequence::getRank() const {
138 ImplicitConversionRank Rank = ICR_Exact_Match;
139 if (GetConversionRank(First) > Rank)
140 Rank = GetConversionRank(First);
141 if (GetConversionRank(Second) > Rank)
142 Rank = GetConversionRank(Second);
143 if (GetConversionRank(Third) > Rank)
144 Rank = GetConversionRank(Third);
145 return Rank;
146}
147
148/// isPointerConversionToBool - Determines whether this conversion is
149/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000150/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000151/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000152bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000153 // Note that FromType has not necessarily been transformed by the
154 // array-to-pointer or function-to-pointer implicit conversions, so
155 // check for their presence as well as checking whether FromType is
156 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000157 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000158 (getFromType()->isPointerType() ||
159 getFromType()->isObjCObjectPointerType() ||
160 getFromType()->isBlockPointerType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000161 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
162 return true;
163
164 return false;
165}
166
Douglas Gregor5c407d92008-10-23 00:40:37 +0000167/// isPointerConversionToVoidPointer - Determines whether this
168/// conversion is a conversion of a pointer to a void pointer. This is
169/// used as part of the ranking of standard conversion sequences (C++
170/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000171bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000172StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000173isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000174 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000175 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000176
177 // Note that FromType has not necessarily been transformed by the
178 // array-to-pointer implicit conversion, so check for its presence
179 // and redo the conversion to get a pointer.
180 if (First == ICK_Array_To_Pointer)
181 FromType = Context.getArrayDecayedType(FromType);
182
Douglas Gregor1aa450a2009-12-13 21:37:05 +0000183 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000184 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000185 return ToPtrType->getPointeeType()->isVoidType();
186
187 return false;
188}
189
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000190/// DebugPrint - Print this standard conversion sequence to standard
191/// error. Useful for debugging overloading issues.
192void StandardConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000193 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000194 bool PrintedSomething = false;
195 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000196 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000197 PrintedSomething = true;
198 }
199
200 if (Second != ICK_Identity) {
201 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000202 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000203 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000204 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000205
206 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000207 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000208 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000209 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000210 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000211 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000212 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000213 PrintedSomething = true;
214 }
215
216 if (Third != ICK_Identity) {
217 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000218 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000219 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000220 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000221 PrintedSomething = true;
222 }
223
224 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000225 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000226 }
227}
228
229/// DebugPrint - Print this user-defined conversion sequence to standard
230/// error. Useful for debugging overloading issues.
231void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000232 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000233 if (Before.First || Before.Second || Before.Third) {
234 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000235 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000236 }
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000237 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000238 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000239 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000240 After.DebugPrint();
241 }
242}
243
244/// DebugPrint - Print this implicit conversion sequence to standard
245/// error. Useful for debugging overloading issues.
246void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000247 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000248 switch (ConversionKind) {
249 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000250 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000251 Standard.DebugPrint();
252 break;
253 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000254 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000255 UserDefined.DebugPrint();
256 break;
257 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000258 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000259 break;
John McCall0d1da222010-01-12 00:44:57 +0000260 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000261 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000262 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000263 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000264 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000265 break;
266 }
267
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000268 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000269}
270
John McCall0d1da222010-01-12 00:44:57 +0000271void AmbiguousConversionSequence::construct() {
272 new (&conversions()) ConversionSet();
273}
274
275void AmbiguousConversionSequence::destruct() {
276 conversions().~ConversionSet();
277}
278
279void
280AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
281 FromTypePtr = O.FromTypePtr;
282 ToTypePtr = O.ToTypePtr;
283 new (&conversions()) ConversionSet(O.conversions());
284}
285
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000286namespace {
287 // Structure used by OverloadCandidate::DeductionFailureInfo to store
288 // template parameter and template argument information.
289 struct DFIParamWithArguments {
290 TemplateParameter Param;
291 TemplateArgument FirstArg;
292 TemplateArgument SecondArg;
293 };
294}
295
296/// \brief Convert from Sema's representation of template deduction information
297/// to the form used in overload-candidate information.
298OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000299static MakeDeductionFailureInfo(ASTContext &Context,
300 Sema::TemplateDeductionResult TDK,
Douglas Gregord09efd42010-05-08 20:07:26 +0000301 Sema::TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000302 OverloadCandidate::DeductionFailureInfo Result;
303 Result.Result = static_cast<unsigned>(TDK);
304 Result.Data = 0;
305 switch (TDK) {
306 case Sema::TDK_Success:
307 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000308 case Sema::TDK_TooManyArguments:
309 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000310 break;
311
312 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000313 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000314 Result.Data = Info.Param.getOpaqueValue();
315 break;
316
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000317 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000318 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000319 // FIXME: Should allocate from normal heap so that we can free this later.
320 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000321 Saved->Param = Info.Param;
322 Saved->FirstArg = Info.FirstArg;
323 Saved->SecondArg = Info.SecondArg;
324 Result.Data = Saved;
325 break;
326 }
327
328 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000329 Result.Data = Info.take();
330 break;
331
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000332 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000333 case Sema::TDK_FailedOverloadResolution:
334 break;
335 }
336
337 return Result;
338}
John McCall0d1da222010-01-12 00:44:57 +0000339
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000340void OverloadCandidate::DeductionFailureInfo::Destroy() {
341 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
342 case Sema::TDK_Success:
343 case Sema::TDK_InstantiationDepth:
344 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000345 case Sema::TDK_TooManyArguments:
346 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000347 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000348 break;
349
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000350 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000351 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000352 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000353 Data = 0;
354 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000355
356 case Sema::TDK_SubstitutionFailure:
357 // FIXME: Destroy the template arugment list?
358 Data = 0;
359 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000360
Douglas Gregor461761d2010-05-08 18:20:53 +0000361 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000362 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000363 case Sema::TDK_FailedOverloadResolution:
364 break;
365 }
366}
367
368TemplateParameter
369OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
370 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
371 case Sema::TDK_Success:
372 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000373 case Sema::TDK_TooManyArguments:
374 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000375 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000376 return TemplateParameter();
377
378 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000379 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000380 return TemplateParameter::getFromOpaqueValue(Data);
381
382 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000383 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000384 return static_cast<DFIParamWithArguments*>(Data)->Param;
385
386 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000387 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000388 case Sema::TDK_FailedOverloadResolution:
389 break;
390 }
391
392 return TemplateParameter();
393}
Douglas Gregord09efd42010-05-08 20:07:26 +0000394
395TemplateArgumentList *
396OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
397 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
398 case Sema::TDK_Success:
399 case Sema::TDK_InstantiationDepth:
400 case Sema::TDK_TooManyArguments:
401 case Sema::TDK_TooFewArguments:
402 case Sema::TDK_Incomplete:
403 case Sema::TDK_InvalidExplicitArguments:
404 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000405 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000406 return 0;
407
408 case Sema::TDK_SubstitutionFailure:
409 return static_cast<TemplateArgumentList*>(Data);
410
411 // Unhandled
412 case Sema::TDK_NonDeducedMismatch:
413 case Sema::TDK_FailedOverloadResolution:
414 break;
415 }
416
417 return 0;
418}
419
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000420const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
421 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
422 case Sema::TDK_Success:
423 case Sema::TDK_InstantiationDepth:
424 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000425 case Sema::TDK_TooManyArguments:
426 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000427 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000428 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000429 return 0;
430
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000431 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000432 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000433 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
434
Douglas Gregor461761d2010-05-08 18:20:53 +0000435 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000436 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000437 case Sema::TDK_FailedOverloadResolution:
438 break;
439 }
440
441 return 0;
442}
443
444const TemplateArgument *
445OverloadCandidate::DeductionFailureInfo::getSecondArg() {
446 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
447 case Sema::TDK_Success:
448 case Sema::TDK_InstantiationDepth:
449 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000450 case Sema::TDK_TooManyArguments:
451 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000452 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000453 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000454 return 0;
455
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000456 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000457 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000458 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
459
Douglas Gregor461761d2010-05-08 18:20:53 +0000460 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000461 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000462 case Sema::TDK_FailedOverloadResolution:
463 break;
464 }
465
466 return 0;
467}
468
469void OverloadCandidateSet::clear() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000470 inherited::clear();
471 Functions.clear();
472}
473
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000474// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000475// overload of the declarations in Old. This routine returns false if
476// New and Old cannot be overloaded, e.g., if New has the same
477// signature as some function in Old (C++ 1.3.10) or if the Old
478// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000479// it does return false, MatchedDecl will point to the decl that New
480// cannot be overloaded with. This decl may be a UsingShadowDecl on
481// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000482//
483// Example: Given the following input:
484//
485// void f(int, float); // #1
486// void f(int, int); // #2
487// int f(int, int); // #3
488//
489// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000490// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000491//
John McCall3d988d92009-12-02 08:47:38 +0000492// When we process #2, Old contains only the FunctionDecl for #1. By
493// comparing the parameter types, we see that #1 and #2 are overloaded
494// (since they have different signatures), so this routine returns
495// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000496//
John McCall3d988d92009-12-02 08:47:38 +0000497// When we process #3, Old is an overload set containing #1 and #2. We
498// compare the signatures of #3 to #1 (they're overloaded, so we do
499// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
500// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000501// signature), IsOverload returns false and MatchedDecl will be set to
502// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000503//
504// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
505// into a class by a using declaration. The rules for whether to hide
506// shadow declarations ignore some properties which otherwise figure
507// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000508Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000509Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
510 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000511 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000512 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000513 NamedDecl *OldD = *I;
514
515 bool OldIsUsingDecl = false;
516 if (isa<UsingShadowDecl>(OldD)) {
517 OldIsUsingDecl = true;
518
519 // We can always introduce two using declarations into the same
520 // context, even if they have identical signatures.
521 if (NewIsUsingDecl) continue;
522
523 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
524 }
525
526 // If either declaration was introduced by a using declaration,
527 // we'll need to use slightly different rules for matching.
528 // Essentially, these rules are the normal rules, except that
529 // function templates hide function templates with different
530 // return types or template parameter lists.
531 bool UseMemberUsingDeclRules =
532 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
533
John McCall3d988d92009-12-02 08:47:38 +0000534 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000535 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
536 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
537 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
538 continue;
539 }
540
John McCalldaa3d6b2009-12-09 03:35:25 +0000541 Match = *I;
542 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000543 }
John McCall3d988d92009-12-02 08:47:38 +0000544 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000545 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
546 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
547 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
548 continue;
549 }
550
John McCalldaa3d6b2009-12-09 03:35:25 +0000551 Match = *I;
552 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000553 }
John McCall84d87672009-12-10 09:41:52 +0000554 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
555 // We can overload with these, which can show up when doing
556 // redeclaration checks for UsingDecls.
557 assert(Old.getLookupKind() == LookupUsingDeclName);
558 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
559 // Optimistically assume that an unresolved using decl will
560 // overload; if it doesn't, we'll have to diagnose during
561 // template instantiation.
562 } else {
John McCall1f82f242009-11-18 22:49:29 +0000563 // (C++ 13p1):
564 // Only function declarations can be overloaded; object and type
565 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000566 Match = *I;
567 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000568 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000569 }
John McCall1f82f242009-11-18 22:49:29 +0000570
John McCalldaa3d6b2009-12-09 03:35:25 +0000571 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000572}
573
John McCalle9cccd82010-06-16 08:42:20 +0000574bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
575 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000576 // If both of the functions are extern "C", then they are not
577 // overloads.
578 if (Old->isExternC() && New->isExternC())
579 return false;
580
John McCall1f82f242009-11-18 22:49:29 +0000581 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
582 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
583
584 // C++ [temp.fct]p2:
585 // A function template can be overloaded with other function templates
586 // and with normal (non-template) functions.
587 if ((OldTemplate == 0) != (NewTemplate == 0))
588 return true;
589
590 // Is the function New an overload of the function Old?
591 QualType OldQType = Context.getCanonicalType(Old->getType());
592 QualType NewQType = Context.getCanonicalType(New->getType());
593
594 // Compare the signatures (C++ 1.3.10) of the two functions to
595 // determine whether they are overloads. If we find any mismatch
596 // in the signature, they are overloads.
597
598 // If either of these functions is a K&R-style function (no
599 // prototype), then we consider them to have matching signatures.
600 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
601 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
602 return false;
603
604 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
605 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
606
607 // The signature of a function includes the types of its
608 // parameters (C++ 1.3.10), which includes the presence or absence
609 // of the ellipsis; see C++ DR 357).
610 if (OldQType != NewQType &&
611 (OldType->getNumArgs() != NewType->getNumArgs() ||
612 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000613 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000614 return true;
615
616 // C++ [temp.over.link]p4:
617 // The signature of a function template consists of its function
618 // signature, its return type and its template parameter list. The names
619 // of the template parameters are significant only for establishing the
620 // relationship between the template parameters and the rest of the
621 // signature.
622 //
623 // We check the return type and template parameter lists for function
624 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000625 //
626 // However, we don't consider either of these when deciding whether
627 // a member introduced by a shadow declaration is hidden.
628 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000629 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
630 OldTemplate->getTemplateParameters(),
631 false, TPL_TemplateMatch) ||
632 OldType->getResultType() != NewType->getResultType()))
633 return true;
634
635 // If the function is a class member, its signature includes the
636 // cv-qualifiers (if any) on the function itself.
637 //
638 // As part of this, also check whether one of the member functions
639 // is static, in which case they are not overloads (C++
640 // 13.1p2). While not part of the definition of the signature,
641 // this check is important to determine whether these functions
642 // can be overloaded.
643 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
644 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
645 if (OldMethod && NewMethod &&
646 !OldMethod->isStatic() && !NewMethod->isStatic() &&
647 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
648 return true;
649
650 // The signatures match; this is not an overload.
651 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000652}
653
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000654/// TryImplicitConversion - Attempt to perform an implicit conversion
655/// from the given expression (Expr) to the given type (ToType). This
656/// function returns an implicit conversion sequence that can be used
657/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000658///
659/// void f(float f);
660/// void g(int i) { f(i); }
661///
662/// this routine would produce an implicit conversion sequence to
663/// describe the initialization of f from i, which will be a standard
664/// conversion sequence containing an lvalue-to-rvalue conversion (C++
665/// 4.1) followed by a floating-integral conversion (C++ 4.9).
666//
667/// Note that this routine only determines how the conversion can be
668/// performed; it does not actually perform the conversion. As such,
669/// it will not produce any diagnostics if no conversion is available,
670/// but will instead return an implicit conversion sequence of kind
671/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000672///
673/// If @p SuppressUserConversions, then user-defined conversions are
674/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000675/// If @p AllowExplicit, then explicit user-defined conversions are
676/// permitted.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000677ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000678Sema::TryImplicitConversion(Expr* From, QualType ToType,
679 bool SuppressUserConversions,
Douglas Gregore81335c2010-04-16 18:00:29 +0000680 bool AllowExplicit,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000681 bool InOverloadResolution) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000682 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +0000683 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000684 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000685 return ICS;
686 }
687
688 if (!getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000689 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000690 return ICS;
691 }
692
Douglas Gregor836a7e82010-08-11 02:15:33 +0000693 // C++ [over.ics.user]p4:
694 // A conversion of an expression of class type to the same class
695 // type is given Exact Match rank, and a conversion of an
696 // expression of class type to a base class of that type is
697 // given Conversion rank, in spite of the fact that a copy/move
698 // constructor (i.e., a user-defined conversion function) is
699 // called for those cases.
700 QualType FromType = From->getType();
701 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
702 (Context.hasSameUnqualifiedType(FromType, ToType) ||
703 IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000704 ICS.setStandard();
705 ICS.Standard.setAsIdentityConversion();
706 ICS.Standard.setFromType(FromType);
707 ICS.Standard.setAllToTypes(ToType);
708
709 // We don't actually check at this point whether there is a valid
710 // copy/move constructor, since overloading just assumes that it
711 // exists. When we actually perform initialization, we'll find the
712 // appropriate constructor to copy the returned object, if needed.
713 ICS.Standard.CopyConstructor = 0;
Douglas Gregor836a7e82010-08-11 02:15:33 +0000714
Douglas Gregor5ab11652010-04-17 22:01:05 +0000715 // Determine whether this is considered a derived-to-base conversion.
716 if (!Context.hasSameUnqualifiedType(FromType, ToType))
717 ICS.Standard.Second = ICK_Derived_To_Base;
Douglas Gregor836a7e82010-08-11 02:15:33 +0000718
719 return ICS;
720 }
721
722 if (SuppressUserConversions) {
723 // We're not in the case above, so there is no conversion that
724 // we can perform.
725 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor5ab11652010-04-17 22:01:05 +0000726 return ICS;
727 }
728
729 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000730 OverloadCandidateSet Conversions(From->getExprLoc());
731 OverloadingResult UserDefResult
732 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000733 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000734
735 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000736 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000737 // C++ [over.ics.user]p4:
738 // A conversion of an expression of class type to the same class
739 // type is given Exact Match rank, and a conversion of an
740 // expression of class type to a base class of that type is
741 // given Conversion rank, in spite of the fact that a copy
742 // constructor (i.e., a user-defined conversion function) is
743 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000744 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000745 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000746 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000747 = Context.getCanonicalType(From->getType().getUnqualifiedType());
748 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000749 if (Constructor->isCopyConstructor() &&
Douglas Gregor4141d5b2009-12-22 00:21:20 +0000750 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000751 // Turn this into a "standard" conversion sequence, so that it
752 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000753 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000754 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000755 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000756 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000757 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000758 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000759 ICS.Standard.Second = ICK_Derived_To_Base;
760 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000761 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000762
763 // C++ [over.best.ics]p4:
764 // However, when considering the argument of a user-defined
765 // conversion function that is a candidate by 13.3.1.3 when
766 // invoked for the copying of the temporary in the second step
767 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
768 // 13.3.1.6 in all cases, only standard conversion sequences and
769 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000770 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000771 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000772 }
John McCalle8c8cd22010-01-13 22:30:33 +0000773 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000774 ICS.setAmbiguous();
775 ICS.Ambiguous.setFromType(From->getType());
776 ICS.Ambiguous.setToType(ToType);
777 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
778 Cand != Conversions.end(); ++Cand)
779 if (Cand->Viable)
780 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000781 } else {
John McCall65eb8792010-02-25 01:37:24 +0000782 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000783 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000784
785 return ICS;
786}
787
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000788/// PerformImplicitConversion - Perform an implicit conversion of the
789/// expression From to the type ToType. Returns true if there was an
790/// error, false otherwise. The expression From is replaced with the
791/// converted expression. Flavor is the kind of conversion we're
792/// performing, used in the error message. If @p AllowExplicit,
793/// explicit user-defined conversions are permitted.
794bool
795Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
796 AssignmentAction Action, bool AllowExplicit) {
797 ImplicitConversionSequence ICS;
798 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
799}
800
801bool
802Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
803 AssignmentAction Action, bool AllowExplicit,
804 ImplicitConversionSequence& ICS) {
805 ICS = TryImplicitConversion(From, ToType,
806 /*SuppressUserConversions=*/false,
807 AllowExplicit,
808 /*InOverloadResolution=*/false);
809 return PerformImplicitConversion(From, ToType, ICS, Action);
810}
811
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000812/// \brief Determine whether the conversion from FromType to ToType is a valid
813/// conversion that strips "noreturn" off the nested function type.
814static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
815 QualType ToType, QualType &ResultTy) {
816 if (Context.hasSameUnqualifiedType(FromType, ToType))
817 return false;
818
819 // Strip the noreturn off the type we're converting from; noreturn can
820 // safely be removed.
821 FromType = Context.getNoReturnType(FromType, false);
822 if (!Context.hasSameUnqualifiedType(FromType, ToType))
823 return false;
824
825 ResultTy = FromType;
826 return true;
827}
Douglas Gregor46188682010-05-18 22:42:18 +0000828
829/// \brief Determine whether the conversion from FromType to ToType is a valid
830/// vector conversion.
831///
832/// \param ICK Will be set to the vector conversion kind, if this is a vector
833/// conversion.
834static bool IsVectorConversion(ASTContext &Context, QualType FromType,
835 QualType ToType, ImplicitConversionKind &ICK) {
836 // We need at least one of these types to be a vector type to have a vector
837 // conversion.
838 if (!ToType->isVectorType() && !FromType->isVectorType())
839 return false;
840
841 // Identical types require no conversions.
842 if (Context.hasSameUnqualifiedType(FromType, ToType))
843 return false;
844
845 // There are no conversions between extended vector types, only identity.
846 if (ToType->isExtVectorType()) {
847 // There are no conversions between extended vector types other than the
848 // identity conversion.
849 if (FromType->isExtVectorType())
850 return false;
851
852 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +0000853 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +0000854 ICK = ICK_Vector_Splat;
855 return true;
856 }
857 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000858
859 // We can perform the conversion between vector types in the following cases:
860 // 1)vector types are equivalent AltiVec and GCC vector types
861 // 2)lax vector conversions are permitted and the vector types are of the
862 // same size
863 if (ToType->isVectorType() && FromType->isVectorType()) {
864 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +0000865 (Context.getLangOptions().LaxVectorConversions &&
866 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000867 ICK = ICK_Vector_Conversion;
868 return true;
869 }
Douglas Gregor46188682010-05-18 22:42:18 +0000870 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000871
Douglas Gregor46188682010-05-18 22:42:18 +0000872 return false;
873}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000874
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000875/// IsStandardConversion - Determines whether there is a standard
876/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
877/// expression From to the type ToType. Standard conversion sequences
878/// only consider non-class types; for conversions that involve class
879/// types, use TryImplicitConversion. If a conversion exists, SCS will
880/// contain the standard conversion sequence required to perform this
881/// conversion and this routine will return true. Otherwise, this
882/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000883bool
884Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000885 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000886 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000887 QualType FromType = From->getType();
888
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000889 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000890 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000891 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000892 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000893 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000894 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000895
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000896 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000897 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000898 if (FromType->isRecordType() || ToType->isRecordType()) {
899 if (getLangOptions().CPlusPlus)
900 return false;
901
Mike Stump11289f42009-09-09 15:08:12 +0000902 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000903 }
904
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000905 // The first conversion can be an lvalue-to-rvalue conversion,
906 // array-to-pointer conversion, or function-to-pointer conversion
907 // (C++ 4p1).
908
Douglas Gregor980fb162010-04-29 18:24:40 +0000909 if (FromType == Context.OverloadTy) {
910 DeclAccessPair AccessPair;
911 if (FunctionDecl *Fn
912 = ResolveAddressOfOverloadedFunction(From, ToType, false,
913 AccessPair)) {
914 // We were able to resolve the address of the overloaded function,
915 // so we can convert to the type of that function.
916 FromType = Fn->getType();
917 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
918 if (!Method->isStatic()) {
919 Type *ClassType
920 = Context.getTypeDeclType(Method->getParent()).getTypePtr();
921 FromType = Context.getMemberPointerType(FromType, ClassType);
922 }
923 }
924
925 // If the "from" expression takes the address of the overloaded
926 // function, update the type of the resulting expression accordingly.
927 if (FromType->getAs<FunctionType>())
928 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
929 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
930 FromType = Context.getPointerType(FromType);
931
932 // Check that we've computed the proper type after overload resolution.
933 assert(Context.hasSameType(FromType,
934 FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
935 } else {
936 return false;
937 }
938 }
Mike Stump11289f42009-09-09 15:08:12 +0000939 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000940 // An lvalue (3.10) of a non-function, non-array type T can be
941 // converted to an rvalue.
942 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000943 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000944 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000945 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000946 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000947
948 // If T is a non-class type, the type of the rvalue is the
949 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000950 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
951 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000952 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000953 } else if (FromType->isArrayType()) {
954 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000955 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000956
957 // An lvalue or rvalue of type "array of N T" or "array of unknown
958 // bound of T" can be converted to an rvalue of type "pointer to
959 // T" (C++ 4.2p1).
960 FromType = Context.getArrayDecayedType(FromType);
961
962 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
963 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +0000964 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000965
966 // For the purpose of ranking in overload resolution
967 // (13.3.3.1.1), this conversion is considered an
968 // array-to-pointer conversion followed by a qualification
969 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000970 SCS.Second = ICK_Identity;
971 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000972 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000973 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000974 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000975 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
976 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000977 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000978
979 // An lvalue of function type T can be converted to an rvalue of
980 // type "pointer to T." The result is a pointer to the
981 // function. (C++ 4.3p1).
982 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000983 } else {
984 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000985 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000986 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000987 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000988
989 // The second conversion can be an integral promotion, floating
990 // point promotion, integral conversion, floating point conversion,
991 // floating-integral conversion, pointer conversion,
992 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000993 // For overloading in C, this can also be a "compatible-type"
994 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000995 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +0000996 ImplicitConversionKind SecondICK = ICK_Identity;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000997 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000998 // The unqualified versions of the types are the same: there's no
999 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001000 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +00001001 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001002 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001003 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001004 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001005 } else if (IsFloatingPointPromotion(FromType, ToType)) {
1006 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001007 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001008 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001009 } else if (IsComplexPromotion(FromType, ToType)) {
1010 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001011 SCS.Second = ICK_Complex_Promotion;
1012 FromType = ToType.getUnqualifiedType();
Douglas Gregorb90df602010-06-16 00:17:44 +00001013 } else if (FromType->isIntegralOrEnumerationType() &&
Douglas Gregor6972a622010-06-16 00:35:25 +00001014 ToType->isIntegralType(Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001015 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001016 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001017 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001018 } else if (FromType->isComplexType() && ToType->isComplexType()) {
1019 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001020 SCS.Second = ICK_Complex_Conversion;
1021 FromType = ToType.getUnqualifiedType();
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001022 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
1023 (ToType->isComplexType() && FromType->isArithmeticType())) {
1024 // Complex-real conversions (C99 6.3.1.7)
1025 SCS.Second = ICK_Complex_Real;
1026 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001027 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001028 // Floating point conversions (C++ 4.8).
1029 SCS.Second = ICK_Floating_Conversion;
1030 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001031 } else if ((FromType->isRealFloatingType() &&
Douglas Gregor6972a622010-06-16 00:35:25 +00001032 ToType->isIntegralType(Context) && !ToType->isBooleanType()) ||
Douglas Gregorb90df602010-06-16 00:17:44 +00001033 (FromType->isIntegralOrEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001034 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001035 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001036 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001037 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +00001038 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1039 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001040 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001041 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001042 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +00001043 } else if (IsMemberPointerConversion(From, FromType, ToType,
1044 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001045 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001046 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +00001047 } else if (ToType->isBooleanType() &&
1048 (FromType->isArithmeticType() ||
1049 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +00001050 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +00001051 FromType->isBlockPointerType() ||
1052 FromType->isMemberPointerType() ||
Douglas Gregora3208f92010-06-22 23:41:02 +00001053 FromType->isNullPtrType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001054 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001055 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001056 FromType = Context.BoolTy;
Douglas Gregor46188682010-05-18 22:42:18 +00001057 } else if (IsVectorConversion(Context, FromType, ToType, SecondICK)) {
1058 SCS.Second = SecondICK;
1059 FromType = ToType.getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00001060 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +00001061 Context.typesAreCompatible(ToType, FromType)) {
1062 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001063 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001064 FromType = ToType.getUnqualifiedType();
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001065 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
1066 // Treat a conversion that strips "noreturn" as an identity conversion.
1067 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001068 } else {
1069 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001070 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001071 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001072 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001073
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001074 QualType CanonFrom;
1075 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001076 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +00001077 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001078 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001079 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001080 CanonFrom = Context.getCanonicalType(FromType);
1081 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001082 } else {
1083 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001084 SCS.Third = ICK_Identity;
1085
Mike Stump11289f42009-09-09 15:08:12 +00001086 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001087 // [...] Any difference in top-level cv-qualification is
1088 // subsumed by the initialization itself and does not constitute
1089 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001090 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +00001091 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001092 if (CanonFrom.getLocalUnqualifiedType()
1093 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001094 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1095 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001096 FromType = ToType;
1097 CanonFrom = CanonTo;
1098 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001099 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001100 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001101
1102 // If we have not converted the argument type to the parameter type,
1103 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001104 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001105 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001106
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001107 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001108}
1109
1110/// IsIntegralPromotion - Determines whether the conversion from the
1111/// expression From (whose potentially-adjusted type is FromType) to
1112/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1113/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001114bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001115 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001116 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001117 if (!To) {
1118 return false;
1119 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001120
1121 // An rvalue of type char, signed char, unsigned char, short int, or
1122 // unsigned short int can be converted to an rvalue of type int if
1123 // int can represent all the values of the source type; otherwise,
1124 // the source rvalue can be converted to an rvalue of type unsigned
1125 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001126 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1127 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001128 if (// We can promote any signed, promotable integer type to an int
1129 (FromType->isSignedIntegerType() ||
1130 // We can promote any unsigned integer type whose size is
1131 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001132 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001133 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001134 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001135 }
1136
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001137 return To->getKind() == BuiltinType::UInt;
1138 }
1139
1140 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
1141 // can be converted to an rvalue of the first of the following types
1142 // that can represent all the values of its underlying type: int,
1143 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +00001144
1145 // We pre-calculate the promotion type for enum types.
1146 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
1147 if (ToType->isIntegerType())
1148 return Context.hasSameUnqualifiedType(ToType,
1149 FromEnumType->getDecl()->getPromotionType());
1150
1151 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001152 // Determine whether the type we're converting from is signed or
1153 // unsigned.
1154 bool FromIsSigned;
1155 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +00001156
1157 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1158 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001159
1160 // The types we'll try to promote to, in the appropriate
1161 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001162 QualType PromoteTypes[6] = {
1163 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001164 Context.LongTy, Context.UnsignedLongTy ,
1165 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001166 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001167 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001168 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1169 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001170 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001171 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1172 // We found the type that we can promote to. If this is the
1173 // type we wanted, we have a promotion. Otherwise, no
1174 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001175 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001176 }
1177 }
1178 }
1179
1180 // An rvalue for an integral bit-field (9.6) can be converted to an
1181 // rvalue of type int if int can represent all the values of the
1182 // bit-field; otherwise, it can be converted to unsigned int if
1183 // unsigned int can represent all the values of the bit-field. If
1184 // the bit-field is larger yet, no integral promotion applies to
1185 // it. If the bit-field has an enumerated type, it is treated as any
1186 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001187 // FIXME: We should delay checking of bit-fields until we actually perform the
1188 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001189 using llvm::APSInt;
1190 if (From)
1191 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001192 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001193 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001194 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1195 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1196 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001197
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001198 // Are we promoting to an int from a bitfield that fits in an int?
1199 if (BitWidth < ToSize ||
1200 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1201 return To->getKind() == BuiltinType::Int;
1202 }
Mike Stump11289f42009-09-09 15:08:12 +00001203
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001204 // Are we promoting to an unsigned int from an unsigned bitfield
1205 // that fits into an unsigned int?
1206 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1207 return To->getKind() == BuiltinType::UInt;
1208 }
Mike Stump11289f42009-09-09 15:08:12 +00001209
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001210 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001211 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001212 }
Mike Stump11289f42009-09-09 15:08:12 +00001213
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001214 // An rvalue of type bool can be converted to an rvalue of type int,
1215 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001216 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001217 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001218 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001219
1220 return false;
1221}
1222
1223/// IsFloatingPointPromotion - Determines whether the conversion from
1224/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1225/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001226bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001227 /// An rvalue of type float can be converted to an rvalue of type
1228 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001229 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1230 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001231 if (FromBuiltin->getKind() == BuiltinType::Float &&
1232 ToBuiltin->getKind() == BuiltinType::Double)
1233 return true;
1234
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001235 // C99 6.3.1.5p1:
1236 // When a float is promoted to double or long double, or a
1237 // double is promoted to long double [...].
1238 if (!getLangOptions().CPlusPlus &&
1239 (FromBuiltin->getKind() == BuiltinType::Float ||
1240 FromBuiltin->getKind() == BuiltinType::Double) &&
1241 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1242 return true;
1243 }
1244
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001245 return false;
1246}
1247
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001248/// \brief Determine if a conversion is a complex promotion.
1249///
1250/// A complex promotion is defined as a complex -> complex conversion
1251/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001252/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001253bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001254 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001255 if (!FromComplex)
1256 return false;
1257
John McCall9dd450b2009-09-21 23:43:11 +00001258 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001259 if (!ToComplex)
1260 return false;
1261
1262 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001263 ToComplex->getElementType()) ||
1264 IsIntegralPromotion(0, FromComplex->getElementType(),
1265 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001266}
1267
Douglas Gregor237f96c2008-11-26 23:31:11 +00001268/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1269/// the pointer type FromPtr to a pointer to type ToPointee, with the
1270/// same type qualifiers as FromPtr has on its pointee type. ToType,
1271/// if non-empty, will be a pointer to ToType that may or may not have
1272/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001273static QualType
1274BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001275 QualType ToPointee, QualType ToType,
1276 ASTContext &Context) {
1277 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1278 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001279 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001280
1281 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001282 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001283 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001284 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001285 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001286
1287 // Build a pointer to ToPointee. It has the right qualifiers
1288 // already.
1289 return Context.getPointerType(ToPointee);
1290 }
1291
1292 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +00001293 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001294 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1295 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +00001296}
1297
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001298/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1299/// the FromType, which is an objective-c pointer, to ToType, which may or may
1300/// not have the right set of qualifiers.
1301static QualType
1302BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1303 QualType ToType,
1304 ASTContext &Context) {
1305 QualType CanonFromType = Context.getCanonicalType(FromType);
1306 QualType CanonToType = Context.getCanonicalType(ToType);
1307 Qualifiers Quals = CanonFromType.getQualifiers();
1308
1309 // Exact qualifier match -> return the pointer type we're converting to.
1310 if (CanonToType.getLocalQualifiers() == Quals)
1311 return ToType;
1312
1313 // Just build a canonical type that has the right qualifiers.
1314 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1315}
1316
Mike Stump11289f42009-09-09 15:08:12 +00001317static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001318 bool InOverloadResolution,
1319 ASTContext &Context) {
1320 // Handle value-dependent integral null pointer constants correctly.
1321 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1322 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001323 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001324 return !InOverloadResolution;
1325
Douglas Gregor56751b52009-09-25 04:25:58 +00001326 return Expr->isNullPointerConstant(Context,
1327 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1328 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001329}
Mike Stump11289f42009-09-09 15:08:12 +00001330
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001331/// IsPointerConversion - Determines whether the conversion of the
1332/// expression From, which has the (possibly adjusted) type FromType,
1333/// can be converted to the type ToType via a pointer conversion (C++
1334/// 4.10). If so, returns true and places the converted type (that
1335/// might differ from ToType in its cv-qualifiers at some level) into
1336/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001337///
Douglas Gregora29dc052008-11-27 01:19:21 +00001338/// This routine also supports conversions to and from block pointers
1339/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1340/// pointers to interfaces. FIXME: Once we've determined the
1341/// appropriate overloading rules for Objective-C, we may want to
1342/// split the Objective-C checks into a different routine; however,
1343/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001344/// conversions, so for now they live here. IncompatibleObjC will be
1345/// set if the conversion is an allowed Objective-C conversion that
1346/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001347bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001348 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001349 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001350 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001351 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001352 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1353 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001354
Mike Stump11289f42009-09-09 15:08:12 +00001355 // Conversion from a null pointer constant to any Objective-C pointer type.
1356 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001357 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001358 ConvertedType = ToType;
1359 return true;
1360 }
1361
Douglas Gregor231d1c62008-11-27 00:15:41 +00001362 // Blocks: Block pointers can be converted to void*.
1363 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001364 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001365 ConvertedType = ToType;
1366 return true;
1367 }
1368 // Blocks: A null pointer constant can be converted to a block
1369 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001370 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001371 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001372 ConvertedType = ToType;
1373 return true;
1374 }
1375
Sebastian Redl576fd422009-05-10 18:38:11 +00001376 // If the left-hand-side is nullptr_t, the right side can be a null
1377 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001378 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001379 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001380 ConvertedType = ToType;
1381 return true;
1382 }
1383
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001384 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001385 if (!ToTypePtr)
1386 return false;
1387
1388 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001389 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001390 ConvertedType = ToType;
1391 return true;
1392 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001393
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001394 // Beyond this point, both types need to be pointers
1395 // , including objective-c pointers.
1396 QualType ToPointeeType = ToTypePtr->getPointeeType();
1397 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1398 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1399 ToType, Context);
1400 return true;
1401
1402 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001403 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001404 if (!FromTypePtr)
1405 return false;
1406
1407 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001408
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001409 // An rvalue of type "pointer to cv T," where T is an object type,
1410 // can be converted to an rvalue of type "pointer to cv void" (C++
1411 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001412 if (FromPointeeType->isIncompleteOrObjectType() &&
1413 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001414 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001415 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001416 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001417 return true;
1418 }
1419
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001420 // When we're overloading in C, we allow a special kind of pointer
1421 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001422 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001423 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001424 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001425 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001426 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001427 return true;
1428 }
1429
Douglas Gregor5c407d92008-10-23 00:40:37 +00001430 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001431 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001432 // An rvalue of type "pointer to cv D," where D is a class type,
1433 // can be converted to an rvalue of type "pointer to cv B," where
1434 // B is a base class (clause 10) of D. If B is an inaccessible
1435 // (clause 11) or ambiguous (10.2) base class of D, a program that
1436 // necessitates this conversion is ill-formed. The result of the
1437 // conversion is a pointer to the base class sub-object of the
1438 // derived class object. The null pointer value is converted to
1439 // the null pointer value of the destination type.
1440 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001441 // Note that we do not check for ambiguity or inaccessibility
1442 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001443 if (getLangOptions().CPlusPlus &&
1444 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001445 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001446 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001447 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001448 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001449 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001450 ToType, Context);
1451 return true;
1452 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001453
Douglas Gregora119f102008-12-19 19:13:09 +00001454 return false;
1455}
1456
1457/// isObjCPointerConversion - Determines whether this is an
1458/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1459/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001460bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001461 QualType& ConvertedType,
1462 bool &IncompatibleObjC) {
1463 if (!getLangOptions().ObjC1)
1464 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001465
Steve Naroff7cae42b2009-07-10 23:34:53 +00001466 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001467 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001468 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001469 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001470
Steve Naroff7cae42b2009-07-10 23:34:53 +00001471 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001472 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001473 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001474 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001475 ConvertedType = ToType;
1476 return true;
1477 }
1478 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001479 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001480 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001481 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001482 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001483 ConvertedType = ToType;
1484 return true;
1485 }
1486 // Objective C++: We're able to convert from a pointer to an
1487 // interface to a pointer to a different interface.
1488 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001489 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1490 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1491 if (getLangOptions().CPlusPlus && LHS && RHS &&
1492 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1493 FromObjCPtr->getPointeeType()))
1494 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001495 ConvertedType = ToType;
1496 return true;
1497 }
1498
1499 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1500 // Okay: this is some kind of implicit downcast of Objective-C
1501 // interfaces, which is permitted. However, we're going to
1502 // complain about it.
1503 IncompatibleObjC = true;
1504 ConvertedType = FromType;
1505 return true;
1506 }
Mike Stump11289f42009-09-09 15:08:12 +00001507 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001508 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001509 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001510 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001511 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001512 else if (const BlockPointerType *ToBlockPtr =
1513 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001514 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001515 // to a block pointer type.
1516 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1517 ConvertedType = ToType;
1518 return true;
1519 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001520 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001521 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001522 else if (FromType->getAs<BlockPointerType>() &&
1523 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1524 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001525 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001526 ConvertedType = ToType;
1527 return true;
1528 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001529 else
Douglas Gregora119f102008-12-19 19:13:09 +00001530 return false;
1531
Douglas Gregor033f56d2008-12-23 00:53:59 +00001532 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001533 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001534 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001535 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001536 FromPointeeType = FromBlockPtr->getPointeeType();
1537 else
Douglas Gregora119f102008-12-19 19:13:09 +00001538 return false;
1539
Douglas Gregora119f102008-12-19 19:13:09 +00001540 // If we have pointers to pointers, recursively check whether this
1541 // is an Objective-C conversion.
1542 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1543 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1544 IncompatibleObjC)) {
1545 // We always complain about this conversion.
1546 IncompatibleObjC = true;
1547 ConvertedType = ToType;
1548 return true;
1549 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001550 // Allow conversion of pointee being objective-c pointer to another one;
1551 // as in I* to id.
1552 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1553 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1554 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1555 IncompatibleObjC)) {
1556 ConvertedType = ToType;
1557 return true;
1558 }
1559
Douglas Gregor033f56d2008-12-23 00:53:59 +00001560 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001561 // differences in the argument and result types are in Objective-C
1562 // pointer conversions. If so, we permit the conversion (but
1563 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001564 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001565 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001566 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001567 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001568 if (FromFunctionType && ToFunctionType) {
1569 // If the function types are exactly the same, this isn't an
1570 // Objective-C pointer conversion.
1571 if (Context.getCanonicalType(FromPointeeType)
1572 == Context.getCanonicalType(ToPointeeType))
1573 return false;
1574
1575 // Perform the quick checks that will tell us whether these
1576 // function types are obviously different.
1577 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1578 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1579 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1580 return false;
1581
1582 bool HasObjCConversion = false;
1583 if (Context.getCanonicalType(FromFunctionType->getResultType())
1584 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1585 // Okay, the types match exactly. Nothing to do.
1586 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1587 ToFunctionType->getResultType(),
1588 ConvertedType, IncompatibleObjC)) {
1589 // Okay, we have an Objective-C pointer conversion.
1590 HasObjCConversion = true;
1591 } else {
1592 // Function types are too different. Abort.
1593 return false;
1594 }
Mike Stump11289f42009-09-09 15:08:12 +00001595
Douglas Gregora119f102008-12-19 19:13:09 +00001596 // Check argument types.
1597 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1598 ArgIdx != NumArgs; ++ArgIdx) {
1599 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1600 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1601 if (Context.getCanonicalType(FromArgType)
1602 == Context.getCanonicalType(ToArgType)) {
1603 // Okay, the types match exactly. Nothing to do.
1604 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1605 ConvertedType, IncompatibleObjC)) {
1606 // Okay, we have an Objective-C pointer conversion.
1607 HasObjCConversion = true;
1608 } else {
1609 // Argument types are too different. Abort.
1610 return false;
1611 }
1612 }
1613
1614 if (HasObjCConversion) {
1615 // We had an Objective-C conversion. Allow this pointer
1616 // conversion, but complain about it.
1617 ConvertedType = ToType;
1618 IncompatibleObjC = true;
1619 return true;
1620 }
1621 }
1622
Sebastian Redl72b597d2009-01-25 19:43:20 +00001623 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001624}
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001625
1626/// FunctionArgTypesAreEqual - This routine checks two function proto types
1627/// for equlity of their argument types. Caller has already checked that
1628/// they have same number of arguments. This routine assumes that Objective-C
1629/// pointer types which only differ in their protocol qualifiers are equal.
1630bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1631 FunctionProtoType* NewType){
1632 if (!getLangOptions().ObjC1)
1633 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1634 NewType->arg_type_begin());
1635
1636 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1637 N = NewType->arg_type_begin(),
1638 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1639 QualType ToType = (*O);
1640 QualType FromType = (*N);
1641 if (ToType != FromType) {
1642 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1643 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001644 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1645 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1646 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1647 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001648 continue;
1649 }
John McCall8b07ec22010-05-15 11:32:37 +00001650 else if (const ObjCObjectPointerType *PTTo =
1651 ToType->getAs<ObjCObjectPointerType>()) {
1652 if (const ObjCObjectPointerType *PTFr =
1653 FromType->getAs<ObjCObjectPointerType>())
1654 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1655 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001656 }
1657 return false;
1658 }
1659 }
1660 return true;
1661}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001662
Douglas Gregor39c16d42008-10-24 04:54:22 +00001663/// CheckPointerConversion - Check the pointer conversion from the
1664/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001665/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001666/// conversions for which IsPointerConversion has already returned
1667/// true. It returns true and produces a diagnostic if there was an
1668/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001669bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001670 CastExpr::CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001671 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001672 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001673 QualType FromType = From->getType();
1674
Douglas Gregor4038cf42010-06-08 17:35:15 +00001675 if (CXXBoolLiteralExpr* LitBool
1676 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
1677 if (LitBool->getValue() == false)
1678 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1679 << ToType;
1680
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001681 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1682 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001683 QualType FromPointeeType = FromPtrType->getPointeeType(),
1684 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001685
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001686 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1687 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001688 // We must have a derived-to-base conversion. Check an
1689 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001690 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1691 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001692 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001693 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001694 return true;
1695
1696 // The conversion was successful.
1697 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001698 }
1699 }
Mike Stump11289f42009-09-09 15:08:12 +00001700 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001701 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001702 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001703 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001704 // Objective-C++ conversions are always okay.
1705 // FIXME: We should have a different class of conversions for the
1706 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001707 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001708 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001709
Steve Naroff7cae42b2009-07-10 23:34:53 +00001710 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001711 return false;
1712}
1713
Sebastian Redl72b597d2009-01-25 19:43:20 +00001714/// IsMemberPointerConversion - Determines whether the conversion of the
1715/// expression From, which has the (possibly adjusted) type FromType, can be
1716/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1717/// If so, returns true and places the converted type (that might differ from
1718/// ToType in its cv-qualifiers at some level) into ConvertedType.
1719bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001720 QualType ToType,
1721 bool InOverloadResolution,
1722 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001723 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001724 if (!ToTypePtr)
1725 return false;
1726
1727 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001728 if (From->isNullPointerConstant(Context,
1729 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1730 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001731 ConvertedType = ToType;
1732 return true;
1733 }
1734
1735 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001736 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001737 if (!FromTypePtr)
1738 return false;
1739
1740 // A pointer to member of B can be converted to a pointer to member of D,
1741 // where D is derived from B (C++ 4.11p2).
1742 QualType FromClass(FromTypePtr->getClass(), 0);
1743 QualType ToClass(ToTypePtr->getClass(), 0);
1744 // FIXME: What happens when these are dependent? Is this function even called?
1745
1746 if (IsDerivedFrom(ToClass, FromClass)) {
1747 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1748 ToClass.getTypePtr());
1749 return true;
1750 }
1751
1752 return false;
1753}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001754
Sebastian Redl72b597d2009-01-25 19:43:20 +00001755/// CheckMemberPointerConversion - Check the member pointer conversion from the
1756/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001757/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001758/// for which IsMemberPointerConversion has already returned true. It returns
1759/// true and produces a diagnostic if there was an error, or returns false
1760/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001761bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001762 CastExpr::CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001763 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001764 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001765 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001766 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001767 if (!FromPtrType) {
1768 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001769 assert(From->isNullPointerConstant(Context,
1770 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001771 "Expr must be null pointer constant!");
1772 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001773 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001774 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001775
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001776 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001777 assert(ToPtrType && "No member pointer cast has a target type "
1778 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001779
Sebastian Redled8f2002009-01-28 18:33:18 +00001780 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1781 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001782
Sebastian Redled8f2002009-01-28 18:33:18 +00001783 // FIXME: What about dependent types?
1784 assert(FromClass->isRecordType() && "Pointer into non-class.");
1785 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001786
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001787 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001788 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001789 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1790 assert(DerivationOkay &&
1791 "Should not have been called if derivation isn't OK.");
1792 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001793
Sebastian Redled8f2002009-01-28 18:33:18 +00001794 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1795 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001796 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1797 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1798 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1799 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001800 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001801
Douglas Gregor89ee6822009-02-28 01:32:25 +00001802 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001803 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1804 << FromClass << ToClass << QualType(VBase, 0)
1805 << From->getSourceRange();
1806 return true;
1807 }
1808
John McCall5b0829a2010-02-10 09:31:12 +00001809 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001810 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1811 Paths.front(),
1812 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001813
Anders Carlssond7923c62009-08-22 23:33:40 +00001814 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001815 BuildBasePathArray(Paths, BasePath);
Anders Carlssond7923c62009-08-22 23:33:40 +00001816 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001817 return false;
1818}
1819
Douglas Gregor9a657932008-10-21 23:43:52 +00001820/// IsQualificationConversion - Determines whether the conversion from
1821/// an rvalue of type FromType to ToType is a qualification conversion
1822/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001823bool
1824Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001825 FromType = Context.getCanonicalType(FromType);
1826 ToType = Context.getCanonicalType(ToType);
1827
1828 // If FromType and ToType are the same type, this is not a
1829 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001830 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001831 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001832
Douglas Gregor9a657932008-10-21 23:43:52 +00001833 // (C++ 4.4p4):
1834 // A conversion can add cv-qualifiers at levels other than the first
1835 // in multi-level pointers, subject to the following rules: [...]
1836 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001837 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001838 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001839 // Within each iteration of the loop, we check the qualifiers to
1840 // determine if this still looks like a qualification
1841 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001842 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001843 // until there are no more pointers or pointers-to-members left to
1844 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001845 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001846
1847 // -- for every j > 0, if const is in cv 1,j then const is in cv
1848 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001849 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001850 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001851
Douglas Gregor9a657932008-10-21 23:43:52 +00001852 // -- if the cv 1,j and cv 2,j are different, then const is in
1853 // every cv for 0 < k < j.
1854 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001855 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001856 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001857
Douglas Gregor9a657932008-10-21 23:43:52 +00001858 // Keep track of whether all prior cv-qualifiers in the "to" type
1859 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001860 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001861 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001862 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001863
1864 // We are left with FromType and ToType being the pointee types
1865 // after unwrapping the original FromType and ToType the same number
1866 // of types. If we unwrapped any pointers, and if FromType and
1867 // ToType have the same unqualified type (since we checked
1868 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001869 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001870}
1871
Douglas Gregor576e98c2009-01-30 23:27:23 +00001872/// Determines whether there is a user-defined conversion sequence
1873/// (C++ [over.ics.user]) that converts expression From to the type
1874/// ToType. If such a conversion exists, User will contain the
1875/// user-defined conversion sequence that performs such a conversion
1876/// and this routine will return true. Otherwise, this routine returns
1877/// false and User is unspecified.
1878///
Douglas Gregor576e98c2009-01-30 23:27:23 +00001879/// \param AllowExplicit true if the conversion should consider C++0x
1880/// "explicit" conversion functions as well as non-explicit conversion
1881/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001882OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1883 UserDefinedConversionSequence& User,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001884 OverloadCandidateSet& CandidateSet,
1885 bool AllowExplicit) {
1886 // Whether we will only visit constructors.
1887 bool ConstructorsOnly = false;
1888
1889 // If the type we are conversion to is a class type, enumerate its
1890 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001891 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001892 // C++ [over.match.ctor]p1:
1893 // When objects of class type are direct-initialized (8.5), or
1894 // copy-initialized from an expression of the same or a
1895 // derived class type (8.5), overload resolution selects the
1896 // constructor. [...] For copy-initialization, the candidate
1897 // functions are all the converting constructors (12.3.1) of
1898 // that class. The argument list is the expression-list within
1899 // the parentheses of the initializer.
1900 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1901 (From->getType()->getAs<RecordType>() &&
1902 IsDerivedFrom(From->getType(), ToType)))
1903 ConstructorsOnly = true;
1904
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001905 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1906 // We're not going to find any constructors.
1907 } else if (CXXRecordDecl *ToRecordDecl
1908 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001909 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregor52b72822010-07-02 23:12:18 +00001910 for (llvm::tie(Con, ConEnd) = LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001911 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00001912 NamedDecl *D = *Con;
1913 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1914
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001915 // Find the constructor (which may be a template).
1916 CXXConstructorDecl *Constructor = 0;
1917 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00001918 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001919 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001920 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001921 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1922 else
John McCalla0296f72010-03-19 07:35:19 +00001923 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001924
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001925 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001926 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001927 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00001928 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001929 /*ExplicitArgs*/ 0,
John McCall6b51f282009-11-23 01:53:49 +00001930 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001931 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001932 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001933 // Allow one user-defined conversion when user specifies a
1934 // From->ToType conversion via an static cast (c-style, etc).
John McCalla0296f72010-03-19 07:35:19 +00001935 AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001936 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001937 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001938 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001939 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001940 }
1941 }
1942
Douglas Gregor5ab11652010-04-17 22:01:05 +00001943 // Enumerate conversion functions, if we're allowed to.
1944 if (ConstructorsOnly) {
Mike Stump11289f42009-09-09 15:08:12 +00001945 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
Douglas Gregor5ab11652010-04-17 22:01:05 +00001946 PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001947 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001948 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00001949 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001950 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001951 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1952 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00001953 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001954 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001955 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001956 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00001957 DeclAccessPair FoundDecl = I.getPair();
1958 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00001959 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1960 if (isa<UsingShadowDecl>(D))
1961 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1962
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001963 CXXConversionDecl *Conv;
1964 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00001965 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1966 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001967 else
John McCallda4458e2010-03-31 01:36:47 +00001968 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001969
1970 if (AllowExplicit || !Conv->isExplicit()) {
1971 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00001972 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001973 ActingContext, From, ToType,
1974 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001975 else
John McCalla0296f72010-03-19 07:35:19 +00001976 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCallb89836b2010-01-26 01:37:31 +00001977 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001978 }
1979 }
1980 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001981 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001982
1983 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001984 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001985 case OR_Success:
1986 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001987 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001988 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1989 // C++ [over.ics.user]p1:
1990 // If the user-defined conversion is specified by a
1991 // constructor (12.3.1), the initial standard conversion
1992 // sequence converts the source type to the type required by
1993 // the argument of the constructor.
1994 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001995 QualType ThisType = Constructor->getThisType(Context);
John McCall0d1da222010-01-12 00:44:57 +00001996 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian55824512009-11-06 00:23:08 +00001997 User.EllipsisConversion = true;
1998 else {
1999 User.Before = Best->Conversions[0].Standard;
2000 User.EllipsisConversion = false;
2001 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002002 User.ConversionFunction = Constructor;
2003 User.After.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00002004 User.After.setFromType(
2005 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002006 User.After.setAllToTypes(ToType);
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002007 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00002008 } else if (CXXConversionDecl *Conversion
2009 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2010 // C++ [over.ics.user]p1:
2011 //
2012 // [...] If the user-defined conversion is specified by a
2013 // conversion function (12.3.2), the initial standard
2014 // conversion sequence converts the source type to the
2015 // implicit object parameter of the conversion function.
2016 User.Before = Best->Conversions[0].Standard;
2017 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002018 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002019
2020 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00002021 // The second standard conversion sequence converts the
2022 // result of the user-defined conversion to the target type
2023 // for the sequence. Since an implicit conversion sequence
2024 // is an initialization, the special rules for
2025 // initialization by user-defined conversion apply when
2026 // selecting the best user-defined conversion for a
2027 // user-defined conversion sequence (see 13.3.3 and
2028 // 13.3.3.1).
2029 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002030 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002031 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002032 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002033 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002034 }
Mike Stump11289f42009-09-09 15:08:12 +00002035
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002036 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002037 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00002038 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002039 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002040 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002041
2042 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002043 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002044 }
2045
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002046 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002047}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002048
2049bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002050Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002051 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002052 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002053 OverloadingResult OvResult =
2054 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002055 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002056 if (OvResult == OR_Ambiguous)
2057 Diag(From->getSourceRange().getBegin(),
2058 diag::err_typecheck_ambiguous_condition)
2059 << From->getType() << ToType << From->getSourceRange();
2060 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2061 Diag(From->getSourceRange().getBegin(),
2062 diag::err_typecheck_nonviable_condition)
2063 << From->getType() << ToType << From->getSourceRange();
2064 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002065 return false;
John McCallad907772010-01-12 07:18:19 +00002066 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002067 return true;
2068}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002069
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002070/// CompareImplicitConversionSequences - Compare two implicit
2071/// conversion sequences to determine whether one is better than the
2072/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00002073ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002074Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
2075 const ImplicitConversionSequence& ICS2)
2076{
2077 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2078 // conversion sequences (as defined in 13.3.3.1)
2079 // -- a standard conversion sequence (13.3.3.1.1) is a better
2080 // conversion sequence than a user-defined conversion sequence or
2081 // an ellipsis conversion sequence, and
2082 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2083 // conversion sequence than an ellipsis conversion sequence
2084 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002085 //
John McCall0d1da222010-01-12 00:44:57 +00002086 // C++0x [over.best.ics]p10:
2087 // For the purpose of ranking implicit conversion sequences as
2088 // described in 13.3.3.2, the ambiguous conversion sequence is
2089 // treated as a user-defined sequence that is indistinguishable
2090 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002091 if (ICS1.getKindRank() < ICS2.getKindRank())
2092 return ImplicitConversionSequence::Better;
2093 else if (ICS2.getKindRank() < ICS1.getKindRank())
2094 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002095
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002096 // The following checks require both conversion sequences to be of
2097 // the same kind.
2098 if (ICS1.getKind() != ICS2.getKind())
2099 return ImplicitConversionSequence::Indistinguishable;
2100
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002101 // Two implicit conversion sequences of the same form are
2102 // indistinguishable conversion sequences unless one of the
2103 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002104 if (ICS1.isStandard())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002105 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002106 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002107 // User-defined conversion sequence U1 is a better conversion
2108 // sequence than another user-defined conversion sequence U2 if
2109 // they contain the same user-defined conversion function or
2110 // constructor and if the second standard conversion sequence of
2111 // U1 is better than the second standard conversion sequence of
2112 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002113 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002114 ICS2.UserDefined.ConversionFunction)
2115 return CompareStandardConversionSequences(ICS1.UserDefined.After,
2116 ICS2.UserDefined.After);
2117 }
2118
2119 return ImplicitConversionSequence::Indistinguishable;
2120}
2121
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002122static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2123 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2124 Qualifiers Quals;
2125 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2126 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2127 }
2128
2129 return Context.hasSameUnqualifiedType(T1, T2);
2130}
2131
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002132// Per 13.3.3.2p3, compare the given standard conversion sequences to
2133// determine if one is a proper subset of the other.
2134static ImplicitConversionSequence::CompareKind
2135compareStandardConversionSubsets(ASTContext &Context,
2136 const StandardConversionSequence& SCS1,
2137 const StandardConversionSequence& SCS2) {
2138 ImplicitConversionSequence::CompareKind Result
2139 = ImplicitConversionSequence::Indistinguishable;
2140
Douglas Gregore87561a2010-05-23 22:10:15 +00002141 // the identity conversion sequence is considered to be a subsequence of
2142 // any non-identity conversion sequence
2143 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2144 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2145 return ImplicitConversionSequence::Better;
2146 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2147 return ImplicitConversionSequence::Worse;
2148 }
2149
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002150 if (SCS1.Second != SCS2.Second) {
2151 if (SCS1.Second == ICK_Identity)
2152 Result = ImplicitConversionSequence::Better;
2153 else if (SCS2.Second == ICK_Identity)
2154 Result = ImplicitConversionSequence::Worse;
2155 else
2156 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002157 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002158 return ImplicitConversionSequence::Indistinguishable;
2159
2160 if (SCS1.Third == SCS2.Third) {
2161 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2162 : ImplicitConversionSequence::Indistinguishable;
2163 }
2164
2165 if (SCS1.Third == ICK_Identity)
2166 return Result == ImplicitConversionSequence::Worse
2167 ? ImplicitConversionSequence::Indistinguishable
2168 : ImplicitConversionSequence::Better;
2169
2170 if (SCS2.Third == ICK_Identity)
2171 return Result == ImplicitConversionSequence::Better
2172 ? ImplicitConversionSequence::Indistinguishable
2173 : ImplicitConversionSequence::Worse;
2174
2175 return ImplicitConversionSequence::Indistinguishable;
2176}
2177
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002178/// CompareStandardConversionSequences - Compare two standard
2179/// conversion sequences to determine whether one is better than the
2180/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002181ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002182Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
2183 const StandardConversionSequence& SCS2)
2184{
2185 // Standard conversion sequence S1 is a better conversion sequence
2186 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2187
2188 // -- S1 is a proper subsequence of S2 (comparing the conversion
2189 // sequences in the canonical form defined by 13.3.3.1.1,
2190 // excluding any Lvalue Transformation; the identity conversion
2191 // sequence is considered to be a subsequence of any
2192 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002193 if (ImplicitConversionSequence::CompareKind CK
2194 = compareStandardConversionSubsets(Context, SCS1, SCS2))
2195 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002196
2197 // -- the rank of S1 is better than the rank of S2 (by the rules
2198 // defined below), or, if not that,
2199 ImplicitConversionRank Rank1 = SCS1.getRank();
2200 ImplicitConversionRank Rank2 = SCS2.getRank();
2201 if (Rank1 < Rank2)
2202 return ImplicitConversionSequence::Better;
2203 else if (Rank2 < Rank1)
2204 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002205
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002206 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2207 // are indistinguishable unless one of the following rules
2208 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002209
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002210 // A conversion that is not a conversion of a pointer, or
2211 // pointer to member, to bool is better than another conversion
2212 // that is such a conversion.
2213 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2214 return SCS2.isPointerConversionToBool()
2215 ? ImplicitConversionSequence::Better
2216 : ImplicitConversionSequence::Worse;
2217
Douglas Gregor5c407d92008-10-23 00:40:37 +00002218 // C++ [over.ics.rank]p4b2:
2219 //
2220 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002221 // conversion of B* to A* is better than conversion of B* to
2222 // void*, and conversion of A* to void* is better than conversion
2223 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002224 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00002225 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00002226 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00002227 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002228 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2229 // Exactly one of the conversion sequences is a conversion to
2230 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002231 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2232 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002233 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2234 // Neither conversion sequence converts to a void pointer; compare
2235 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002236 if (ImplicitConversionSequence::CompareKind DerivedCK
2237 = CompareDerivedToBaseConversions(SCS1, SCS2))
2238 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002239 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2240 // Both conversion sequences are conversions to void
2241 // pointers. Compare the source types to determine if there's an
2242 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002243 QualType FromType1 = SCS1.getFromType();
2244 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002245
2246 // Adjust the types we're converting from via the array-to-pointer
2247 // conversion, if we need to.
2248 if (SCS1.First == ICK_Array_To_Pointer)
2249 FromType1 = Context.getArrayDecayedType(FromType1);
2250 if (SCS2.First == ICK_Array_To_Pointer)
2251 FromType2 = Context.getArrayDecayedType(FromType2);
2252
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002253 QualType FromPointee1
2254 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2255 QualType FromPointee2
2256 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002257
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002258 if (IsDerivedFrom(FromPointee2, FromPointee1))
2259 return ImplicitConversionSequence::Better;
2260 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2261 return ImplicitConversionSequence::Worse;
2262
2263 // Objective-C++: If one interface is more specific than the
2264 // other, it is the better one.
John McCall8b07ec22010-05-15 11:32:37 +00002265 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2266 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002267 if (FromIface1 && FromIface1) {
2268 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2269 return ImplicitConversionSequence::Better;
2270 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2271 return ImplicitConversionSequence::Worse;
2272 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002273 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002274
2275 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2276 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002277 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002278 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002279 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002280
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002281 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00002282 // C++0x [over.ics.rank]p3b4:
2283 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2284 // implicit object parameter of a non-static member function declared
2285 // without a ref-qualifier, and S1 binds an rvalue reference to an
2286 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00002287 // FIXME: We don't know if we're dealing with the implicit object parameter,
2288 // or if the member function in this case has a ref qualifier.
2289 // (Of course, we don't have ref qualifiers yet.)
2290 if (SCS1.RRefBinding != SCS2.RRefBinding)
2291 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2292 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00002293
2294 // C++ [over.ics.rank]p3b4:
2295 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2296 // which the references refer are the same type except for
2297 // top-level cv-qualifiers, and the type to which the reference
2298 // initialized by S2 refers is more cv-qualified than the type
2299 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002300 QualType T1 = SCS1.getToType(2);
2301 QualType T2 = SCS2.getToType(2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002302 T1 = Context.getCanonicalType(T1);
2303 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002304 Qualifiers T1Quals, T2Quals;
2305 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2306 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2307 if (UnqualT1 == UnqualT2) {
2308 // If the type is an array type, promote the element qualifiers to the type
2309 // for comparison.
2310 if (isa<ArrayType>(T1) && T1Quals)
2311 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2312 if (isa<ArrayType>(T2) && T2Quals)
2313 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002314 if (T2.isMoreQualifiedThan(T1))
2315 return ImplicitConversionSequence::Better;
2316 else if (T1.isMoreQualifiedThan(T2))
2317 return ImplicitConversionSequence::Worse;
2318 }
2319 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002320
2321 return ImplicitConversionSequence::Indistinguishable;
2322}
2323
2324/// CompareQualificationConversions - Compares two standard conversion
2325/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002326/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2327ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002328Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00002329 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002330 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002331 // -- S1 and S2 differ only in their qualification conversion and
2332 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2333 // cv-qualification signature of type T1 is a proper subset of
2334 // the cv-qualification signature of type T2, and S1 is not the
2335 // deprecated string literal array-to-pointer conversion (4.2).
2336 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2337 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2338 return ImplicitConversionSequence::Indistinguishable;
2339
2340 // FIXME: the example in the standard doesn't use a qualification
2341 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002342 QualType T1 = SCS1.getToType(2);
2343 QualType T2 = SCS2.getToType(2);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002344 T1 = Context.getCanonicalType(T1);
2345 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002346 Qualifiers T1Quals, T2Quals;
2347 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2348 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002349
2350 // If the types are the same, we won't learn anything by unwrapped
2351 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002352 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002353 return ImplicitConversionSequence::Indistinguishable;
2354
Chandler Carruth607f38e2009-12-29 07:16:59 +00002355 // If the type is an array type, promote the element qualifiers to the type
2356 // for comparison.
2357 if (isa<ArrayType>(T1) && T1Quals)
2358 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2359 if (isa<ArrayType>(T2) && T2Quals)
2360 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2361
Mike Stump11289f42009-09-09 15:08:12 +00002362 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002363 = ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002364 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002365 // Within each iteration of the loop, we check the qualifiers to
2366 // determine if this still looks like a qualification
2367 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002368 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002369 // until there are no more pointers or pointers-to-members left
2370 // to unwrap. This essentially mimics what
2371 // IsQualificationConversion does, but here we're checking for a
2372 // strict subset of qualifiers.
2373 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2374 // The qualifiers are the same, so this doesn't tell us anything
2375 // about how the sequences rank.
2376 ;
2377 else if (T2.isMoreQualifiedThan(T1)) {
2378 // T1 has fewer qualifiers, so it could be the better sequence.
2379 if (Result == ImplicitConversionSequence::Worse)
2380 // Neither has qualifiers that are a subset of the other's
2381 // qualifiers.
2382 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002383
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002384 Result = ImplicitConversionSequence::Better;
2385 } else if (T1.isMoreQualifiedThan(T2)) {
2386 // T2 has fewer qualifiers, so it could be the better sequence.
2387 if (Result == ImplicitConversionSequence::Better)
2388 // Neither has qualifiers that are a subset of the other's
2389 // qualifiers.
2390 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002391
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002392 Result = ImplicitConversionSequence::Worse;
2393 } else {
2394 // Qualifiers are disjoint.
2395 return ImplicitConversionSequence::Indistinguishable;
2396 }
2397
2398 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002399 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002400 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002401 }
2402
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002403 // Check that the winning standard conversion sequence isn't using
2404 // the deprecated string literal array to pointer conversion.
2405 switch (Result) {
2406 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002407 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002408 Result = ImplicitConversionSequence::Indistinguishable;
2409 break;
2410
2411 case ImplicitConversionSequence::Indistinguishable:
2412 break;
2413
2414 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002415 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002416 Result = ImplicitConversionSequence::Indistinguishable;
2417 break;
2418 }
2419
2420 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002421}
2422
Douglas Gregor5c407d92008-10-23 00:40:37 +00002423/// CompareDerivedToBaseConversions - Compares two standard conversion
2424/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002425/// various kinds of derived-to-base conversions (C++
2426/// [over.ics.rank]p4b3). As part of these checks, we also look at
2427/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002428ImplicitConversionSequence::CompareKind
2429Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2430 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002431 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002432 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002433 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002434 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002435
2436 // Adjust the types we're converting from via the array-to-pointer
2437 // conversion, if we need to.
2438 if (SCS1.First == ICK_Array_To_Pointer)
2439 FromType1 = Context.getArrayDecayedType(FromType1);
2440 if (SCS2.First == ICK_Array_To_Pointer)
2441 FromType2 = Context.getArrayDecayedType(FromType2);
2442
2443 // Canonicalize all of the types.
2444 FromType1 = Context.getCanonicalType(FromType1);
2445 ToType1 = Context.getCanonicalType(ToType1);
2446 FromType2 = Context.getCanonicalType(FromType2);
2447 ToType2 = Context.getCanonicalType(ToType2);
2448
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002449 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002450 //
2451 // If class B is derived directly or indirectly from class A and
2452 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002453 //
2454 // For Objective-C, we let A, B, and C also be Objective-C
2455 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002456
2457 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002458 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002459 SCS2.Second == ICK_Pointer_Conversion &&
2460 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2461 FromType1->isPointerType() && FromType2->isPointerType() &&
2462 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002463 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002464 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002465 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002466 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002467 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002468 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002469 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002470 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002471
John McCall8b07ec22010-05-15 11:32:37 +00002472 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2473 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2474 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2475 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002476
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002477 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002478 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2479 if (IsDerivedFrom(ToPointee1, ToPointee2))
2480 return ImplicitConversionSequence::Better;
2481 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2482 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002483
2484 if (ToIface1 && ToIface2) {
2485 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2486 return ImplicitConversionSequence::Better;
2487 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2488 return ImplicitConversionSequence::Worse;
2489 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002490 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002491
2492 // -- conversion of B* to A* is better than conversion of C* to A*,
2493 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2494 if (IsDerivedFrom(FromPointee2, FromPointee1))
2495 return ImplicitConversionSequence::Better;
2496 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2497 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002498
Douglas Gregor237f96c2008-11-26 23:31:11 +00002499 if (FromIface1 && FromIface2) {
2500 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2501 return ImplicitConversionSequence::Better;
2502 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2503 return ImplicitConversionSequence::Worse;
2504 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002505 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002506 }
2507
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002508 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002509 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2510 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2511 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2512 const MemberPointerType * FromMemPointer1 =
2513 FromType1->getAs<MemberPointerType>();
2514 const MemberPointerType * ToMemPointer1 =
2515 ToType1->getAs<MemberPointerType>();
2516 const MemberPointerType * FromMemPointer2 =
2517 FromType2->getAs<MemberPointerType>();
2518 const MemberPointerType * ToMemPointer2 =
2519 ToType2->getAs<MemberPointerType>();
2520 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2521 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2522 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2523 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2524 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2525 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2526 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2527 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002528 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002529 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2530 if (IsDerivedFrom(ToPointee1, ToPointee2))
2531 return ImplicitConversionSequence::Worse;
2532 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2533 return ImplicitConversionSequence::Better;
2534 }
2535 // conversion of B::* to C::* is better than conversion of A::* to C::*
2536 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2537 if (IsDerivedFrom(FromPointee1, FromPointee2))
2538 return ImplicitConversionSequence::Better;
2539 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2540 return ImplicitConversionSequence::Worse;
2541 }
2542 }
2543
Douglas Gregor5ab11652010-04-17 22:01:05 +00002544 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002545 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002546 // -- binding of an expression of type C to a reference of type
2547 // B& is better than binding an expression of type C to a
2548 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002549 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2550 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002551 if (IsDerivedFrom(ToType1, ToType2))
2552 return ImplicitConversionSequence::Better;
2553 else if (IsDerivedFrom(ToType2, ToType1))
2554 return ImplicitConversionSequence::Worse;
2555 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002556
Douglas Gregor2fe98832008-11-03 19:09:14 +00002557 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002558 // -- binding of an expression of type B to a reference of type
2559 // A& is better than binding an expression of type C to a
2560 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002561 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2562 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002563 if (IsDerivedFrom(FromType2, FromType1))
2564 return ImplicitConversionSequence::Better;
2565 else if (IsDerivedFrom(FromType1, FromType2))
2566 return ImplicitConversionSequence::Worse;
2567 }
2568 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002569
Douglas Gregor5c407d92008-10-23 00:40:37 +00002570 return ImplicitConversionSequence::Indistinguishable;
2571}
2572
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002573/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2574/// determine whether they are reference-related,
2575/// reference-compatible, reference-compatible with added
2576/// qualification, or incompatible, for use in C++ initialization by
2577/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2578/// type, and the first type (T1) is the pointee type of the reference
2579/// type being initialized.
2580Sema::ReferenceCompareResult
2581Sema::CompareReferenceRelationship(SourceLocation Loc,
2582 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002583 bool &DerivedToBase,
2584 bool &ObjCConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002585 assert(!OrigT1->isReferenceType() &&
2586 "T1 must be the pointee type of the reference type");
2587 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2588
2589 QualType T1 = Context.getCanonicalType(OrigT1);
2590 QualType T2 = Context.getCanonicalType(OrigT2);
2591 Qualifiers T1Quals, T2Quals;
2592 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2593 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2594
2595 // C++ [dcl.init.ref]p4:
2596 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2597 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2598 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002599 DerivedToBase = false;
2600 ObjCConversion = false;
2601 if (UnqualT1 == UnqualT2) {
2602 // Nothing to do.
2603 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002604 IsDerivedFrom(UnqualT2, UnqualT1))
2605 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002606 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2607 UnqualT2->isObjCObjectOrInterfaceType() &&
2608 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2609 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002610 else
2611 return Ref_Incompatible;
2612
2613 // At this point, we know that T1 and T2 are reference-related (at
2614 // least).
2615
2616 // If the type is an array type, promote the element qualifiers to the type
2617 // for comparison.
2618 if (isa<ArrayType>(T1) && T1Quals)
2619 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2620 if (isa<ArrayType>(T2) && T2Quals)
2621 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2622
2623 // C++ [dcl.init.ref]p4:
2624 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2625 // reference-related to T2 and cv1 is the same cv-qualification
2626 // as, or greater cv-qualification than, cv2. For purposes of
2627 // overload resolution, cases for which cv1 is greater
2628 // cv-qualification than cv2 are identified as
2629 // reference-compatible with added qualification (see 13.3.3.2).
2630 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2631 return Ref_Compatible;
2632 else if (T1.isMoreQualifiedThan(T2))
2633 return Ref_Compatible_With_Added_Qualification;
2634 else
2635 return Ref_Related;
2636}
2637
Douglas Gregor836a7e82010-08-11 02:15:33 +00002638/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00002639/// with DeclType. Return true if something definite is found.
2640static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00002641FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2642 QualType DeclType, SourceLocation DeclLoc,
2643 Expr *Init, QualType T2, bool AllowRvalues,
2644 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002645 assert(T2->isRecordType() && "Can only find conversions of record types.");
2646 CXXRecordDecl *T2RecordDecl
2647 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2648
Douglas Gregor836a7e82010-08-11 02:15:33 +00002649 QualType ToType
2650 = AllowRvalues? DeclType->getAs<ReferenceType>()->getPointeeType()
2651 : DeclType;
2652
Sebastian Redld92badf2010-06-30 18:13:39 +00002653 OverloadCandidateSet CandidateSet(DeclLoc);
2654 const UnresolvedSetImpl *Conversions
2655 = T2RecordDecl->getVisibleConversionFunctions();
2656 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2657 E = Conversions->end(); I != E; ++I) {
2658 NamedDecl *D = *I;
2659 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2660 if (isa<UsingShadowDecl>(D))
2661 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2662
2663 FunctionTemplateDecl *ConvTemplate
2664 = dyn_cast<FunctionTemplateDecl>(D);
2665 CXXConversionDecl *Conv;
2666 if (ConvTemplate)
2667 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2668 else
2669 Conv = cast<CXXConversionDecl>(D);
2670
Douglas Gregor836a7e82010-08-11 02:15:33 +00002671 // If this is an explicit conversion, and we're not allowed to consider
2672 // explicit conversions, skip it.
2673 if (!AllowExplicit && Conv->isExplicit())
2674 continue;
2675
2676 if (AllowRvalues) {
2677 bool DerivedToBase = false;
2678 bool ObjCConversion = false;
2679 if (!ConvTemplate &&
2680 S.CompareReferenceRelationship(DeclLoc,
2681 Conv->getConversionType().getNonReferenceType().getUnqualifiedType(),
2682 DeclType.getNonReferenceType().getUnqualifiedType(),
2683 DerivedToBase, ObjCConversion)
2684 == Sema::Ref_Incompatible)
2685 continue;
2686 } else {
2687 // If the conversion function doesn't return a reference type,
2688 // it can't be considered for this conversion. An rvalue reference
2689 // is only acceptable if its referencee is a function type.
2690
2691 const ReferenceType *RefType =
2692 Conv->getConversionType()->getAs<ReferenceType>();
2693 if (!RefType ||
2694 (!RefType->isLValueReferenceType() &&
2695 !RefType->getPointeeType()->isFunctionType()))
2696 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00002697 }
Douglas Gregor836a7e82010-08-11 02:15:33 +00002698
2699 if (ConvTemplate)
2700 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2701 Init, ToType, CandidateSet);
2702 else
2703 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2704 ToType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00002705 }
2706
2707 OverloadCandidateSet::iterator Best;
2708 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2709 case OR_Success:
2710 // C++ [over.ics.ref]p1:
2711 //
2712 // [...] If the parameter binds directly to the result of
2713 // applying a conversion function to the argument
2714 // expression, the implicit conversion sequence is a
2715 // user-defined conversion sequence (13.3.3.1.2), with the
2716 // second standard conversion sequence either an identity
2717 // conversion or, if the conversion function returns an
2718 // entity of a type that is a derived class of the parameter
2719 // type, a derived-to-base Conversion.
2720 if (!Best->FinalConversion.DirectBinding)
2721 return false;
2722
2723 ICS.setUserDefined();
2724 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2725 ICS.UserDefined.After = Best->FinalConversion;
2726 ICS.UserDefined.ConversionFunction = Best->Function;
2727 ICS.UserDefined.EllipsisConversion = false;
2728 assert(ICS.UserDefined.After.ReferenceBinding &&
2729 ICS.UserDefined.After.DirectBinding &&
2730 "Expected a direct reference binding!");
2731 return true;
2732
2733 case OR_Ambiguous:
2734 ICS.setAmbiguous();
2735 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2736 Cand != CandidateSet.end(); ++Cand)
2737 if (Cand->Viable)
2738 ICS.Ambiguous.addConversion(Cand->Function);
2739 return true;
2740
2741 case OR_No_Viable_Function:
2742 case OR_Deleted:
2743 // There was no suitable conversion, or we found a deleted
2744 // conversion; continue with other checks.
2745 return false;
2746 }
Eric Christopheraba9fb22010-06-30 18:36:32 +00002747
2748 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002749}
2750
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002751/// \brief Compute an implicit conversion sequence for reference
2752/// initialization.
2753static ImplicitConversionSequence
2754TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2755 SourceLocation DeclLoc,
2756 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002757 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002758 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2759
2760 // Most paths end in a failed conversion.
2761 ImplicitConversionSequence ICS;
2762 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2763
2764 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2765 QualType T2 = Init->getType();
2766
2767 // If the initializer is the address of an overloaded function, try
2768 // to resolve the overloaded function. If all goes well, T2 is the
2769 // type of the resulting function.
2770 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2771 DeclAccessPair Found;
2772 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2773 false, Found))
2774 T2 = Fn->getType();
2775 }
2776
2777 // Compute some basic properties of the types and the initializer.
2778 bool isRValRef = DeclType->isRValueReferenceType();
2779 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002780 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002781 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002782 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002783 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
2784 ObjCConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002785
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002786
Sebastian Redld92badf2010-06-30 18:13:39 +00002787 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00002788 // A reference to type "cv1 T1" is initialized by an expression
2789 // of type "cv2 T2" as follows:
2790
Sebastian Redld92badf2010-06-30 18:13:39 +00002791 // -- If reference is an lvalue reference and the initializer expression
2792 // The next bullet point (T1 is a function) is pretty much equivalent to this
2793 // one, so it's handled here.
2794 if (!isRValRef || T1->isFunctionType()) {
2795 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2796 // reference-compatible with "cv2 T2," or
2797 //
2798 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2799 if (InitCategory.isLValue() &&
2800 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002801 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00002802 // When a parameter of reference type binds directly (8.5.3)
2803 // to an argument expression, the implicit conversion sequence
2804 // is the identity conversion, unless the argument expression
2805 // has a type that is a derived class of the parameter type,
2806 // in which case the implicit conversion sequence is a
2807 // derived-to-base Conversion (13.3.3.1).
2808 ICS.setStandard();
2809 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002810 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2811 : ObjCConversion? ICK_Compatible_Conversion
2812 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00002813 ICS.Standard.Third = ICK_Identity;
2814 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2815 ICS.Standard.setToType(0, T2);
2816 ICS.Standard.setToType(1, T1);
2817 ICS.Standard.setToType(2, T1);
2818 ICS.Standard.ReferenceBinding = true;
2819 ICS.Standard.DirectBinding = true;
2820 ICS.Standard.RRefBinding = isRValRef;
2821 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002822
Sebastian Redld92badf2010-06-30 18:13:39 +00002823 // Nothing more to do: the inaccessibility/ambiguity check for
2824 // derived-to-base conversions is suppressed when we're
2825 // computing the implicit conversion sequence (C++
2826 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002827 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00002828 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002829
Sebastian Redld92badf2010-06-30 18:13:39 +00002830 // -- has a class type (i.e., T2 is a class type), where T1 is
2831 // not reference-related to T2, and can be implicitly
2832 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2833 // is reference-compatible with "cv3 T3" 92) (this
2834 // conversion is selected by enumerating the applicable
2835 // conversion functions (13.3.1.6) and choosing the best
2836 // one through overload resolution (13.3)),
2837 if (!SuppressUserConversions && T2->isRecordType() &&
2838 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2839 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00002840 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2841 Init, T2, /*AllowRvalues=*/false,
2842 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00002843 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002844 }
2845 }
2846
Sebastian Redld92badf2010-06-30 18:13:39 +00002847 // -- Otherwise, the reference shall be an lvalue reference to a
2848 // non-volatile const type (i.e., cv1 shall be const), or the reference
2849 // shall be an rvalue reference and the initializer expression shall be
2850 // an rvalue or have a function type.
Douglas Gregor870f3742010-04-18 09:22:00 +00002851 //
2852 // We actually handle one oddity of C++ [over.ics.ref] at this
2853 // point, which is that, due to p2 (which short-circuits reference
2854 // binding by only attempting a simple conversion for non-direct
2855 // bindings) and p3's strange wording, we allow a const volatile
2856 // reference to bind to an rvalue. Hence the check for the presence
2857 // of "const" rather than checking for "const" being the only
2858 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00002859 // This is also the point where rvalue references and lvalue inits no longer
2860 // go together.
2861 if ((!isRValRef && !T1.isConstQualified()) ||
2862 (isRValRef && InitCategory.isLValue()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002863 return ICS;
2864
Sebastian Redld92badf2010-06-30 18:13:39 +00002865 // -- If T1 is a function type, then
2866 // -- if T2 is the same type as T1, the reference is bound to the
2867 // initializer expression lvalue;
2868 // -- if T2 is a class type and the initializer expression can be
2869 // implicitly converted to an lvalue of type T1 [...], the
2870 // reference is bound to the function lvalue that is the result
2871 // of the conversion;
2872 // This is the same as for the lvalue case above, so it was handled there.
2873 // -- otherwise, the program is ill-formed.
2874 // This is the one difference to the lvalue case.
2875 if (T1->isFunctionType())
2876 return ICS;
2877
2878 // -- Otherwise, if T2 is a class type and
Douglas Gregorf93df192010-04-18 08:46:23 +00002879 // -- the initializer expression is an rvalue and "cv1 T1"
2880 // is reference-compatible with "cv2 T2," or
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002881 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002882 // -- T1 is not reference-related to T2 and the initializer
2883 // expression can be implicitly converted to an rvalue
2884 // of type "cv3 T3" (this conversion is selected by
2885 // enumerating the applicable conversion functions
2886 // (13.3.1.6) and choosing the best one through overload
2887 // resolution (13.3)),
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002888 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002889 // then the reference is bound to the initializer
2890 // expression rvalue in the first case and to the object
2891 // that is the result of the conversion in the second case
2892 // (or, in either case, to the appropriate base class
2893 // subobject of the object).
Douglas Gregor836a7e82010-08-11 02:15:33 +00002894 if (T2->isRecordType()) {
2895 // First case: "cv1 T1" is reference-compatible with "cv2 T2". This is a
2896 // direct binding in C++0x but not in C++03.
2897 if (InitCategory.isRValue() &&
2898 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2899 ICS.setStandard();
2900 ICS.Standard.First = ICK_Identity;
2901 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2902 : ObjCConversion? ICK_Compatible_Conversion
2903 : ICK_Identity;
2904 ICS.Standard.Third = ICK_Identity;
2905 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2906 ICS.Standard.setToType(0, T2);
2907 ICS.Standard.setToType(1, T1);
2908 ICS.Standard.setToType(2, T1);
2909 ICS.Standard.ReferenceBinding = true;
2910 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
2911 ICS.Standard.RRefBinding = isRValRef;
2912 ICS.Standard.CopyConstructor = 0;
2913 return ICS;
2914 }
2915
2916 // Second case: not reference-related.
2917 if (RefRelationship == Sema::Ref_Incompatible &&
2918 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2919 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2920 Init, T2, /*AllowRvalues=*/true,
2921 AllowExplicit))
2922 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002923 }
Douglas Gregor836a7e82010-08-11 02:15:33 +00002924
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002925 // -- Otherwise, a temporary of type "cv1 T1" is created and
2926 // initialized from the initializer expression using the
2927 // rules for a non-reference copy initialization (8.5). The
2928 // reference is then bound to the temporary. If T1 is
2929 // reference-related to T2, cv1 must be the same
2930 // cv-qualification as, or greater cv-qualification than,
2931 // cv2; otherwise, the program is ill-formed.
2932 if (RefRelationship == Sema::Ref_Related) {
2933 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2934 // we would be reference-compatible or reference-compatible with
2935 // added qualification. But that wasn't the case, so the reference
2936 // initialization fails.
2937 return ICS;
2938 }
2939
2940 // If at least one of the types is a class type, the types are not
2941 // related, and we aren't allowed any user conversions, the
2942 // reference binding fails. This case is important for breaking
2943 // recursion, since TryImplicitConversion below will attempt to
2944 // create a temporary through the use of a copy constructor.
2945 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2946 (T1->isRecordType() || T2->isRecordType()))
2947 return ICS;
2948
2949 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002950 // When a parameter of reference type is not bound directly to
2951 // an argument expression, the conversion sequence is the one
2952 // required to convert the argument expression to the
2953 // underlying type of the reference according to
2954 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2955 // to copy-initializing a temporary of the underlying type with
2956 // the argument expression. Any difference in top-level
2957 // cv-qualification is subsumed by the initialization itself
2958 // and does not constitute a conversion.
2959 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2960 /*AllowExplicit=*/false,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002961 /*InOverloadResolution=*/false);
2962
2963 // Of course, that's still a reference binding.
2964 if (ICS.isStandard()) {
2965 ICS.Standard.ReferenceBinding = true;
2966 ICS.Standard.RRefBinding = isRValRef;
2967 } else if (ICS.isUserDefined()) {
2968 ICS.UserDefined.After.ReferenceBinding = true;
2969 ICS.UserDefined.After.RRefBinding = isRValRef;
2970 }
2971 return ICS;
2972}
2973
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002974/// TryCopyInitialization - Try to copy-initialize a value of type
2975/// ToType from the expression From. Return the implicit conversion
2976/// sequence required to pass this argument, which may be a bad
2977/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002978/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00002979/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002980static ImplicitConversionSequence
2981TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00002982 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002983 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002984 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002985 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002986 /*FIXME:*/From->getLocStart(),
2987 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002988 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002989
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002990 return S.TryImplicitConversion(From, ToType,
2991 SuppressUserConversions,
2992 /*AllowExplicit=*/false,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002993 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002994}
2995
Douglas Gregor436424c2008-11-18 23:14:02 +00002996/// TryObjectArgumentInitialization - Try to initialize the object
2997/// parameter of the given member function (@c Method) from the
2998/// expression @p From.
2999ImplicitConversionSequence
John McCall47000992010-01-14 03:28:57 +00003000Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall6e9f8f62009-12-03 04:06:58 +00003001 CXXMethodDecl *Method,
3002 CXXRecordDecl *ActingContext) {
3003 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003004 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3005 // const volatile object.
3006 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3007 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
3008 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003009
3010 // Set up the conversion sequence as a "bad" conversion, to allow us
3011 // to exit early.
3012 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003013
3014 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003015 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003016 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003017 FromType = PT->getPointeeType();
3018
3019 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003020
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003021 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00003022 // where X is the class of which the function is a member
3023 // (C++ [over.match.funcs]p4). However, when finding an implicit
3024 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00003025 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003026 // (C++ [over.match.funcs]p5). We perform a simplified version of
3027 // reference binding here, that allows class rvalues to bind to
3028 // non-constant references.
3029
3030 // First check the qualifiers. We don't care about lvalue-vs-rvalue
3031 // with the implicit object parameter (C++ [over.match.funcs]p5).
3032 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003033 if (ImplicitParamType.getCVRQualifiers()
3034 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003035 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003036 ICS.setBad(BadConversionSequence::bad_qualifiers,
3037 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003038 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003039 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003040
3041 // Check that we have either the same type or a derived type. It
3042 // affects the conversion rank.
3043 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003044 ImplicitConversionKind SecondKind;
3045 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3046 SecondKind = ICK_Identity;
3047 } else if (IsDerivedFrom(FromType, ClassType))
3048 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003049 else {
John McCall65eb8792010-02-25 01:37:24 +00003050 ICS.setBad(BadConversionSequence::unrelated_class,
3051 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003052 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003053 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003054
3055 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003056 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003057 ICS.Standard.setAsIdentityConversion();
3058 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003059 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003060 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003061 ICS.Standard.ReferenceBinding = true;
3062 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00003063 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003064 return ICS;
3065}
3066
3067/// PerformObjectArgumentInitialization - Perform initialization of
3068/// the implicit object parameter for the given Method with the given
3069/// expression.
3070bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003071Sema::PerformObjectArgumentInitialization(Expr *&From,
3072 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003073 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003074 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003075 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003076 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003077 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003078
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003079 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003080 FromRecordType = PT->getPointeeType();
3081 DestType = Method->getThisType(Context);
3082 } else {
3083 FromRecordType = From->getType();
3084 DestType = ImplicitParamRecordType;
3085 }
3086
John McCall6e9f8f62009-12-03 04:06:58 +00003087 // Note that we always use the true parent context when performing
3088 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003089 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00003090 = TryObjectArgumentInitialization(From->getType(), Method,
3091 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00003092 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00003093 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003094 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003095 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003096
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003097 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00003098 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00003099
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003100 if (!Context.hasSameType(From->getType(), DestType))
Anders Carlsson0c509ee2010-04-24 16:57:13 +00003101 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
Sebastian Redlc57d34b2010-07-20 04:20:21 +00003102 From->getType()->isPointerType() ?
3103 ImplicitCastExpr::RValue : ImplicitCastExpr::LValue);
Douglas Gregor436424c2008-11-18 23:14:02 +00003104 return false;
3105}
3106
Douglas Gregor5fb53972009-01-14 15:45:31 +00003107/// TryContextuallyConvertToBool - Attempt to contextually convert the
3108/// expression From to bool (C++0x [conv]p3).
3109ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003110 // FIXME: This is pretty broken.
Mike Stump11289f42009-09-09 15:08:12 +00003111 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003112 // FIXME: Are these flags correct?
3113 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003114 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00003115 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003116}
3117
3118/// PerformContextuallyConvertToBool - Perform a contextual conversion
3119/// of the expression From to bool (C++0x [conv]p3).
3120bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
3121 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00003122 if (!ICS.isBad())
3123 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003124
Fariborz Jahanian76197412009-11-18 18:26:29 +00003125 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003126 return Diag(From->getSourceRange().getBegin(),
3127 diag::err_typecheck_bool_condition)
3128 << From->getType() << From->getSourceRange();
3129 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003130}
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003131
3132/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3133/// expression From to 'id'.
3134ImplicitConversionSequence Sema::TryContextuallyConvertToObjCId(Expr *From) {
John McCall8b07ec22010-05-15 11:32:37 +00003135 QualType Ty = Context.getObjCIdType();
3136 return TryImplicitConversion(From, Ty,
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003137 // FIXME: Are these flags correct?
3138 /*SuppressUserConversions=*/false,
3139 /*AllowExplicit=*/true,
3140 /*InOverloadResolution=*/false);
3141}
3142
3143/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3144/// of the expression From to 'id'.
3145bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCall8b07ec22010-05-15 11:32:37 +00003146 QualType Ty = Context.getObjCIdType();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003147 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(From);
3148 if (!ICS.isBad())
3149 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3150 return true;
3151}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003152
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003153/// \brief Attempt to convert the given expression to an integral or
3154/// enumeration type.
3155///
3156/// This routine will attempt to convert an expression of class type to an
3157/// integral or enumeration type, if that class type only has a single
3158/// conversion to an integral or enumeration type.
3159///
Douglas Gregor4799d032010-06-30 00:20:43 +00003160/// \param Loc The source location of the construct that requires the
3161/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003162///
Douglas Gregor4799d032010-06-30 00:20:43 +00003163/// \param FromE The expression we're converting from.
3164///
3165/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3166/// have integral or enumeration type.
3167///
3168/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3169/// incomplete class type.
3170///
3171/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3172/// explicit conversion function (because no implicit conversion functions
3173/// were available). This is a recovery mode.
3174///
3175/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3176/// showing which conversion was picked.
3177///
3178/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3179/// conversion function that could convert to integral or enumeration type.
3180///
3181/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3182/// usable conversion function.
3183///
3184/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3185/// function, which may be an extension in this case.
3186///
3187/// \returns The expression, converted to an integral or enumeration type if
3188/// successful.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003189Sema::OwningExprResult
3190Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, ExprArg FromE,
3191 const PartialDiagnostic &NotIntDiag,
3192 const PartialDiagnostic &IncompleteDiag,
3193 const PartialDiagnostic &ExplicitConvDiag,
3194 const PartialDiagnostic &ExplicitConvNote,
3195 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003196 const PartialDiagnostic &AmbigNote,
3197 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003198 Expr *From = static_cast<Expr *>(FromE.get());
3199
3200 // We can't perform any more checking for type-dependent expressions.
3201 if (From->isTypeDependent())
3202 return move(FromE);
3203
3204 // If the expression already has integral or enumeration type, we're golden.
3205 QualType T = From->getType();
3206 if (T->isIntegralOrEnumerationType())
3207 return move(FromE);
3208
3209 // FIXME: Check for missing '()' if T is a function type?
3210
3211 // If we don't have a class type in C++, there's no way we can get an
3212 // expression of integral or enumeration type.
3213 const RecordType *RecordTy = T->getAs<RecordType>();
3214 if (!RecordTy || !getLangOptions().CPlusPlus) {
3215 Diag(Loc, NotIntDiag)
3216 << T << From->getSourceRange();
Douglas Gregor5823da32010-06-29 23:25:20 +00003217 return move(FromE);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003218 }
3219
3220 // We must have a complete class type.
3221 if (RequireCompleteType(Loc, T, IncompleteDiag))
Douglas Gregor4799d032010-06-30 00:20:43 +00003222 return move(FromE);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003223
3224 // Look for a conversion to an integral or enumeration type.
3225 UnresolvedSet<4> ViableConversions;
3226 UnresolvedSet<4> ExplicitConversions;
3227 const UnresolvedSetImpl *Conversions
3228 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3229
3230 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3231 E = Conversions->end();
3232 I != E;
3233 ++I) {
3234 if (CXXConversionDecl *Conversion
3235 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3236 if (Conversion->getConversionType().getNonReferenceType()
3237 ->isIntegralOrEnumerationType()) {
3238 if (Conversion->isExplicit())
3239 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3240 else
3241 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3242 }
3243 }
3244
3245 switch (ViableConversions.size()) {
3246 case 0:
3247 if (ExplicitConversions.size() == 1) {
3248 DeclAccessPair Found = ExplicitConversions[0];
3249 CXXConversionDecl *Conversion
3250 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3251
3252 // The user probably meant to invoke the given explicit
3253 // conversion; use it.
3254 QualType ConvTy
3255 = Conversion->getConversionType().getNonReferenceType();
3256 std::string TypeStr;
3257 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3258
3259 Diag(Loc, ExplicitConvDiag)
3260 << T << ConvTy
3261 << FixItHint::CreateInsertion(From->getLocStart(),
3262 "static_cast<" + TypeStr + ">(")
3263 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3264 ")");
3265 Diag(Conversion->getLocation(), ExplicitConvNote)
3266 << ConvTy->isEnumeralType() << ConvTy;
3267
3268 // If we aren't in a SFINAE context, build a call to the
3269 // explicit conversion function.
3270 if (isSFINAEContext())
3271 return ExprError();
3272
3273 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
3274 From = BuildCXXMemberCallExpr(FromE.takeAs<Expr>(), Found, Conversion);
3275 FromE = Owned(From);
3276 }
3277
3278 // We'll complain below about a non-integral condition type.
3279 break;
3280
3281 case 1: {
3282 // Apply this conversion.
3283 DeclAccessPair Found = ViableConversions[0];
3284 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor4799d032010-06-30 00:20:43 +00003285
3286 CXXConversionDecl *Conversion
3287 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3288 QualType ConvTy
3289 = Conversion->getConversionType().getNonReferenceType();
3290 if (ConvDiag.getDiagID()) {
3291 if (isSFINAEContext())
3292 return ExprError();
3293
3294 Diag(Loc, ConvDiag)
3295 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3296 }
3297
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003298 From = BuildCXXMemberCallExpr(FromE.takeAs<Expr>(), Found,
3299 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
3300 FromE = Owned(From);
3301 break;
3302 }
3303
3304 default:
3305 Diag(Loc, AmbigDiag)
3306 << T << From->getSourceRange();
3307 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3308 CXXConversionDecl *Conv
3309 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3310 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3311 Diag(Conv->getLocation(), AmbigNote)
3312 << ConvTy->isEnumeralType() << ConvTy;
3313 }
Douglas Gregor5823da32010-06-29 23:25:20 +00003314 return move(FromE);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003315 }
3316
Douglas Gregor5823da32010-06-29 23:25:20 +00003317 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003318 Diag(Loc, NotIntDiag)
3319 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003320
3321 return move(FromE);
3322}
3323
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003324/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003325/// candidate functions, using the given function call arguments. If
3326/// @p SuppressUserConversions, then don't allow user-defined
3327/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003328///
3329/// \para PartialOverloading true if we are performing "partial" overloading
3330/// based on an incomplete set of function arguments. This feature is used by
3331/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003332void
3333Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003334 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003335 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003336 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003337 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003338 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003339 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003340 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003341 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003342 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003343 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003344
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003345 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003346 if (!isa<CXXConstructorDecl>(Method)) {
3347 // If we get here, it's because we're calling a member function
3348 // that is named without a member access expression (e.g.,
3349 // "this->f") that was either written explicitly or created
3350 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003351 // function, e.g., X::f(). We use an empty type for the implied
3352 // object argument (C++ [over.call.func]p3), and the acting context
3353 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003354 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00003355 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003356 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003357 return;
3358 }
3359 // We treat a constructor like a non-member function, since its object
3360 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003361 }
3362
Douglas Gregorff7028a2009-11-13 23:59:09 +00003363 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003364 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003365
Douglas Gregor27381f32009-11-23 12:27:39 +00003366 // Overload resolution is always an unevaluated context.
3367 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3368
Douglas Gregorffe14e32009-11-14 01:20:54 +00003369 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3370 // C++ [class.copy]p3:
3371 // A member function template is never instantiated to perform the copy
3372 // of a class object to an object of its class type.
3373 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3374 if (NumArgs == 1 &&
3375 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003376 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3377 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003378 return;
3379 }
3380
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003381 // Add this candidate
3382 CandidateSet.push_back(OverloadCandidate());
3383 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003384 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003385 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003386 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003387 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003388 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003389
3390 unsigned NumArgsInProto = Proto->getNumArgs();
3391
3392 // (C++ 13.3.2p2): A candidate function having fewer than m
3393 // parameters is viable only if it has an ellipsis in its parameter
3394 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00003395 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3396 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003397 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003398 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003399 return;
3400 }
3401
3402 // (C++ 13.3.2p2): A candidate function having more than m parameters
3403 // is viable only if the (m+1)st parameter has a default argument
3404 // (8.3.6). For the purposes of overload resolution, the
3405 // parameter list is truncated on the right, so that there are
3406 // exactly m parameters.
3407 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003408 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003409 // Not enough arguments.
3410 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003411 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003412 return;
3413 }
3414
3415 // Determine the implicit conversion sequences for each of the
3416 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003417 Candidate.Conversions.resize(NumArgs);
3418 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3419 if (ArgIdx < NumArgsInProto) {
3420 // (C++ 13.3.2p3): for F to be a viable function, there shall
3421 // exist for each argument an implicit conversion sequence
3422 // (13.3.3.1) that converts that argument to the corresponding
3423 // parameter of F.
3424 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003425 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003426 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00003427 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003428 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003429 if (Candidate.Conversions[ArgIdx].isBad()) {
3430 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003431 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003432 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003433 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003434 } else {
3435 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3436 // argument for which there is no corresponding parameter is
3437 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003438 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003439 }
3440 }
3441}
3442
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003443/// \brief Add all of the function declarations in the given function set to
3444/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003445void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003446 Expr **Args, unsigned NumArgs,
3447 OverloadCandidateSet& CandidateSet,
3448 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003449 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003450 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3451 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003452 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003453 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003454 cast<CXXMethodDecl>(FD)->getParent(),
3455 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003456 CandidateSet, SuppressUserConversions);
3457 else
John McCalla0296f72010-03-19 07:35:19 +00003458 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003459 SuppressUserConversions);
3460 } else {
John McCalla0296f72010-03-19 07:35:19 +00003461 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003462 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3463 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003464 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003465 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003466 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003467 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003468 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003469 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003470 else
John McCalla0296f72010-03-19 07:35:19 +00003471 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003472 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003473 Args, NumArgs, CandidateSet,
3474 SuppressUserConversions);
3475 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003476 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003477}
3478
John McCallf0f1cf02009-11-17 07:50:12 +00003479/// AddMethodCandidate - Adds a named decl (which is some kind of
3480/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003481void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003482 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00003483 Expr **Args, unsigned NumArgs,
3484 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003485 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003486 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003487 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003488
3489 if (isa<UsingShadowDecl>(Decl))
3490 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3491
3492 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3493 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3494 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003495 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3496 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003497 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003498 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003499 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003500 } else {
John McCalla0296f72010-03-19 07:35:19 +00003501 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00003502 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003503 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003504 }
3505}
3506
Douglas Gregor436424c2008-11-18 23:14:02 +00003507/// AddMethodCandidate - Adds the given C++ member function to the set
3508/// of candidate functions, using the given function call arguments
3509/// and the object argument (@c Object). For example, in a call
3510/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3511/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3512/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003513/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003514void
John McCalla0296f72010-03-19 07:35:19 +00003515Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003516 CXXRecordDecl *ActingContext, QualType ObjectType,
3517 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003518 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003519 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003520 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003521 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003522 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003523 assert(!isa<CXXConstructorDecl>(Method) &&
3524 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003525
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003526 if (!CandidateSet.isNewCandidate(Method))
3527 return;
3528
Douglas Gregor27381f32009-11-23 12:27:39 +00003529 // Overload resolution is always an unevaluated context.
3530 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3531
Douglas Gregor436424c2008-11-18 23:14:02 +00003532 // Add this candidate
3533 CandidateSet.push_back(OverloadCandidate());
3534 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003535 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003536 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003537 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003538 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003539
3540 unsigned NumArgsInProto = Proto->getNumArgs();
3541
3542 // (C++ 13.3.2p2): A candidate function having fewer than m
3543 // parameters is viable only if it has an ellipsis in its parameter
3544 // list (8.3.5).
3545 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3546 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003547 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003548 return;
3549 }
3550
3551 // (C++ 13.3.2p2): A candidate function having more than m parameters
3552 // is viable only if the (m+1)st parameter has a default argument
3553 // (8.3.6). For the purposes of overload resolution, the
3554 // parameter list is truncated on the right, so that there are
3555 // exactly m parameters.
3556 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3557 if (NumArgs < MinRequiredArgs) {
3558 // Not enough arguments.
3559 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003560 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003561 return;
3562 }
3563
3564 Candidate.Viable = true;
3565 Candidate.Conversions.resize(NumArgs + 1);
3566
John McCall6e9f8f62009-12-03 04:06:58 +00003567 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003568 // The implicit object argument is ignored.
3569 Candidate.IgnoreObjectArgument = true;
3570 else {
3571 // Determine the implicit conversion sequence for the object
3572 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00003573 Candidate.Conversions[0]
3574 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003575 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003576 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003577 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003578 return;
3579 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003580 }
3581
3582 // Determine the implicit conversion sequences for each of the
3583 // arguments.
3584 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3585 if (ArgIdx < NumArgsInProto) {
3586 // (C++ 13.3.2p3): for F to be a viable function, there shall
3587 // exist for each argument an implicit conversion sequence
3588 // (13.3.3.1) that converts that argument to the corresponding
3589 // parameter of F.
3590 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003591 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003592 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003593 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003594 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003595 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003596 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003597 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003598 break;
3599 }
3600 } else {
3601 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3602 // argument for which there is no corresponding parameter is
3603 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003604 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003605 }
3606 }
3607}
Douglas Gregor3626a5c2010-05-08 17:41:32 +00003608
Douglas Gregor97628d62009-08-21 00:16:32 +00003609/// \brief Add a C++ member function template as a candidate to the candidate
3610/// set, using template argument deduction to produce an appropriate member
3611/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003612void
Douglas Gregor97628d62009-08-21 00:16:32 +00003613Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003614 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003615 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003616 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003617 QualType ObjectType,
3618 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003619 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003620 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003621 if (!CandidateSet.isNewCandidate(MethodTmpl))
3622 return;
3623
Douglas Gregor97628d62009-08-21 00:16:32 +00003624 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003625 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003626 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003627 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003628 // candidate functions in the usual way.113) A given name can refer to one
3629 // or more function templates and also to a set of overloaded non-template
3630 // functions. In such a case, the candidate functions generated from each
3631 // function template are combined with the set of non-template candidate
3632 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003633 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003634 FunctionDecl *Specialization = 0;
3635 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003636 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003637 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003638 CandidateSet.push_back(OverloadCandidate());
3639 OverloadCandidate &Candidate = CandidateSet.back();
3640 Candidate.FoundDecl = FoundDecl;
3641 Candidate.Function = MethodTmpl->getTemplatedDecl();
3642 Candidate.Viable = false;
3643 Candidate.FailureKind = ovl_fail_bad_deduction;
3644 Candidate.IsSurrogate = false;
3645 Candidate.IgnoreObjectArgument = false;
3646 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3647 Info);
3648 return;
3649 }
Mike Stump11289f42009-09-09 15:08:12 +00003650
Douglas Gregor97628d62009-08-21 00:16:32 +00003651 // Add the function template specialization produced by template argument
3652 // deduction as a candidate.
3653 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003654 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003655 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003656 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003657 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003658 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003659}
3660
Douglas Gregor05155d82009-08-21 23:19:43 +00003661/// \brief Add a C++ function template specialization as a candidate
3662/// in the candidate set, using template argument deduction to produce
3663/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003664void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003665Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003666 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003667 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003668 Expr **Args, unsigned NumArgs,
3669 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003670 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003671 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3672 return;
3673
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003674 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003675 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003676 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003677 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003678 // candidate functions in the usual way.113) A given name can refer to one
3679 // or more function templates and also to a set of overloaded non-template
3680 // functions. In such a case, the candidate functions generated from each
3681 // function template are combined with the set of non-template candidate
3682 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003683 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003684 FunctionDecl *Specialization = 0;
3685 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003686 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003687 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003688 CandidateSet.push_back(OverloadCandidate());
3689 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003690 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003691 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3692 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003693 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003694 Candidate.IsSurrogate = false;
3695 Candidate.IgnoreObjectArgument = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003696 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3697 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003698 return;
3699 }
Mike Stump11289f42009-09-09 15:08:12 +00003700
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003701 // Add the function template specialization produced by template argument
3702 // deduction as a candidate.
3703 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003704 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003705 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003706}
Mike Stump11289f42009-09-09 15:08:12 +00003707
Douglas Gregora1f013e2008-11-07 22:36:19 +00003708/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003709/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003710/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003711/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003712/// (which may or may not be the same type as the type that the
3713/// conversion function produces).
3714void
3715Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003716 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003717 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003718 Expr *From, QualType ToType,
3719 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003720 assert(!Conversion->getDescribedFunctionTemplate() &&
3721 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003722 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003723 if (!CandidateSet.isNewCandidate(Conversion))
3724 return;
3725
Douglas Gregor27381f32009-11-23 12:27:39 +00003726 // Overload resolution is always an unevaluated context.
3727 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3728
Douglas Gregora1f013e2008-11-07 22:36:19 +00003729 // Add this candidate
3730 CandidateSet.push_back(OverloadCandidate());
3731 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003732 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003733 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003734 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003735 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003736 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003737 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003738 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003739
Douglas Gregor436424c2008-11-18 23:14:02 +00003740 // Determine the implicit conversion sequence for the implicit
3741 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00003742 Candidate.Viable = true;
3743 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00003744 Candidate.Conversions[0]
3745 = TryObjectArgumentInitialization(From->getType(), Conversion,
3746 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00003747 // Conversion functions to a different type in the base class is visible in
3748 // the derived class. So, a derived to base conversion should not participate
3749 // in overload resolution.
3750 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
3751 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00003752 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003753 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003754 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003755 return;
3756 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003757
3758 // We won't go through a user-define type conversion function to convert a
3759 // derived to base as such conversions are given Conversion Rank. They only
3760 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3761 QualType FromCanon
3762 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3763 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3764 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3765 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003766 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003767 return;
3768 }
3769
Douglas Gregora1f013e2008-11-07 22:36:19 +00003770 // To determine what the conversion from the result of calling the
3771 // conversion function to the type we're eventually trying to
3772 // convert to (ToType), we need to synthesize a call to the
3773 // conversion function and attempt copy initialization from it. This
3774 // makes sure that we get the right semantics with respect to
3775 // lvalues/rvalues and the type. Fortunately, we can allocate this
3776 // call on the stack and we don't need its arguments to be
3777 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003778 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003779 From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00003780 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
3781 Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00003782 CastExpr::CK_FunctionToPointerDecay,
John McCallcf142162010-08-07 06:22:56 +00003783 &ConversionRef, ImplicitCastExpr::RValue);
Mike Stump11289f42009-09-09 15:08:12 +00003784
3785 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003786 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3787 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00003788 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003789 Conversion->getConversionType().getNonLValueExprType(Context),
Douglas Gregore8f080122009-11-17 21:16:22 +00003790 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003791 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003792 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003793 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003794 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003795
John McCall0d1da222010-01-12 00:44:57 +00003796 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003797 case ImplicitConversionSequence::StandardConversion:
3798 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003799
3800 // C++ [over.ics.user]p3:
3801 // If the user-defined conversion is specified by a specialization of a
3802 // conversion function template, the second standard conversion sequence
3803 // shall have exact match rank.
3804 if (Conversion->getPrimaryTemplate() &&
3805 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3806 Candidate.Viable = false;
3807 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3808 }
3809
Douglas Gregora1f013e2008-11-07 22:36:19 +00003810 break;
3811
3812 case ImplicitConversionSequence::BadConversion:
3813 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003814 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003815 break;
3816
3817 default:
Mike Stump11289f42009-09-09 15:08:12 +00003818 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003819 "Can only end up with a standard conversion sequence or failure");
3820 }
3821}
3822
Douglas Gregor05155d82009-08-21 23:19:43 +00003823/// \brief Adds a conversion function template specialization
3824/// candidate to the overload set, using template argument deduction
3825/// to deduce the template arguments of the conversion function
3826/// template from the type that we are converting to (C++
3827/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003828void
Douglas Gregor05155d82009-08-21 23:19:43 +00003829Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003830 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003831 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003832 Expr *From, QualType ToType,
3833 OverloadCandidateSet &CandidateSet) {
3834 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3835 "Only conversion function templates permitted here");
3836
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003837 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3838 return;
3839
John McCallbc077cf2010-02-08 23:07:23 +00003840 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003841 CXXConversionDecl *Specialization = 0;
3842 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003843 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003844 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003845 CandidateSet.push_back(OverloadCandidate());
3846 OverloadCandidate &Candidate = CandidateSet.back();
3847 Candidate.FoundDecl = FoundDecl;
3848 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3849 Candidate.Viable = false;
3850 Candidate.FailureKind = ovl_fail_bad_deduction;
3851 Candidate.IsSurrogate = false;
3852 Candidate.IgnoreObjectArgument = false;
3853 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3854 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00003855 return;
3856 }
Mike Stump11289f42009-09-09 15:08:12 +00003857
Douglas Gregor05155d82009-08-21 23:19:43 +00003858 // Add the conversion function template specialization produced by
3859 // template argument deduction as a candidate.
3860 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003861 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00003862 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003863}
3864
Douglas Gregorab7897a2008-11-19 22:57:39 +00003865/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3866/// converts the given @c Object to a function pointer via the
3867/// conversion function @c Conversion, and then attempts to call it
3868/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3869/// the type of function that we'll eventually be calling.
3870void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003871 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003872 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003873 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00003874 QualType ObjectType,
3875 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00003876 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003877 if (!CandidateSet.isNewCandidate(Conversion))
3878 return;
3879
Douglas Gregor27381f32009-11-23 12:27:39 +00003880 // Overload resolution is always an unevaluated context.
3881 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3882
Douglas Gregorab7897a2008-11-19 22:57:39 +00003883 CandidateSet.push_back(OverloadCandidate());
3884 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003885 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003886 Candidate.Function = 0;
3887 Candidate.Surrogate = Conversion;
3888 Candidate.Viable = true;
3889 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003890 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003891 Candidate.Conversions.resize(NumArgs + 1);
3892
3893 // Determine the implicit conversion sequence for the implicit
3894 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003895 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00003896 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003897 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003898 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003899 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00003900 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003901 return;
3902 }
3903
3904 // The first conversion is actually a user-defined conversion whose
3905 // first conversion is ObjectInit's standard conversion (which is
3906 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00003907 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003908 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003909 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003910 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00003911 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00003912 = Candidate.Conversions[0].UserDefined.Before;
3913 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3914
Mike Stump11289f42009-09-09 15:08:12 +00003915 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00003916 unsigned NumArgsInProto = Proto->getNumArgs();
3917
3918 // (C++ 13.3.2p2): A candidate function having fewer than m
3919 // parameters is viable only if it has an ellipsis in its parameter
3920 // list (8.3.5).
3921 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3922 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003923 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003924 return;
3925 }
3926
3927 // Function types don't have any default arguments, so just check if
3928 // we have enough arguments.
3929 if (NumArgs < NumArgsInProto) {
3930 // Not enough arguments.
3931 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003932 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003933 return;
3934 }
3935
3936 // Determine the implicit conversion sequences for each of the
3937 // arguments.
3938 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3939 if (ArgIdx < NumArgsInProto) {
3940 // (C++ 13.3.2p3): for F to be a viable function, there shall
3941 // exist for each argument an implicit conversion sequence
3942 // (13.3.3.1) that converts that argument to the corresponding
3943 // parameter of F.
3944 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003945 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003946 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003947 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00003948 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00003949 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003950 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003951 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003952 break;
3953 }
3954 } else {
3955 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3956 // argument for which there is no corresponding parameter is
3957 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003958 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003959 }
3960 }
3961}
3962
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003963/// \brief Add overload candidates for overloaded operators that are
3964/// member functions.
3965///
3966/// Add the overloaded operator candidates that are member functions
3967/// for the operator Op that was used in an operator expression such
3968/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3969/// CandidateSet will store the added overload candidates. (C++
3970/// [over.match.oper]).
3971void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3972 SourceLocation OpLoc,
3973 Expr **Args, unsigned NumArgs,
3974 OverloadCandidateSet& CandidateSet,
3975 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003976 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3977
3978 // C++ [over.match.oper]p3:
3979 // For a unary operator @ with an operand of a type whose
3980 // cv-unqualified version is T1, and for a binary operator @ with
3981 // a left operand of a type whose cv-unqualified version is T1 and
3982 // a right operand of a type whose cv-unqualified version is T2,
3983 // three sets of candidate functions, designated member
3984 // candidates, non-member candidates and built-in candidates, are
3985 // constructed as follows:
3986 QualType T1 = Args[0]->getType();
3987 QualType T2;
3988 if (NumArgs > 1)
3989 T2 = Args[1]->getType();
3990
3991 // -- If T1 is a class type, the set of member candidates is the
3992 // result of the qualified lookup of T1::operator@
3993 // (13.3.1.1.1); otherwise, the set of member candidates is
3994 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003995 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003996 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003997 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003998 return;
Mike Stump11289f42009-09-09 15:08:12 +00003999
John McCall27b18f82009-11-17 02:14:36 +00004000 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4001 LookupQualifiedName(Operators, T1Rec->getDecl());
4002 Operators.suppressDiagnostics();
4003
Mike Stump11289f42009-09-09 15:08:12 +00004004 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004005 OperEnd = Operators.end();
4006 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004007 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004008 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00004009 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004010 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004011 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004012}
4013
Douglas Gregora11693b2008-11-12 17:17:38 +00004014/// AddBuiltinCandidate - Add a candidate for a built-in
4015/// operator. ResultTy and ParamTys are the result and parameter types
4016/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004017/// arguments being passed to the candidate. IsAssignmentOperator
4018/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004019/// operator. NumContextualBoolArguments is the number of arguments
4020/// (at the beginning of the argument list) that will be contextually
4021/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004022void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004023 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004024 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004025 bool IsAssignmentOperator,
4026 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004027 // Overload resolution is always an unevaluated context.
4028 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
4029
Douglas Gregora11693b2008-11-12 17:17:38 +00004030 // Add this candidate
4031 CandidateSet.push_back(OverloadCandidate());
4032 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004033 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004034 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004035 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004036 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004037 Candidate.BuiltinTypes.ResultTy = ResultTy;
4038 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4039 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4040
4041 // Determine the implicit conversion sequences for each of the
4042 // arguments.
4043 Candidate.Viable = true;
4044 Candidate.Conversions.resize(NumArgs);
4045 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004046 // C++ [over.match.oper]p4:
4047 // For the built-in assignment operators, conversions of the
4048 // left operand are restricted as follows:
4049 // -- no temporaries are introduced to hold the left operand, and
4050 // -- no user-defined conversions are applied to the left
4051 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004052 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004053 //
4054 // We block these conversions by turning off user-defined
4055 // conversions, since that is the only way that initialization of
4056 // a reference to a non-class type can occur from something that
4057 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004058 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004059 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004060 "Contextual conversion to bool requires bool type");
4061 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
4062 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004063 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004064 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004065 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00004066 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004067 }
John McCall0d1da222010-01-12 00:44:57 +00004068 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004069 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004070 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004071 break;
4072 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004073 }
4074}
4075
4076/// BuiltinCandidateTypeSet - A set of types that will be used for the
4077/// candidate operator functions for built-in operators (C++
4078/// [over.built]). The types are separated into pointer types and
4079/// enumeration types.
4080class BuiltinCandidateTypeSet {
4081 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004082 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004083
4084 /// PointerTypes - The set of pointer types that will be used in the
4085 /// built-in candidates.
4086 TypeSet PointerTypes;
4087
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004088 /// MemberPointerTypes - The set of member pointer types that will be
4089 /// used in the built-in candidates.
4090 TypeSet MemberPointerTypes;
4091
Douglas Gregora11693b2008-11-12 17:17:38 +00004092 /// EnumerationTypes - The set of enumeration types that will be
4093 /// used in the built-in candidates.
4094 TypeSet EnumerationTypes;
4095
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004096 /// \brief The set of vector types that will be used in the built-in
4097 /// candidates.
4098 TypeSet VectorTypes;
4099
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004100 /// Sema - The semantic analysis instance where we are building the
4101 /// candidate type set.
4102 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004103
Douglas Gregora11693b2008-11-12 17:17:38 +00004104 /// Context - The AST context in which we will build the type sets.
4105 ASTContext &Context;
4106
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004107 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4108 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004109 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004110
4111public:
4112 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004113 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004114
Mike Stump11289f42009-09-09 15:08:12 +00004115 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004116 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004117
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004118 void AddTypesConvertedFrom(QualType Ty,
4119 SourceLocation Loc,
4120 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004121 bool AllowExplicitConversions,
4122 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004123
4124 /// pointer_begin - First pointer type found;
4125 iterator pointer_begin() { return PointerTypes.begin(); }
4126
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004127 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004128 iterator pointer_end() { return PointerTypes.end(); }
4129
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004130 /// member_pointer_begin - First member pointer type found;
4131 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4132
4133 /// member_pointer_end - Past the last member pointer type found;
4134 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4135
Douglas Gregora11693b2008-11-12 17:17:38 +00004136 /// enumeration_begin - First enumeration type found;
4137 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4138
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004139 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004140 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004141
4142 iterator vector_begin() { return VectorTypes.begin(); }
4143 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregora11693b2008-11-12 17:17:38 +00004144};
4145
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004146/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004147/// the set of pointer types along with any more-qualified variants of
4148/// that type. For example, if @p Ty is "int const *", this routine
4149/// will add "int const *", "int const volatile *", "int const
4150/// restrict *", and "int const volatile restrict *" to the set of
4151/// pointer types. Returns true if the add of @p Ty itself succeeded,
4152/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004153///
4154/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004155bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004156BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4157 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004158
Douglas Gregora11693b2008-11-12 17:17:38 +00004159 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004160 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004161 return false;
4162
John McCall8ccfcb52009-09-24 19:53:00 +00004163 const PointerType *PointerTy = Ty->getAs<PointerType>();
4164 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00004165
John McCall8ccfcb52009-09-24 19:53:00 +00004166 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004167 // Don't add qualified variants of arrays. For one, they're not allowed
4168 // (the qualifier would sink to the element type), and for another, the
4169 // only overload situation where it matters is subscript or pointer +- int,
4170 // and those shouldn't have qualifier variants anyway.
4171 if (PointeeTy->isArrayType())
4172 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004173 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00004174 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00004175 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004176 bool hasVolatile = VisibleQuals.hasVolatile();
4177 bool hasRestrict = VisibleQuals.hasRestrict();
4178
John McCall8ccfcb52009-09-24 19:53:00 +00004179 // Iterate through all strict supersets of BaseCVR.
4180 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4181 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004182 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4183 // in the types.
4184 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4185 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00004186 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4187 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00004188 }
4189
4190 return true;
4191}
4192
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004193/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4194/// to the set of pointer types along with any more-qualified variants of
4195/// that type. For example, if @p Ty is "int const *", this routine
4196/// will add "int const *", "int const volatile *", "int const
4197/// restrict *", and "int const volatile restrict *" to the set of
4198/// pointer types. Returns true if the add of @p Ty itself succeeded,
4199/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004200///
4201/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004202bool
4203BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4204 QualType Ty) {
4205 // Insert this type.
4206 if (!MemberPointerTypes.insert(Ty))
4207 return false;
4208
John McCall8ccfcb52009-09-24 19:53:00 +00004209 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4210 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004211
John McCall8ccfcb52009-09-24 19:53:00 +00004212 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004213 // Don't add qualified variants of arrays. For one, they're not allowed
4214 // (the qualifier would sink to the element type), and for another, the
4215 // only overload situation where it matters is subscript or pointer +- int,
4216 // and those shouldn't have qualifier variants anyway.
4217 if (PointeeTy->isArrayType())
4218 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004219 const Type *ClassTy = PointerTy->getClass();
4220
4221 // Iterate through all strict supersets of the pointee type's CVR
4222 // qualifiers.
4223 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4224 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4225 if ((CVR | BaseCVR) != CVR) continue;
4226
4227 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4228 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004229 }
4230
4231 return true;
4232}
4233
Douglas Gregora11693b2008-11-12 17:17:38 +00004234/// AddTypesConvertedFrom - Add each of the types to which the type @p
4235/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004236/// primarily interested in pointer types and enumeration types. We also
4237/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004238/// AllowUserConversions is true if we should look at the conversion
4239/// functions of a class type, and AllowExplicitConversions if we
4240/// should also include the explicit conversion functions of a class
4241/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004242void
Douglas Gregor5fb53972009-01-14 15:45:31 +00004243BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004244 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004245 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004246 bool AllowExplicitConversions,
4247 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004248 // Only deal with canonical types.
4249 Ty = Context.getCanonicalType(Ty);
4250
4251 // Look through reference types; they aren't part of the type of an
4252 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004253 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00004254 Ty = RefTy->getPointeeType();
4255
4256 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004257 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00004258
Sebastian Redl65ae2002009-11-05 16:36:20 +00004259 // If we're dealing with an array type, decay to the pointer.
4260 if (Ty->isArrayType())
4261 Ty = SemaRef.Context.getArrayDecayedType(Ty);
4262
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004263 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004264 QualType PointeeTy = PointerTy->getPointeeType();
4265
4266 // Insert our type, and its more-qualified variants, into the set
4267 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004268 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00004269 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004270 } else if (Ty->isMemberPointerType()) {
4271 // Member pointers are far easier, since the pointee can't be converted.
4272 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4273 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00004274 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00004275 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004276 } else if (Ty->isVectorType()) {
4277 VectorTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004278 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004279 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004280 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004281 // No conversion functions in incomplete types.
4282 return;
4283 }
Mike Stump11289f42009-09-09 15:08:12 +00004284
Douglas Gregora11693b2008-11-12 17:17:38 +00004285 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00004286 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00004287 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00004288 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004289 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004290 NamedDecl *D = I.getDecl();
4291 if (isa<UsingShadowDecl>(D))
4292 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004293
Mike Stump11289f42009-09-09 15:08:12 +00004294 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00004295 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00004296 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00004297 continue;
4298
John McCallda4458e2010-03-31 01:36:47 +00004299 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004300 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004301 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004302 VisibleQuals);
4303 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004304 }
4305 }
4306 }
4307}
4308
Douglas Gregor84605ae2009-08-24 13:43:27 +00004309/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4310/// the volatile- and non-volatile-qualified assignment operators for the
4311/// given type to the candidate set.
4312static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4313 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004314 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004315 unsigned NumArgs,
4316 OverloadCandidateSet &CandidateSet) {
4317 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004318
Douglas Gregor84605ae2009-08-24 13:43:27 +00004319 // T& operator=(T&, T)
4320 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4321 ParamTypes[1] = T;
4322 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4323 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004324
Douglas Gregor84605ae2009-08-24 13:43:27 +00004325 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4326 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004327 ParamTypes[0]
4328 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004329 ParamTypes[1] = T;
4330 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004331 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004332 }
4333}
Mike Stump11289f42009-09-09 15:08:12 +00004334
Sebastian Redl1054fae2009-10-25 17:03:50 +00004335/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4336/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004337static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4338 Qualifiers VRQuals;
4339 const RecordType *TyRec;
4340 if (const MemberPointerType *RHSMPType =
4341 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004342 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004343 else
4344 TyRec = ArgExpr->getType()->getAs<RecordType>();
4345 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004346 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004347 VRQuals.addVolatile();
4348 VRQuals.addRestrict();
4349 return VRQuals;
4350 }
4351
4352 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004353 if (!ClassDecl->hasDefinition())
4354 return VRQuals;
4355
John McCallad371252010-01-20 00:46:10 +00004356 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004357 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004358
John McCallad371252010-01-20 00:46:10 +00004359 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004360 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004361 NamedDecl *D = I.getDecl();
4362 if (isa<UsingShadowDecl>(D))
4363 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4364 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004365 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4366 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4367 CanTy = ResTypeRef->getPointeeType();
4368 // Need to go down the pointer/mempointer chain and add qualifiers
4369 // as see them.
4370 bool done = false;
4371 while (!done) {
4372 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4373 CanTy = ResTypePtr->getPointeeType();
4374 else if (const MemberPointerType *ResTypeMPtr =
4375 CanTy->getAs<MemberPointerType>())
4376 CanTy = ResTypeMPtr->getPointeeType();
4377 else
4378 done = true;
4379 if (CanTy.isVolatileQualified())
4380 VRQuals.addVolatile();
4381 if (CanTy.isRestrictQualified())
4382 VRQuals.addRestrict();
4383 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4384 return VRQuals;
4385 }
4386 }
4387 }
4388 return VRQuals;
4389}
4390
Douglas Gregord08452f2008-11-19 15:42:04 +00004391/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4392/// operator overloads to the candidate set (C++ [over.built]), based
4393/// on the operator @p Op and the arguments given. For example, if the
4394/// operator is a binary '+', this routine might add "int
4395/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00004396void
Mike Stump11289f42009-09-09 15:08:12 +00004397Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004398 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00004399 Expr **Args, unsigned NumArgs,
4400 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004401 // The set of "promoted arithmetic types", which are the arithmetic
4402 // types are that preserved by promotion (C++ [over.built]p2). Note
4403 // that the first few of these types are the promoted integral
4404 // types; these types need to be first.
4405 // FIXME: What about complex?
4406 const unsigned FirstIntegralType = 0;
4407 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00004408 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00004409 LastPromotedIntegralType = 13;
4410 const unsigned FirstPromotedArithmeticType = 7,
4411 LastPromotedArithmeticType = 16;
4412 const unsigned NumArithmeticTypes = 16;
4413 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00004414 Context.BoolTy, Context.CharTy, Context.WCharTy,
4415// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00004416 Context.SignedCharTy, Context.ShortTy,
4417 Context.UnsignedCharTy, Context.UnsignedShortTy,
4418 Context.IntTy, Context.LongTy, Context.LongLongTy,
4419 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
4420 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
4421 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00004422 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
4423 "Invalid first promoted integral type");
4424 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4425 == Context.UnsignedLongLongTy &&
4426 "Invalid last promoted integral type");
4427 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
4428 "Invalid first promoted arithmetic type");
4429 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4430 == Context.LongDoubleTy &&
4431 "Invalid last promoted arithmetic type");
4432
Douglas Gregora11693b2008-11-12 17:17:38 +00004433 // Find all of the types that the arguments can convert to, but only
4434 // if the operator we're looking at has built-in operator candidates
4435 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004436 Qualifiers VisibleTypeConversionsQuals;
4437 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004438 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4439 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4440
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004441 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004442 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4443 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4444 OpLoc,
4445 true,
4446 (Op == OO_Exclaim ||
4447 Op == OO_AmpAmp ||
4448 Op == OO_PipePipe),
4449 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004450
4451 bool isComparison = false;
4452 switch (Op) {
4453 case OO_None:
4454 case NUM_OVERLOADED_OPERATORS:
4455 assert(false && "Expected an overloaded operator");
4456 break;
4457
Douglas Gregord08452f2008-11-19 15:42:04 +00004458 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00004459 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00004460 goto UnaryStar;
4461 else
4462 goto BinaryStar;
4463 break;
4464
4465 case OO_Plus: // '+' is either unary or binary
4466 if (NumArgs == 1)
4467 goto UnaryPlus;
4468 else
4469 goto BinaryPlus;
4470 break;
4471
4472 case OO_Minus: // '-' is either unary or binary
4473 if (NumArgs == 1)
4474 goto UnaryMinus;
4475 else
4476 goto BinaryMinus;
4477 break;
4478
4479 case OO_Amp: // '&' is either unary or binary
4480 if (NumArgs == 1)
4481 goto UnaryAmp;
4482 else
4483 goto BinaryAmp;
4484
4485 case OO_PlusPlus:
4486 case OO_MinusMinus:
4487 // C++ [over.built]p3:
4488 //
4489 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4490 // is either volatile or empty, there exist candidate operator
4491 // functions of the form
4492 //
4493 // VQ T& operator++(VQ T&);
4494 // T operator++(VQ T&, int);
4495 //
4496 // C++ [over.built]p4:
4497 //
4498 // For every pair (T, VQ), where T is an arithmetic type other
4499 // than bool, and VQ is either volatile or empty, there exist
4500 // candidate operator functions of the form
4501 //
4502 // VQ T& operator--(VQ T&);
4503 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00004504 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004505 Arith < NumArithmeticTypes; ++Arith) {
4506 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00004507 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004508 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00004509
4510 // Non-volatile version.
4511 if (NumArgs == 1)
4512 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4513 else
4514 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004515 // heuristic to reduce number of builtin candidates in the set.
4516 // Add volatile version only if there are conversions to a volatile type.
4517 if (VisibleTypeConversionsQuals.hasVolatile()) {
4518 // Volatile version
4519 ParamTypes[0]
4520 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4521 if (NumArgs == 1)
4522 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4523 else
4524 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4525 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004526 }
4527
4528 // C++ [over.built]p5:
4529 //
4530 // For every pair (T, VQ), where T is a cv-qualified or
4531 // cv-unqualified object type, and VQ is either volatile or
4532 // empty, there exist candidate operator functions of the form
4533 //
4534 // T*VQ& operator++(T*VQ&);
4535 // T*VQ& operator--(T*VQ&);
4536 // T* operator++(T*VQ&, int);
4537 // T* operator--(T*VQ&, int);
4538 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4539 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4540 // Skip pointer types that aren't pointers to object types.
Eli Friedmana170cd62010-08-05 02:49:48 +00004541 if (!(*Ptr)->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00004542 continue;
4543
Mike Stump11289f42009-09-09 15:08:12 +00004544 QualType ParamTypes[2] = {
4545 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00004546 };
Mike Stump11289f42009-09-09 15:08:12 +00004547
Douglas Gregord08452f2008-11-19 15:42:04 +00004548 // Without volatile
4549 if (NumArgs == 1)
4550 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4551 else
4552 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4553
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004554 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4555 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004556 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00004557 ParamTypes[0]
4558 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00004559 if (NumArgs == 1)
4560 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4561 else
4562 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4563 }
4564 }
4565 break;
4566
4567 UnaryStar:
4568 // C++ [over.built]p6:
4569 // For every cv-qualified or cv-unqualified object type T, there
4570 // exist candidate operator functions of the form
4571 //
4572 // T& operator*(T*);
4573 //
4574 // C++ [over.built]p7:
4575 // For every function type T, there exist candidate operator
4576 // functions of the form
4577 // T& operator*(T*);
4578 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4579 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4580 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004581 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004582 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00004583 &ParamTy, Args, 1, CandidateSet);
4584 }
4585 break;
4586
4587 UnaryPlus:
4588 // C++ [over.built]p8:
4589 // For every type T, there exist candidate operator functions of
4590 // the form
4591 //
4592 // T* operator+(T*);
4593 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4594 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4595 QualType ParamTy = *Ptr;
4596 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4597 }
Mike Stump11289f42009-09-09 15:08:12 +00004598
Douglas Gregord08452f2008-11-19 15:42:04 +00004599 // Fall through
4600
4601 UnaryMinus:
4602 // C++ [over.built]p9:
4603 // For every promoted arithmetic type T, there exist candidate
4604 // operator functions of the form
4605 //
4606 // T operator+(T);
4607 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00004608 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004609 Arith < LastPromotedArithmeticType; ++Arith) {
4610 QualType ArithTy = ArithmeticTypes[Arith];
4611 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4612 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004613
4614 // Extension: We also add these operators for vector types.
4615 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4616 VecEnd = CandidateTypes.vector_end();
4617 Vec != VecEnd; ++Vec) {
4618 QualType VecTy = *Vec;
4619 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4620 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004621 break;
4622
4623 case OO_Tilde:
4624 // C++ [over.built]p10:
4625 // For every promoted integral type T, there exist candidate
4626 // operator functions of the form
4627 //
4628 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00004629 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004630 Int < LastPromotedIntegralType; ++Int) {
4631 QualType IntTy = ArithmeticTypes[Int];
4632 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4633 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004634
4635 // Extension: We also add this operator for vector types.
4636 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4637 VecEnd = CandidateTypes.vector_end();
4638 Vec != VecEnd; ++Vec) {
4639 QualType VecTy = *Vec;
4640 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4641 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004642 break;
4643
Douglas Gregora11693b2008-11-12 17:17:38 +00004644 case OO_New:
4645 case OO_Delete:
4646 case OO_Array_New:
4647 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00004648 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00004649 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00004650 break;
4651
4652 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00004653 UnaryAmp:
4654 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00004655 // C++ [over.match.oper]p3:
4656 // -- For the operator ',', the unary operator '&', or the
4657 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00004658 break;
4659
Douglas Gregor84605ae2009-08-24 13:43:27 +00004660 case OO_EqualEqual:
4661 case OO_ExclaimEqual:
4662 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00004663 // For every pointer to member type T, there exist candidate operator
4664 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00004665 //
4666 // bool operator==(T,T);
4667 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00004668 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00004669 MemPtr = CandidateTypes.member_pointer_begin(),
4670 MemPtrEnd = CandidateTypes.member_pointer_end();
4671 MemPtr != MemPtrEnd;
4672 ++MemPtr) {
4673 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4674 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4675 }
Mike Stump11289f42009-09-09 15:08:12 +00004676
Douglas Gregor84605ae2009-08-24 13:43:27 +00004677 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004678
Douglas Gregora11693b2008-11-12 17:17:38 +00004679 case OO_Less:
4680 case OO_Greater:
4681 case OO_LessEqual:
4682 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004683 // C++ [over.built]p15:
4684 //
4685 // For every pointer or enumeration type T, there exist
4686 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004687 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004688 // bool operator<(T, T);
4689 // bool operator>(T, T);
4690 // bool operator<=(T, T);
4691 // bool operator>=(T, T);
4692 // bool operator==(T, T);
4693 // bool operator!=(T, T);
4694 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4695 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4696 QualType ParamTypes[2] = { *Ptr, *Ptr };
4697 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4698 }
Mike Stump11289f42009-09-09 15:08:12 +00004699 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00004700 = CandidateTypes.enumeration_begin();
4701 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4702 QualType ParamTypes[2] = { *Enum, *Enum };
4703 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4704 }
4705
4706 // Fall through.
4707 isComparison = true;
4708
Douglas Gregord08452f2008-11-19 15:42:04 +00004709 BinaryPlus:
4710 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00004711 if (!isComparison) {
4712 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4713
4714 // C++ [over.built]p13:
4715 //
4716 // For every cv-qualified or cv-unqualified object type T
4717 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004718 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004719 // T* operator+(T*, ptrdiff_t);
4720 // T& operator[](T*, ptrdiff_t); [BELOW]
4721 // T* operator-(T*, ptrdiff_t);
4722 // T* operator+(ptrdiff_t, T*);
4723 // T& operator[](ptrdiff_t, T*); [BELOW]
4724 //
4725 // C++ [over.built]p14:
4726 //
4727 // For every T, where T is a pointer to object type, there
4728 // exist candidate operator functions of the form
4729 //
4730 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00004731 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00004732 = CandidateTypes.pointer_begin();
4733 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4734 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4735
4736 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4737 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4738
4739 if (Op == OO_Plus) {
4740 // T* operator+(ptrdiff_t, T*);
4741 ParamTypes[0] = ParamTypes[1];
4742 ParamTypes[1] = *Ptr;
4743 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4744 } else {
4745 // ptrdiff_t operator-(T, T);
4746 ParamTypes[1] = *Ptr;
4747 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4748 Args, 2, CandidateSet);
4749 }
4750 }
4751 }
4752 // Fall through
4753
Douglas Gregora11693b2008-11-12 17:17:38 +00004754 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00004755 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00004756 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00004757 // C++ [over.built]p12:
4758 //
4759 // For every pair of promoted arithmetic types L and R, there
4760 // exist candidate operator functions of the form
4761 //
4762 // LR operator*(L, R);
4763 // LR operator/(L, R);
4764 // LR operator+(L, R);
4765 // LR operator-(L, R);
4766 // bool operator<(L, R);
4767 // bool operator>(L, R);
4768 // bool operator<=(L, R);
4769 // bool operator>=(L, R);
4770 // bool operator==(L, R);
4771 // bool operator!=(L, R);
4772 //
4773 // where LR is the result of the usual arithmetic conversions
4774 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004775 //
4776 // C++ [over.built]p24:
4777 //
4778 // For every pair of promoted arithmetic types L and R, there exist
4779 // candidate operator functions of the form
4780 //
4781 // LR operator?(bool, L, R);
4782 //
4783 // where LR is the result of the usual arithmetic conversions
4784 // between types L and R.
4785 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004786 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004787 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004788 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004789 Right < LastPromotedArithmeticType; ++Right) {
4790 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004791 QualType Result
4792 = isComparison
4793 ? Context.BoolTy
4794 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004795 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4796 }
4797 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004798
4799 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
4800 // conditional operator for vector types.
4801 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4802 Vec1End = CandidateTypes.vector_end();
4803 Vec1 != Vec1End; ++Vec1)
4804 for (BuiltinCandidateTypeSet::iterator
4805 Vec2 = CandidateTypes.vector_begin(),
4806 Vec2End = CandidateTypes.vector_end();
4807 Vec2 != Vec2End; ++Vec2) {
4808 QualType LandR[2] = { *Vec1, *Vec2 };
4809 QualType Result;
4810 if (isComparison)
4811 Result = Context.BoolTy;
4812 else {
4813 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
4814 Result = *Vec1;
4815 else
4816 Result = *Vec2;
4817 }
4818
4819 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4820 }
4821
Douglas Gregora11693b2008-11-12 17:17:38 +00004822 break;
4823
4824 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00004825 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00004826 case OO_Caret:
4827 case OO_Pipe:
4828 case OO_LessLess:
4829 case OO_GreaterGreater:
4830 // C++ [over.built]p17:
4831 //
4832 // For every pair of promoted integral types L and R, there
4833 // exist candidate operator functions of the form
4834 //
4835 // LR operator%(L, R);
4836 // LR operator&(L, R);
4837 // LR operator^(L, R);
4838 // LR operator|(L, R);
4839 // L operator<<(L, R);
4840 // L operator>>(L, R);
4841 //
4842 // where LR is the result of the usual arithmetic conversions
4843 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00004844 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004845 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004846 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004847 Right < LastPromotedIntegralType; ++Right) {
4848 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4849 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4850 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004851 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004852 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4853 }
4854 }
4855 break;
4856
4857 case OO_Equal:
4858 // C++ [over.built]p20:
4859 //
4860 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00004861 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00004862 // empty, there exist candidate operator functions of the form
4863 //
4864 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004865 for (BuiltinCandidateTypeSet::iterator
4866 Enum = CandidateTypes.enumeration_begin(),
4867 EnumEnd = CandidateTypes.enumeration_end();
4868 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00004869 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004870 CandidateSet);
4871 for (BuiltinCandidateTypeSet::iterator
4872 MemPtr = CandidateTypes.member_pointer_begin(),
4873 MemPtrEnd = CandidateTypes.member_pointer_end();
4874 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00004875 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004876 CandidateSet);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004877
4878 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00004879
4880 case OO_PlusEqual:
4881 case OO_MinusEqual:
4882 // C++ [over.built]p19:
4883 //
4884 // For every pair (T, VQ), where T is any type and VQ is either
4885 // volatile or empty, there exist candidate operator functions
4886 // of the form
4887 //
4888 // T*VQ& operator=(T*VQ&, T*);
4889 //
4890 // C++ [over.built]p21:
4891 //
4892 // For every pair (T, VQ), where T is a cv-qualified or
4893 // cv-unqualified object type and VQ is either volatile or
4894 // empty, there exist candidate operator functions of the form
4895 //
4896 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4897 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4898 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4899 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4900 QualType ParamTypes[2];
4901 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4902
4903 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004904 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004905 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4906 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004907
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004908 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4909 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004910 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00004911 ParamTypes[0]
4912 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00004913 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4914 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00004915 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004916 }
4917 // Fall through.
4918
4919 case OO_StarEqual:
4920 case OO_SlashEqual:
4921 // C++ [over.built]p18:
4922 //
4923 // For every triple (L, VQ, R), where L is an arithmetic type,
4924 // VQ is either volatile or empty, and R is a promoted
4925 // arithmetic type, there exist candidate operator functions of
4926 // the form
4927 //
4928 // VQ L& operator=(VQ L&, R);
4929 // VQ L& operator*=(VQ L&, R);
4930 // VQ L& operator/=(VQ L&, R);
4931 // VQ L& operator+=(VQ L&, R);
4932 // VQ L& operator-=(VQ L&, R);
4933 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004934 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004935 Right < LastPromotedArithmeticType; ++Right) {
4936 QualType ParamTypes[2];
4937 ParamTypes[1] = ArithmeticTypes[Right];
4938
4939 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004940 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004941 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4942 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004943
4944 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004945 if (VisibleTypeConversionsQuals.hasVolatile()) {
4946 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4947 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4948 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4949 /*IsAssigmentOperator=*/Op == OO_Equal);
4950 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004951 }
4952 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004953
4954 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
4955 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4956 Vec1End = CandidateTypes.vector_end();
4957 Vec1 != Vec1End; ++Vec1)
4958 for (BuiltinCandidateTypeSet::iterator
4959 Vec2 = CandidateTypes.vector_begin(),
4960 Vec2End = CandidateTypes.vector_end();
4961 Vec2 != Vec2End; ++Vec2) {
4962 QualType ParamTypes[2];
4963 ParamTypes[1] = *Vec2;
4964 // Add this built-in operator as a candidate (VQ is empty).
4965 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
4966 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4967 /*IsAssigmentOperator=*/Op == OO_Equal);
4968
4969 // Add this built-in operator as a candidate (VQ is 'volatile').
4970 if (VisibleTypeConversionsQuals.hasVolatile()) {
4971 ParamTypes[0] = Context.getVolatileType(*Vec1);
4972 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4973 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4974 /*IsAssigmentOperator=*/Op == OO_Equal);
4975 }
4976 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004977 break;
4978
4979 case OO_PercentEqual:
4980 case OO_LessLessEqual:
4981 case OO_GreaterGreaterEqual:
4982 case OO_AmpEqual:
4983 case OO_CaretEqual:
4984 case OO_PipeEqual:
4985 // C++ [over.built]p22:
4986 //
4987 // For every triple (L, VQ, R), where L is an integral type, VQ
4988 // is either volatile or empty, and R is a promoted integral
4989 // type, there exist candidate operator functions of the form
4990 //
4991 // VQ L& operator%=(VQ L&, R);
4992 // VQ L& operator<<=(VQ L&, R);
4993 // VQ L& operator>>=(VQ L&, R);
4994 // VQ L& operator&=(VQ L&, R);
4995 // VQ L& operator^=(VQ L&, R);
4996 // VQ L& operator|=(VQ L&, R);
4997 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004998 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004999 Right < LastPromotedIntegralType; ++Right) {
5000 QualType ParamTypes[2];
5001 ParamTypes[1] = ArithmeticTypes[Right];
5002
5003 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005004 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00005005 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00005006 if (VisibleTypeConversionsQuals.hasVolatile()) {
5007 // Add this built-in operator as a candidate (VQ is 'volatile').
5008 ParamTypes[0] = ArithmeticTypes[Left];
5009 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
5010 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5011 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5012 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005013 }
5014 }
5015 break;
5016
Douglas Gregord08452f2008-11-19 15:42:04 +00005017 case OO_Exclaim: {
5018 // C++ [over.operator]p23:
5019 //
5020 // There also exist candidate operator functions of the form
5021 //
Mike Stump11289f42009-09-09 15:08:12 +00005022 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00005023 // bool operator&&(bool, bool); [BELOW]
5024 // bool operator||(bool, bool); [BELOW]
5025 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00005026 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5027 /*IsAssignmentOperator=*/false,
5028 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00005029 break;
5030 }
5031
Douglas Gregora11693b2008-11-12 17:17:38 +00005032 case OO_AmpAmp:
5033 case OO_PipePipe: {
5034 // C++ [over.operator]p23:
5035 //
5036 // There also exist candidate operator functions of the form
5037 //
Douglas Gregord08452f2008-11-19 15:42:04 +00005038 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00005039 // bool operator&&(bool, bool);
5040 // bool operator||(bool, bool);
5041 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00005042 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5043 /*IsAssignmentOperator=*/false,
5044 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00005045 break;
5046 }
5047
5048 case OO_Subscript:
5049 // C++ [over.built]p13:
5050 //
5051 // For every cv-qualified or cv-unqualified object type T there
5052 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00005053 //
Douglas Gregora11693b2008-11-12 17:17:38 +00005054 // T* operator+(T*, ptrdiff_t); [ABOVE]
5055 // T& operator[](T*, ptrdiff_t);
5056 // T* operator-(T*, ptrdiff_t); [ABOVE]
5057 // T* operator+(ptrdiff_t, T*); [ABOVE]
5058 // T& operator[](ptrdiff_t, T*);
5059 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
5060 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5061 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005062 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005063 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00005064
5065 // T& operator[](T*, ptrdiff_t)
5066 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5067
5068 // T& operator[](ptrdiff_t, T*);
5069 ParamTypes[0] = ParamTypes[1];
5070 ParamTypes[1] = *Ptr;
5071 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005072 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005073 break;
5074
5075 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005076 // C++ [over.built]p11:
5077 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5078 // C1 is the same type as C2 or is a derived class of C2, T is an object
5079 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5080 // there exist candidate operator functions of the form
5081 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5082 // where CV12 is the union of CV1 and CV2.
5083 {
5084 for (BuiltinCandidateTypeSet::iterator Ptr =
5085 CandidateTypes.pointer_begin();
5086 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5087 QualType C1Ty = (*Ptr);
5088 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005089 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005090 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005091 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005092 if (!isa<RecordType>(C1))
5093 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005094 // heuristic to reduce number of builtin candidates in the set.
5095 // Add volatile/restrict version only if there are conversions to a
5096 // volatile/restrict type.
5097 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5098 continue;
5099 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5100 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005101 }
5102 for (BuiltinCandidateTypeSet::iterator
5103 MemPtr = CandidateTypes.member_pointer_begin(),
5104 MemPtrEnd = CandidateTypes.member_pointer_end();
5105 MemPtr != MemPtrEnd; ++MemPtr) {
5106 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5107 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00005108 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005109 if (C1 != C2 && !IsDerivedFrom(C1, C2))
5110 break;
5111 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5112 // build CV12 T&
5113 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005114 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5115 T.isVolatileQualified())
5116 continue;
5117 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5118 T.isRestrictQualified())
5119 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005120 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005121 QualType ResultTy = Context.getLValueReferenceType(T);
5122 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5123 }
5124 }
5125 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005126 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005127
5128 case OO_Conditional:
5129 // Note that we don't consider the first argument, since it has been
5130 // contextually converted to bool long ago. The candidates below are
5131 // therefore added as binary.
5132 //
5133 // C++ [over.built]p24:
5134 // For every type T, where T is a pointer or pointer-to-member type,
5135 // there exist candidate operator functions of the form
5136 //
5137 // T operator?(bool, T, T);
5138 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00005139 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
5140 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
5141 QualType ParamTypes[2] = { *Ptr, *Ptr };
5142 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5143 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005144 for (BuiltinCandidateTypeSet::iterator Ptr =
5145 CandidateTypes.member_pointer_begin(),
5146 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
5147 QualType ParamTypes[2] = { *Ptr, *Ptr };
5148 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5149 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005150 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00005151 }
5152}
5153
Douglas Gregore254f902009-02-04 00:32:51 +00005154/// \brief Add function candidates found via argument-dependent lookup
5155/// to the set of overloading candidates.
5156///
5157/// This routine performs argument-dependent name lookup based on the
5158/// given function name (which may also be an operator name) and adds
5159/// all of the overload candidates found by ADL to the overload
5160/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00005161void
Douglas Gregore254f902009-02-04 00:32:51 +00005162Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00005163 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00005164 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00005165 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005166 OverloadCandidateSet& CandidateSet,
5167 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00005168 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00005169
John McCall91f61fc2010-01-26 06:04:06 +00005170 // FIXME: This approach for uniquing ADL results (and removing
5171 // redundant candidates from the set) relies on pointer-equality,
5172 // which means we need to key off the canonical decl. However,
5173 // always going back to the canonical decl might not get us the
5174 // right set of default arguments. What default arguments are
5175 // we supposed to consider on ADL candidates, anyway?
5176
Douglas Gregorcabea402009-09-22 15:41:20 +00005177 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00005178 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00005179
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005180 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005181 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5182 CandEnd = CandidateSet.end();
5183 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00005184 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00005185 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00005186 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00005187 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00005188 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005189
5190 // For each of the ADL candidates we found, add it to the overload
5191 // set.
John McCall8fe68082010-01-26 07:16:45 +00005192 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00005193 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00005194 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00005195 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00005196 continue;
5197
John McCalla0296f72010-03-19 07:35:19 +00005198 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005199 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005200 } else
John McCall4c4c1df2010-01-26 03:27:55 +00005201 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00005202 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00005203 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00005204 }
Douglas Gregore254f902009-02-04 00:32:51 +00005205}
5206
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005207/// isBetterOverloadCandidate - Determines whether the first overload
5208/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00005209bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005210Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCallbc077cf2010-02-08 23:07:23 +00005211 const OverloadCandidate& Cand2,
5212 SourceLocation Loc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005213 // Define viable functions to be better candidates than non-viable
5214 // functions.
5215 if (!Cand2.Viable)
5216 return Cand1.Viable;
5217 else if (!Cand1.Viable)
5218 return false;
5219
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005220 // C++ [over.match.best]p1:
5221 //
5222 // -- if F is a static member function, ICS1(F) is defined such
5223 // that ICS1(F) is neither better nor worse than ICS1(G) for
5224 // any function G, and, symmetrically, ICS1(G) is neither
5225 // better nor worse than ICS1(F).
5226 unsigned StartArg = 0;
5227 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5228 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005229
Douglas Gregord3cb3562009-07-07 23:38:56 +00005230 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005231 // A viable function F1 is defined to be a better function than another
5232 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00005233 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005234 unsigned NumArgs = Cand1.Conversions.size();
5235 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5236 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005237 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005238 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
5239 Cand2.Conversions[ArgIdx])) {
5240 case ImplicitConversionSequence::Better:
5241 // Cand1 has a better conversion sequence.
5242 HasBetterConversion = true;
5243 break;
5244
5245 case ImplicitConversionSequence::Worse:
5246 // Cand1 can't be better than Cand2.
5247 return false;
5248
5249 case ImplicitConversionSequence::Indistinguishable:
5250 // Do nothing.
5251 break;
5252 }
5253 }
5254
Mike Stump11289f42009-09-09 15:08:12 +00005255 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00005256 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005257 if (HasBetterConversion)
5258 return true;
5259
Mike Stump11289f42009-09-09 15:08:12 +00005260 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00005261 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00005262 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00005263 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5264 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005265
5266 // -- F1 and F2 are function template specializations, and the function
5267 // template for F1 is more specialized than the template for F2
5268 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00005269 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00005270 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5271 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00005272 if (FunctionTemplateDecl *BetterTemplate
5273 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5274 Cand2.Function->getPrimaryTemplate(),
John McCallbc077cf2010-02-08 23:07:23 +00005275 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00005276 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5277 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00005278 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005279
Douglas Gregora1f013e2008-11-07 22:36:19 +00005280 // -- the context is an initialization by user-defined conversion
5281 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5282 // from the return type of F1 to the destination type (i.e.,
5283 // the type of the entity being initialized) is a better
5284 // conversion sequence than the standard conversion sequence
5285 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00005286 if (Cand1.Function && Cand2.Function &&
5287 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00005288 isa<CXXConversionDecl>(Cand2.Function)) {
5289 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
5290 Cand2.FinalConversion)) {
5291 case ImplicitConversionSequence::Better:
5292 // Cand1 has a better conversion sequence.
5293 return true;
5294
5295 case ImplicitConversionSequence::Worse:
5296 // Cand1 can't be better than Cand2.
5297 return false;
5298
5299 case ImplicitConversionSequence::Indistinguishable:
5300 // Do nothing
5301 break;
5302 }
5303 }
5304
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005305 return false;
5306}
5307
Mike Stump11289f42009-09-09 15:08:12 +00005308/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005309/// within an overload candidate set.
5310///
5311/// \param CandidateSet the set of candidate functions.
5312///
5313/// \param Loc the location of the function name (or operator symbol) for
5314/// which overload resolution occurs.
5315///
Mike Stump11289f42009-09-09 15:08:12 +00005316/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005317/// function, Best points to the candidate function found.
5318///
5319/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00005320OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
5321 SourceLocation Loc,
5322 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005323 // Find the best viable function.
5324 Best = CandidateSet.end();
5325 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5326 Cand != CandidateSet.end(); ++Cand) {
5327 if (Cand->Viable) {
John McCallbc077cf2010-02-08 23:07:23 +00005328 if (Best == CandidateSet.end() ||
5329 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005330 Best = Cand;
5331 }
5332 }
5333
5334 // If we didn't find any viable functions, abort.
5335 if (Best == CandidateSet.end())
5336 return OR_No_Viable_Function;
5337
5338 // Make sure that this function is better than every other viable
5339 // function. If not, we have an ambiguity.
5340 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5341 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00005342 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005343 Cand != Best &&
John McCallbc077cf2010-02-08 23:07:23 +00005344 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005345 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005346 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005347 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005348 }
Mike Stump11289f42009-09-09 15:08:12 +00005349
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005350 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00005351 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005352 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005353 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00005354 return OR_Deleted;
5355
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005356 // C++ [basic.def.odr]p2:
5357 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00005358 // when referred to from a potentially-evaluated expression. [Note: this
5359 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005360 // (clause 13), user-defined conversions (12.3.2), allocation function for
5361 // placement new (5.3.4), as well as non-default initialization (8.5).
5362 if (Best->Function)
5363 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005364 return OR_Success;
5365}
5366
John McCall53262c92010-01-12 02:15:36 +00005367namespace {
5368
5369enum OverloadCandidateKind {
5370 oc_function,
5371 oc_method,
5372 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005373 oc_function_template,
5374 oc_method_template,
5375 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00005376 oc_implicit_default_constructor,
5377 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005378 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00005379};
5380
John McCalle1ac8d12010-01-13 00:25:19 +00005381OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5382 FunctionDecl *Fn,
5383 std::string &Description) {
5384 bool isTemplate = false;
5385
5386 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5387 isTemplate = true;
5388 Description = S.getTemplateArgumentBindingsText(
5389 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5390 }
John McCallfd0b2f82010-01-06 09:43:14 +00005391
5392 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00005393 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005394 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005395
John McCall53262c92010-01-12 02:15:36 +00005396 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5397 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005398 }
5399
5400 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5401 // This actually gets spelled 'candidate function' for now, but
5402 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00005403 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005404 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00005405
5406 assert(Meth->isCopyAssignment()
5407 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00005408 return oc_implicit_copy_assignment;
5409 }
5410
John McCalle1ac8d12010-01-13 00:25:19 +00005411 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00005412}
5413
5414} // end anonymous namespace
5415
5416// Notes the location of an overload candidate.
5417void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00005418 std::string FnDesc;
5419 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5420 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5421 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00005422}
5423
John McCall0d1da222010-01-12 00:44:57 +00005424/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5425/// "lead" diagnostic; it will be given two arguments, the source and
5426/// target types of the conversion.
5427void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
5428 SourceLocation CaretLoc,
5429 const PartialDiagnostic &PDiag) {
5430 Diag(CaretLoc, PDiag)
5431 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
5432 for (AmbiguousConversionSequence::const_iterator
5433 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
5434 NoteOverloadCandidate(*I);
5435 }
John McCall12f97bc2010-01-08 04:41:39 +00005436}
5437
John McCall0d1da222010-01-12 00:44:57 +00005438namespace {
5439
John McCall6a61b522010-01-13 09:16:55 +00005440void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5441 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5442 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00005443 assert(Cand->Function && "for now, candidate must be a function");
5444 FunctionDecl *Fn = Cand->Function;
5445
5446 // There's a conversion slot for the object argument if this is a
5447 // non-constructor method. Note that 'I' corresponds the
5448 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00005449 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00005450 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00005451 if (I == 0)
5452 isObjectArgument = true;
5453 else
5454 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00005455 }
5456
John McCalle1ac8d12010-01-13 00:25:19 +00005457 std::string FnDesc;
5458 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5459
John McCall6a61b522010-01-13 09:16:55 +00005460 Expr *FromExpr = Conv.Bad.FromExpr;
5461 QualType FromTy = Conv.Bad.getFromType();
5462 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00005463
John McCallfb7ad0f2010-02-02 02:42:52 +00005464 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00005465 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00005466 Expr *E = FromExpr->IgnoreParens();
5467 if (isa<UnaryOperator>(E))
5468 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00005469 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00005470
5471 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5472 << (unsigned) FnKind << FnDesc
5473 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5474 << ToTy << Name << I+1;
5475 return;
5476 }
5477
John McCall6d174642010-01-23 08:10:49 +00005478 // Do some hand-waving analysis to see if the non-viability is due
5479 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00005480 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5481 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5482 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5483 CToTy = RT->getPointeeType();
5484 else {
5485 // TODO: detect and diagnose the full richness of const mismatches.
5486 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5487 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5488 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5489 }
5490
5491 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5492 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5493 // It is dumb that we have to do this here.
5494 while (isa<ArrayType>(CFromTy))
5495 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5496 while (isa<ArrayType>(CToTy))
5497 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5498
5499 Qualifiers FromQs = CFromTy.getQualifiers();
5500 Qualifiers ToQs = CToTy.getQualifiers();
5501
5502 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5503 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5504 << (unsigned) FnKind << FnDesc
5505 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5506 << FromTy
5507 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5508 << (unsigned) isObjectArgument << I+1;
5509 return;
5510 }
5511
5512 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5513 assert(CVR && "unexpected qualifiers mismatch");
5514
5515 if (isObjectArgument) {
5516 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5517 << (unsigned) FnKind << FnDesc
5518 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5519 << FromTy << (CVR - 1);
5520 } else {
5521 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5522 << (unsigned) FnKind << FnDesc
5523 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5524 << FromTy << (CVR - 1) << I+1;
5525 }
5526 return;
5527 }
5528
John McCall6d174642010-01-23 08:10:49 +00005529 // Diagnose references or pointers to incomplete types differently,
5530 // since it's far from impossible that the incompleteness triggered
5531 // the failure.
5532 QualType TempFromTy = FromTy.getNonReferenceType();
5533 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5534 TempFromTy = PTy->getPointeeType();
5535 if (TempFromTy->isIncompleteType()) {
5536 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5537 << (unsigned) FnKind << FnDesc
5538 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5539 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5540 return;
5541 }
5542
Douglas Gregor56f2e342010-06-30 23:01:39 +00005543 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005544 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00005545 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
5546 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
5547 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5548 FromPtrTy->getPointeeType()) &&
5549 !FromPtrTy->getPointeeType()->isIncompleteType() &&
5550 !ToPtrTy->getPointeeType()->isIncompleteType() &&
5551 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
5552 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005553 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00005554 }
5555 } else if (const ObjCObjectPointerType *FromPtrTy
5556 = FromTy->getAs<ObjCObjectPointerType>()) {
5557 if (const ObjCObjectPointerType *ToPtrTy
5558 = ToTy->getAs<ObjCObjectPointerType>())
5559 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
5560 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
5561 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5562 FromPtrTy->getPointeeType()) &&
5563 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005564 BaseToDerivedConversion = 2;
5565 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
5566 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
5567 !FromTy->isIncompleteType() &&
5568 !ToRefTy->getPointeeType()->isIncompleteType() &&
5569 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
5570 BaseToDerivedConversion = 3;
5571 }
5572
5573 if (BaseToDerivedConversion) {
Douglas Gregor56f2e342010-06-30 23:01:39 +00005574 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005575 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00005576 << (unsigned) FnKind << FnDesc
5577 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005578 << (BaseToDerivedConversion - 1)
Douglas Gregor56f2e342010-06-30 23:01:39 +00005579 << FromTy << ToTy << I+1;
5580 return;
5581 }
5582
John McCall47000992010-01-14 03:28:57 +00005583 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00005584 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5585 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00005586 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00005587 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00005588}
5589
5590void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5591 unsigned NumFormalArgs) {
5592 // TODO: treat calls to a missing default constructor as a special case
5593
5594 FunctionDecl *Fn = Cand->Function;
5595 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5596
5597 unsigned MinParams = Fn->getMinRequiredArguments();
5598
5599 // at least / at most / exactly
Douglas Gregor02eb4832010-05-08 18:13:28 +00005600 // FIXME: variadic templates "at most" should account for parameter packs
John McCall6a61b522010-01-13 09:16:55 +00005601 unsigned mode, modeCount;
5602 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005603 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5604 (Cand->FailureKind == ovl_fail_bad_deduction &&
5605 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCall6a61b522010-01-13 09:16:55 +00005606 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5607 mode = 0; // "at least"
5608 else
5609 mode = 2; // "exactly"
5610 modeCount = MinParams;
5611 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005612 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5613 (Cand->FailureKind == ovl_fail_bad_deduction &&
5614 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00005615 if (MinParams != FnTy->getNumArgs())
5616 mode = 1; // "at most"
5617 else
5618 mode = 2; // "exactly"
5619 modeCount = FnTy->getNumArgs();
5620 }
5621
5622 std::string Description;
5623 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5624
5625 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregor02eb4832010-05-08 18:13:28 +00005626 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5627 << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00005628}
5629
John McCall8b9ed552010-02-01 18:53:26 +00005630/// Diagnose a failed template-argument deduction.
5631void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5632 Expr **Args, unsigned NumArgs) {
5633 FunctionDecl *Fn = Cand->Function; // pattern
5634
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005635 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005636 NamedDecl *ParamD;
5637 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5638 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5639 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00005640 switch (Cand->DeductionFailure.Result) {
5641 case Sema::TDK_Success:
5642 llvm_unreachable("TDK_success while diagnosing bad deduction");
5643
5644 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00005645 assert(ParamD && "no parameter found for incomplete deduction result");
5646 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5647 << ParamD->getDeclName();
5648 return;
5649 }
5650
John McCall42d7d192010-08-05 09:05:08 +00005651 case Sema::TDK_Underqualified: {
5652 assert(ParamD && "no parameter found for bad qualifiers deduction result");
5653 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
5654
5655 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
5656
5657 // Param will have been canonicalized, but it should just be a
5658 // qualified version of ParamD, so move the qualifiers to that.
5659 QualifierCollector Qs(S.Context);
5660 Qs.strip(Param);
5661 QualType NonCanonParam = Qs.apply(TParam->getTypeForDecl());
5662 assert(S.Context.hasSameType(Param, NonCanonParam));
5663
5664 // Arg has also been canonicalized, but there's nothing we can do
5665 // about that. It also doesn't matter as much, because it won't
5666 // have any template parameters in it (because deduction isn't
5667 // done on dependent types).
5668 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
5669
5670 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
5671 << ParamD->getDeclName() << Arg << NonCanonParam;
5672 return;
5673 }
5674
5675 case Sema::TDK_Inconsistent: {
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005676 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005677 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005678 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005679 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005680 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005681 which = 1;
5682 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005683 which = 2;
5684 }
5685
5686 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5687 << which << ParamD->getDeclName()
5688 << *Cand->DeductionFailure.getFirstArg()
5689 << *Cand->DeductionFailure.getSecondArg();
5690 return;
5691 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00005692
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005693 case Sema::TDK_InvalidExplicitArguments:
5694 assert(ParamD && "no parameter found for invalid explicit arguments");
5695 if (ParamD->getDeclName())
5696 S.Diag(Fn->getLocation(),
5697 diag::note_ovl_candidate_explicit_arg_mismatch_named)
5698 << ParamD->getDeclName();
5699 else {
5700 int index = 0;
5701 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5702 index = TTP->getIndex();
5703 else if (NonTypeTemplateParmDecl *NTTP
5704 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5705 index = NTTP->getIndex();
5706 else
5707 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
5708 S.Diag(Fn->getLocation(),
5709 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
5710 << (index + 1);
5711 }
5712 return;
5713
Douglas Gregor02eb4832010-05-08 18:13:28 +00005714 case Sema::TDK_TooManyArguments:
5715 case Sema::TDK_TooFewArguments:
5716 DiagnoseArityMismatch(S, Cand, NumArgs);
5717 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00005718
5719 case Sema::TDK_InstantiationDepth:
5720 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
5721 return;
5722
5723 case Sema::TDK_SubstitutionFailure: {
5724 std::string ArgString;
5725 if (TemplateArgumentList *Args
5726 = Cand->DeductionFailure.getTemplateArgumentList())
5727 ArgString = S.getTemplateArgumentBindingsText(
5728 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
5729 *Args);
5730 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
5731 << ArgString;
5732 return;
5733 }
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005734
John McCall8b9ed552010-02-01 18:53:26 +00005735 // TODO: diagnose these individually, then kill off
5736 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00005737 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00005738 case Sema::TDK_FailedOverloadResolution:
5739 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
5740 return;
5741 }
5742}
5743
5744/// Generates a 'note' diagnostic for an overload candidate. We've
5745/// already generated a primary error at the call site.
5746///
5747/// It really does need to be a single diagnostic with its caret
5748/// pointed at the candidate declaration. Yes, this creates some
5749/// major challenges of technical writing. Yes, this makes pointing
5750/// out problems with specific arguments quite awkward. It's still
5751/// better than generating twenty screens of text for every failed
5752/// overload.
5753///
5754/// It would be great to be able to express per-candidate problems
5755/// more richly for those diagnostic clients that cared, but we'd
5756/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00005757void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
5758 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00005759 FunctionDecl *Fn = Cand->Function;
5760
John McCall12f97bc2010-01-08 04:41:39 +00005761 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00005762 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00005763 std::string FnDesc;
5764 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00005765
5766 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00005767 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00005768 return;
John McCall12f97bc2010-01-08 04:41:39 +00005769 }
5770
John McCalle1ac8d12010-01-13 00:25:19 +00005771 // We don't really have anything else to say about viable candidates.
5772 if (Cand->Viable) {
5773 S.NoteOverloadCandidate(Fn);
5774 return;
5775 }
John McCall0d1da222010-01-12 00:44:57 +00005776
John McCall6a61b522010-01-13 09:16:55 +00005777 switch (Cand->FailureKind) {
5778 case ovl_fail_too_many_arguments:
5779 case ovl_fail_too_few_arguments:
5780 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00005781
John McCall6a61b522010-01-13 09:16:55 +00005782 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00005783 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5784
John McCallfe796dd2010-01-23 05:17:32 +00005785 case ovl_fail_trivial_conversion:
5786 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005787 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00005788 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005789
John McCall65eb8792010-02-25 01:37:24 +00005790 case ovl_fail_bad_conversion: {
5791 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5792 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00005793 if (Cand->Conversions[I].isBad())
5794 return DiagnoseBadConversion(S, Cand, I);
5795
5796 // FIXME: this currently happens when we're called from SemaInit
5797 // when user-conversion overload fails. Figure out how to handle
5798 // those conditions and diagnose them well.
5799 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005800 }
John McCall65eb8792010-02-25 01:37:24 +00005801 }
John McCalld3224162010-01-08 00:58:21 +00005802}
5803
5804void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5805 // Desugar the type of the surrogate down to a function type,
5806 // retaining as many typedefs as possible while still showing
5807 // the function type (and, therefore, its parameter types).
5808 QualType FnType = Cand->Surrogate->getConversionType();
5809 bool isLValueReference = false;
5810 bool isRValueReference = false;
5811 bool isPointer = false;
5812 if (const LValueReferenceType *FnTypeRef =
5813 FnType->getAs<LValueReferenceType>()) {
5814 FnType = FnTypeRef->getPointeeType();
5815 isLValueReference = true;
5816 } else if (const RValueReferenceType *FnTypeRef =
5817 FnType->getAs<RValueReferenceType>()) {
5818 FnType = FnTypeRef->getPointeeType();
5819 isRValueReference = true;
5820 }
5821 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5822 FnType = FnTypePtr->getPointeeType();
5823 isPointer = true;
5824 }
5825 // Desugar down to a function type.
5826 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5827 // Reconstruct the pointer/reference as appropriate.
5828 if (isPointer) FnType = S.Context.getPointerType(FnType);
5829 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5830 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5831
5832 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5833 << FnType;
5834}
5835
5836void NoteBuiltinOperatorCandidate(Sema &S,
5837 const char *Opc,
5838 SourceLocation OpLoc,
5839 OverloadCandidate *Cand) {
5840 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5841 std::string TypeStr("operator");
5842 TypeStr += Opc;
5843 TypeStr += "(";
5844 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5845 if (Cand->Conversions.size() == 1) {
5846 TypeStr += ")";
5847 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5848 } else {
5849 TypeStr += ", ";
5850 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5851 TypeStr += ")";
5852 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5853 }
5854}
5855
5856void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5857 OverloadCandidate *Cand) {
5858 unsigned NoOperands = Cand->Conversions.size();
5859 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5860 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00005861 if (ICS.isBad()) break; // all meaningless after first invalid
5862 if (!ICS.isAmbiguous()) continue;
5863
5864 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00005865 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00005866 }
5867}
5868
John McCall3712d9e2010-01-15 23:32:50 +00005869SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5870 if (Cand->Function)
5871 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00005872 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00005873 return Cand->Surrogate->getLocation();
5874 return SourceLocation();
5875}
5876
John McCallad2587a2010-01-12 00:48:53 +00005877struct CompareOverloadCandidatesForDisplay {
5878 Sema &S;
5879 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00005880
5881 bool operator()(const OverloadCandidate *L,
5882 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00005883 // Fast-path this check.
5884 if (L == R) return false;
5885
John McCall12f97bc2010-01-08 04:41:39 +00005886 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00005887 if (L->Viable) {
5888 if (!R->Viable) return true;
5889
5890 // TODO: introduce a tri-valued comparison for overload
5891 // candidates. Would be more worthwhile if we had a sort
5892 // that could exploit it.
John McCallbc077cf2010-02-08 23:07:23 +00005893 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5894 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00005895 } else if (R->Viable)
5896 return false;
John McCall12f97bc2010-01-08 04:41:39 +00005897
John McCall3712d9e2010-01-15 23:32:50 +00005898 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00005899
John McCall3712d9e2010-01-15 23:32:50 +00005900 // Criteria by which we can sort non-viable candidates:
5901 if (!L->Viable) {
5902 // 1. Arity mismatches come after other candidates.
5903 if (L->FailureKind == ovl_fail_too_many_arguments ||
5904 L->FailureKind == ovl_fail_too_few_arguments)
5905 return false;
5906 if (R->FailureKind == ovl_fail_too_many_arguments ||
5907 R->FailureKind == ovl_fail_too_few_arguments)
5908 return true;
John McCall12f97bc2010-01-08 04:41:39 +00005909
John McCallfe796dd2010-01-23 05:17:32 +00005910 // 2. Bad conversions come first and are ordered by the number
5911 // of bad conversions and quality of good conversions.
5912 if (L->FailureKind == ovl_fail_bad_conversion) {
5913 if (R->FailureKind != ovl_fail_bad_conversion)
5914 return true;
5915
5916 // If there's any ordering between the defined conversions...
5917 // FIXME: this might not be transitive.
5918 assert(L->Conversions.size() == R->Conversions.size());
5919
5920 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00005921 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5922 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCallfe796dd2010-01-23 05:17:32 +00005923 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5924 R->Conversions[I])) {
5925 case ImplicitConversionSequence::Better:
5926 leftBetter++;
5927 break;
5928
5929 case ImplicitConversionSequence::Worse:
5930 leftBetter--;
5931 break;
5932
5933 case ImplicitConversionSequence::Indistinguishable:
5934 break;
5935 }
5936 }
5937 if (leftBetter > 0) return true;
5938 if (leftBetter < 0) return false;
5939
5940 } else if (R->FailureKind == ovl_fail_bad_conversion)
5941 return false;
5942
John McCall3712d9e2010-01-15 23:32:50 +00005943 // TODO: others?
5944 }
5945
5946 // Sort everything else by location.
5947 SourceLocation LLoc = GetLocationForCandidate(L);
5948 SourceLocation RLoc = GetLocationForCandidate(R);
5949
5950 // Put candidates without locations (e.g. builtins) at the end.
5951 if (LLoc.isInvalid()) return false;
5952 if (RLoc.isInvalid()) return true;
5953
5954 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00005955 }
5956};
5957
John McCallfe796dd2010-01-23 05:17:32 +00005958/// CompleteNonViableCandidate - Normally, overload resolution only
5959/// computes up to the first
5960void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5961 Expr **Args, unsigned NumArgs) {
5962 assert(!Cand->Viable);
5963
5964 // Don't do anything on failures other than bad conversion.
5965 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5966
5967 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00005968 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00005969 unsigned ConvCount = Cand->Conversions.size();
5970 while (true) {
5971 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5972 ConvIdx++;
5973 if (Cand->Conversions[ConvIdx - 1].isBad())
5974 break;
5975 }
5976
5977 if (ConvIdx == ConvCount)
5978 return;
5979
John McCall65eb8792010-02-25 01:37:24 +00005980 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
5981 "remaining conversion is initialized?");
5982
Douglas Gregoradc7a702010-04-16 17:45:54 +00005983 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00005984 // operation somehow.
5985 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00005986
5987 const FunctionProtoType* Proto;
5988 unsigned ArgIdx = ConvIdx;
5989
5990 if (Cand->IsSurrogate) {
5991 QualType ConvType
5992 = Cand->Surrogate->getConversionType().getNonReferenceType();
5993 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5994 ConvType = ConvPtrType->getPointeeType();
5995 Proto = ConvType->getAs<FunctionProtoType>();
5996 ArgIdx--;
5997 } else if (Cand->Function) {
5998 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
5999 if (isa<CXXMethodDecl>(Cand->Function) &&
6000 !isa<CXXConstructorDecl>(Cand->Function))
6001 ArgIdx--;
6002 } else {
6003 // Builtin binary operator with a bad first conversion.
6004 assert(ConvCount <= 3);
6005 for (; ConvIdx != ConvCount; ++ConvIdx)
6006 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006007 = TryCopyInitialization(S, Args[ConvIdx],
6008 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6009 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006010 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00006011 return;
6012 }
6013
6014 // Fill in the rest of the conversions.
6015 unsigned NumArgsInProto = Proto->getNumArgs();
6016 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6017 if (ArgIdx < NumArgsInProto)
6018 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006019 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6020 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006021 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00006022 else
6023 Cand->Conversions[ConvIdx].setEllipsis();
6024 }
6025}
6026
John McCalld3224162010-01-08 00:58:21 +00006027} // end anonymous namespace
6028
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006029/// PrintOverloadCandidates - When overload resolution fails, prints
6030/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00006031/// set.
Mike Stump11289f42009-09-09 15:08:12 +00006032void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006033Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00006034 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00006035 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006036 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00006037 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00006038 // Sort the candidates by viability and position. Sorting directly would
6039 // be prohibitive, so we make a set of pointers and sort those.
6040 llvm::SmallVector<OverloadCandidate*, 32> Cands;
6041 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
6042 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6043 LastCand = CandidateSet.end();
John McCallfe796dd2010-01-23 05:17:32 +00006044 Cand != LastCand; ++Cand) {
6045 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00006046 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00006047 else if (OCD == OCD_AllCandidates) {
6048 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006049 if (Cand->Function || Cand->IsSurrogate)
6050 Cands.push_back(Cand);
6051 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6052 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00006053 }
6054 }
6055
John McCallad2587a2010-01-12 00:48:53 +00006056 std::sort(Cands.begin(), Cands.end(),
6057 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00006058
John McCall0d1da222010-01-12 00:44:57 +00006059 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00006060
John McCall12f97bc2010-01-08 04:41:39 +00006061 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006062 const Diagnostic::OverloadsShown ShowOverloads = Diags.getShowOverloads();
6063 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00006064 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6065 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00006066
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006067 // Set an arbitrary limit on the number of candidate functions we'll spam
6068 // the user with. FIXME: This limit should depend on details of the
6069 // candidate list.
6070 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6071 break;
6072 }
6073 ++CandsShown;
6074
John McCalld3224162010-01-08 00:58:21 +00006075 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00006076 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00006077 else if (Cand->IsSurrogate)
6078 NoteSurrogateCandidate(*this, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006079 else {
6080 assert(Cand->Viable &&
6081 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00006082 // Generally we only see ambiguities including viable builtin
6083 // operators if overload resolution got screwed up by an
6084 // ambiguous user-defined conversion.
6085 //
6086 // FIXME: It's quite possible for different conversions to see
6087 // different ambiguities, though.
6088 if (!ReportedAmbiguousConversions) {
6089 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
6090 ReportedAmbiguousConversions = true;
6091 }
John McCalld3224162010-01-08 00:58:21 +00006092
John McCall0d1da222010-01-12 00:44:57 +00006093 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00006094 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00006095 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006096 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006097
6098 if (I != E)
Jeffrey Yasskin5d474d02010-06-11 06:58:43 +00006099 Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006100}
6101
John McCalla0296f72010-03-19 07:35:19 +00006102static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00006103 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00006104 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006105
John McCalla0296f72010-03-19 07:35:19 +00006106 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006107}
6108
Douglas Gregorcd695e52008-11-10 20:40:00 +00006109/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6110/// an overloaded function (C++ [over.over]), where @p From is an
6111/// expression with overloaded function type and @p ToType is the type
6112/// we're trying to resolve to. For example:
6113///
6114/// @code
6115/// int f(double);
6116/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00006117///
Douglas Gregorcd695e52008-11-10 20:40:00 +00006118/// int (*pfd)(double) = f; // selects f(double)
6119/// @endcode
6120///
6121/// This routine returns the resulting FunctionDecl if it could be
6122/// resolved, and NULL otherwise. When @p Complain is true, this
6123/// routine will emit diagnostics if there is an error.
6124FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006125Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00006126 bool Complain,
6127 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006128 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006129 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006130 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00006131 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006132 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00006133 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006134 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006135 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006136 FunctionType = MemTypePtr->getPointeeType();
6137 IsMember = true;
6138 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006139
Douglas Gregorcd695e52008-11-10 20:40:00 +00006140 // C++ [over.over]p1:
6141 // [...] [Note: any redundant set of parentheses surrounding the
6142 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00006143 // C++ [over.over]p1:
6144 // [...] The overloaded function name can be preceded by the &
6145 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00006146 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
6147 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6148 if (OvlExpr->hasExplicitTemplateArgs()) {
6149 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6150 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregorcd695e52008-11-10 20:40:00 +00006151 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00006152
6153 // We expect a pointer or reference to function, or a function pointer.
6154 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6155 if (!FunctionType->isFunctionType()) {
6156 if (Complain)
6157 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6158 << OvlExpr->getName() << ToType;
6159
6160 return 0;
6161 }
6162
6163 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006164
Douglas Gregorcd695e52008-11-10 20:40:00 +00006165 // Look through all of the overloaded functions, searching for one
6166 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00006167 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006168 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
6169
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006170 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00006171 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6172 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006173 // Look through any using declarations to find the underlying function.
6174 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6175
Douglas Gregorcd695e52008-11-10 20:40:00 +00006176 // C++ [over.over]p3:
6177 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00006178 // targets of type "pointer-to-function" or "reference-to-function."
6179 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006180 // type "pointer-to-member-function."
6181 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00006182
Mike Stump11289f42009-09-09 15:08:12 +00006183 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006184 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00006185 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006186 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00006187 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006188 // static when converting to member pointer.
6189 if (Method->isStatic() == IsMember)
6190 continue;
6191 } else if (IsMember)
6192 continue;
Mike Stump11289f42009-09-09 15:08:12 +00006193
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006194 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006195 // If the name is a function template, template argument deduction is
6196 // done (14.8.2.2), and if the argument deduction succeeds, the
6197 // resulting template argument list is used to generate a single
6198 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006199 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006200 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00006201 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006202 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00006203 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00006204 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00006205 FunctionType, Specialization, Info)) {
6206 // FIXME: make a note of the failed deduction for diagnostics.
6207 (void)Result;
6208 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006209 // FIXME: If the match isn't exact, shouldn't we just drop this as
6210 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00006211 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00006212 == Context.getCanonicalType(Specialization->getType()));
John McCalla0296f72010-03-19 07:35:19 +00006213 Matches.push_back(std::make_pair(I.getPair(),
6214 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor9b146582009-07-08 20:55:45 +00006215 }
John McCalld14a8642009-11-21 08:51:07 +00006216
6217 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00006218 }
Mike Stump11289f42009-09-09 15:08:12 +00006219
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006220 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006221 // Skip non-static functions when converting to pointer, and static
6222 // when converting to member pointer.
6223 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00006224 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00006225
6226 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00006227 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00006228 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006229 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006230 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00006231
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006232 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00006233 QualType ResultTy;
6234 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6235 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6236 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00006237 Matches.push_back(std::make_pair(I.getPair(),
6238 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006239 FoundNonTemplateFunction = true;
6240 }
Mike Stump11289f42009-09-09 15:08:12 +00006241 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006242 }
6243
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006244 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00006245 if (Matches.empty()) {
6246 if (Complain) {
6247 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6248 << OvlExpr->getName() << FunctionType;
6249 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6250 E = OvlExpr->decls_end();
6251 I != E; ++I)
6252 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6253 NoteOverloadCandidate(F);
6254 }
6255
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006256 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00006257 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006258 FunctionDecl *Result = Matches[0].second;
John McCall16df1e52010-03-30 21:47:33 +00006259 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006260 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCall58cc69d2010-01-27 01:50:18 +00006261 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00006262 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006263 return Result;
6264 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006265
6266 // C++ [over.over]p4:
6267 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00006268 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006269 // [...] and any given function template specialization F1 is
6270 // eliminated if the set contains a second function template
6271 // specialization whose function template is more specialized
6272 // than the function template of F1 according to the partial
6273 // ordering rules of 14.5.5.2.
6274
6275 // The algorithm specified above is quadratic. We instead use a
6276 // two-pass algorithm (similar to the one used to identify the
6277 // best viable function in an overload set) that identifies the
6278 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00006279
6280 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6281 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6282 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00006283
6284 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00006285 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006286 TPOC_Other, From->getLocStart(),
6287 PDiag(),
6288 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006289 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00006290 PDiag(diag::note_ovl_candidate)
6291 << (unsigned) oc_function_template);
John McCalla0296f72010-03-19 07:35:19 +00006292 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCall58cc69d2010-01-27 01:50:18 +00006293 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00006294 FoundResult = Matches[Result - MatchesCopy.begin()].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00006295 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00006296 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall4fa0d5f2010-05-06 18:15:07 +00006297 DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc());
6298 }
John McCall58cc69d2010-01-27 01:50:18 +00006299 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006300 }
Mike Stump11289f42009-09-09 15:08:12 +00006301
Douglas Gregorfae1d712009-09-26 03:56:17 +00006302 // [...] any function template specializations in the set are
6303 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00006304 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00006305 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00006306 ++I;
6307 else {
John McCalla0296f72010-03-19 07:35:19 +00006308 Matches[I] = Matches[--N];
6309 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00006310 }
6311 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00006312
Mike Stump11289f42009-09-09 15:08:12 +00006313 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006314 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00006315 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006316 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00006317 FoundResult = Matches[0].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00006318 if (Complain) {
John McCalla0296f72010-03-19 07:35:19 +00006319 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
John McCall4fa0d5f2010-05-06 18:15:07 +00006320 DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc());
6321 }
John McCalla0296f72010-03-19 07:35:19 +00006322 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006323 }
Mike Stump11289f42009-09-09 15:08:12 +00006324
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006325 // FIXME: We should probably return the same thing that BestViableFunction
6326 // returns (even if we issue the diagnostics here).
6327 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006328 << Matches[0].second->getDeclName();
6329 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6330 NoteOverloadCandidate(Matches[I].second);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006331 return 0;
6332}
6333
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006334/// \brief Given an expression that refers to an overloaded function, try to
6335/// resolve that overloaded function expression down to a single function.
6336///
6337/// This routine can only resolve template-ids that refer to a single function
6338/// template, where that template-id refers to a single template whose template
6339/// arguments are either provided by the template-id or have defaults,
6340/// as described in C++0x [temp.arg.explicit]p3.
6341FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6342 // C++ [over.over]p1:
6343 // [...] [Note: any redundant set of parentheses surrounding the
6344 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006345 // C++ [over.over]p1:
6346 // [...] The overloaded function name can be preceded by the &
6347 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00006348
6349 if (From->getType() != Context.OverloadTy)
6350 return 0;
6351
6352 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006353
6354 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00006355 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006356 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00006357
6358 TemplateArgumentListInfo ExplicitTemplateArgs;
6359 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006360
6361 // Look through all of the overloaded functions, searching for one
6362 // whose type matches exactly.
6363 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00006364 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6365 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006366 // C++0x [temp.arg.explicit]p3:
6367 // [...] In contexts where deduction is done and fails, or in contexts
6368 // where deduction is not done, if a template argument list is
6369 // specified and it, along with any default template arguments,
6370 // identifies a single function template specialization, then the
6371 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00006372 FunctionTemplateDecl *FunctionTemplate
6373 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006374
6375 // C++ [over.over]p2:
6376 // If the name is a function template, template argument deduction is
6377 // done (14.8.2.2), and if the argument deduction succeeds, the
6378 // resulting template argument list is used to generate a single
6379 // function template specialization, which is added to the set of
6380 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006381 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006382 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006383 if (TemplateDeductionResult Result
6384 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6385 Specialization, Info)) {
6386 // FIXME: make a note of the failed deduction for diagnostics.
6387 (void)Result;
6388 continue;
6389 }
6390
6391 // Multiple matches; we can't resolve to a single declaration.
6392 if (Matched)
6393 return 0;
6394
6395 Matched = Specialization;
6396 }
6397
6398 return Matched;
6399}
6400
Douglas Gregorcabea402009-09-22 15:41:20 +00006401/// \brief Add a single candidate to the overload set.
6402static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00006403 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00006404 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006405 Expr **Args, unsigned NumArgs,
6406 OverloadCandidateSet &CandidateSet,
6407 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00006408 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00006409 if (isa<UsingShadowDecl>(Callee))
6410 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6411
Douglas Gregorcabea402009-09-22 15:41:20 +00006412 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00006413 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00006414 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006415 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006416 return;
John McCalld14a8642009-11-21 08:51:07 +00006417 }
6418
6419 if (FunctionTemplateDecl *FuncTemplate
6420 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00006421 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6422 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006423 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00006424 return;
6425 }
6426
6427 assert(false && "unhandled case in overloaded call candidate");
6428
6429 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00006430}
6431
6432/// \brief Add the overload candidates named by callee and/or found by argument
6433/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00006434void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00006435 Expr **Args, unsigned NumArgs,
6436 OverloadCandidateSet &CandidateSet,
6437 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00006438
6439#ifndef NDEBUG
6440 // Verify that ArgumentDependentLookup is consistent with the rules
6441 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00006442 //
Douglas Gregorcabea402009-09-22 15:41:20 +00006443 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6444 // and let Y be the lookup set produced by argument dependent
6445 // lookup (defined as follows). If X contains
6446 //
6447 // -- a declaration of a class member, or
6448 //
6449 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00006450 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00006451 //
6452 // -- a declaration that is neither a function or a function
6453 // template
6454 //
6455 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00006456
John McCall57500772009-12-16 12:17:52 +00006457 if (ULE->requiresADL()) {
6458 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6459 E = ULE->decls_end(); I != E; ++I) {
6460 assert(!(*I)->getDeclContext()->isRecord());
6461 assert(isa<UsingShadowDecl>(*I) ||
6462 !(*I)->getDeclContext()->isFunctionOrMethod());
6463 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00006464 }
6465 }
6466#endif
6467
John McCall57500772009-12-16 12:17:52 +00006468 // It would be nice to avoid this copy.
6469 TemplateArgumentListInfo TABuffer;
6470 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6471 if (ULE->hasExplicitTemplateArgs()) {
6472 ULE->copyTemplateArgumentsInto(TABuffer);
6473 ExplicitTemplateArgs = &TABuffer;
6474 }
6475
6476 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6477 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00006478 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006479 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00006480 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00006481
John McCall57500772009-12-16 12:17:52 +00006482 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00006483 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6484 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006485 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006486 CandidateSet,
6487 PartialOverloading);
6488}
John McCalld681c392009-12-16 08:11:27 +00006489
6490/// Attempts to recover from a call where no functions were found.
6491///
6492/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00006493static Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006494BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00006495 UnresolvedLookupExpr *ULE,
6496 SourceLocation LParenLoc,
6497 Expr **Args, unsigned NumArgs,
6498 SourceLocation *CommaLocs,
6499 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00006500
6501 CXXScopeSpec SS;
6502 if (ULE->getQualifier()) {
6503 SS.setScopeRep(ULE->getQualifier());
6504 SS.setRange(ULE->getQualifierRange());
6505 }
6506
John McCall57500772009-12-16 12:17:52 +00006507 TemplateArgumentListInfo TABuffer;
6508 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6509 if (ULE->hasExplicitTemplateArgs()) {
6510 ULE->copyTemplateArgumentsInto(TABuffer);
6511 ExplicitTemplateArgs = &TABuffer;
6512 }
6513
John McCalld681c392009-12-16 08:11:27 +00006514 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6515 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00006516 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
Douglas Gregorb412e172010-07-25 18:17:45 +00006517 return SemaRef.ExprError();
John McCalld681c392009-12-16 08:11:27 +00006518
John McCall57500772009-12-16 12:17:52 +00006519 assert(!R.empty() && "lookup results empty despite recovery");
6520
6521 // Build an implicit member call if appropriate. Just drop the
6522 // casts and such from the call, we don't really care.
6523 Sema::OwningExprResult NewFn = SemaRef.ExprError();
6524 if ((*R.begin())->isCXXClassMember())
6525 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6526 else if (ExplicitTemplateArgs)
6527 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6528 else
6529 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6530
6531 if (NewFn.isInvalid())
Douglas Gregorb412e172010-07-25 18:17:45 +00006532 return SemaRef.ExprError();
John McCall57500772009-12-16 12:17:52 +00006533
6534 // This shouldn't cause an infinite loop because we're giving it
6535 // an expression with non-empty lookup results, which should never
6536 // end up here.
6537 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
6538 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
6539 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006540}
Douglas Gregor4038cf42010-06-08 17:35:15 +00006541
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006542/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00006543/// (which eventually refers to the declaration Func) and the call
6544/// arguments Args/NumArgs, attempt to resolve the function call down
6545/// to a specific function. If overload resolution succeeds, returns
6546/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00006547/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006548/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00006549Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006550Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00006551 SourceLocation LParenLoc,
6552 Expr **Args, unsigned NumArgs,
6553 SourceLocation *CommaLocs,
6554 SourceLocation RParenLoc) {
6555#ifndef NDEBUG
6556 if (ULE->requiresADL()) {
6557 // To do ADL, we must have found an unqualified name.
6558 assert(!ULE->getQualifier() && "qualified name with ADL");
6559
6560 // We don't perform ADL for implicit declarations of builtins.
6561 // Verify that this was correctly set up.
6562 FunctionDecl *F;
6563 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6564 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6565 F->getBuiltinID() && F->isImplicit())
6566 assert(0 && "performing ADL for builtin");
6567
6568 // We don't perform ADL in C.
6569 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6570 }
6571#endif
6572
John McCallbc077cf2010-02-08 23:07:23 +00006573 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00006574
John McCall57500772009-12-16 12:17:52 +00006575 // Add the functions denoted by the callee to the set of candidate
6576 // functions, including those from argument-dependent lookup.
6577 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00006578
6579 // If we found nothing, try to recover.
6580 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6581 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00006582 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006583 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall57500772009-12-16 12:17:52 +00006584 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006585
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006586 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006587 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00006588 case OR_Success: {
6589 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00006590 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006591 DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00006592 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00006593 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6594 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006595
6596 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00006597 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006598 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00006599 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006600 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006601 break;
6602
6603 case OR_Ambiguous:
6604 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00006605 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006606 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006607 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006608
6609 case OR_Deleted:
6610 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6611 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00006612 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00006613 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006614 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006615 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006616 }
6617
Douglas Gregorb412e172010-07-25 18:17:45 +00006618 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00006619 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006620}
6621
John McCall4c4c1df2010-01-26 03:27:55 +00006622static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00006623 return Functions.size() > 1 ||
6624 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6625}
6626
Douglas Gregor084d8552009-03-13 23:49:33 +00006627/// \brief Create a unary operation that may resolve to an overloaded
6628/// operator.
6629///
6630/// \param OpLoc The location of the operator itself (e.g., '*').
6631///
6632/// \param OpcIn The UnaryOperator::Opcode that describes this
6633/// operator.
6634///
6635/// \param Functions The set of non-member functions that will be
6636/// considered by overload resolution. The caller needs to build this
6637/// set based on the context using, e.g.,
6638/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6639/// set should not contain any member functions; those will be added
6640/// by CreateOverloadedUnaryOp().
6641///
6642/// \param input The input argument.
John McCall4c4c1df2010-01-26 03:27:55 +00006643Sema::OwningExprResult
6644Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6645 const UnresolvedSetImpl &Fns,
6646 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006647 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
6648 Expr *Input = (Expr *)input.get();
6649
6650 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6651 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6652 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006653 // TODO: provide better source location info.
6654 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006655
6656 Expr *Args[2] = { Input, 0 };
6657 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00006658
Douglas Gregor084d8552009-03-13 23:49:33 +00006659 // For post-increment and post-decrement, add the implicit '0' as
6660 // the second argument, so that we know this is a post-increment or
6661 // post-decrement.
6662 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
6663 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00006664 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00006665 SourceLocation());
6666 NumArgs = 2;
6667 }
6668
6669 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00006670 if (Fns.empty())
6671 return Owned(new (Context) UnaryOperator(input.takeAs<Expr>(),
6672 Opc,
6673 Context.DependentTy,
6674 OpLoc));
6675
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,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006679 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006680 /*ADL*/ true, IsOverloaded(Fns),
6681 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00006682 input.release();
6683 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6684 &Args[0], NumArgs,
6685 Context.DependentTy,
6686 OpLoc));
6687 }
6688
6689 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006690 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006691
6692 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006693 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00006694
6695 // Add operator candidates that are member functions.
6696 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6697
John McCall4c4c1df2010-01-26 03:27:55 +00006698 // Add candidates from ADL.
6699 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00006700 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00006701 /*ExplicitTemplateArgs*/ 0,
6702 CandidateSet);
6703
Douglas Gregor084d8552009-03-13 23:49:33 +00006704 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006705 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00006706
6707 // Perform overload resolution.
6708 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006709 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006710 case OR_Success: {
6711 // We found a built-in operator or an overloaded operator.
6712 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00006713
Douglas Gregor084d8552009-03-13 23:49:33 +00006714 if (FnDecl) {
6715 // We matched an overloaded operator. Build a call to that
6716 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00006717
Douglas Gregor084d8552009-03-13 23:49:33 +00006718 // Convert the arguments.
6719 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00006720 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006721
John McCall16df1e52010-03-30 21:47:33 +00006722 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6723 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00006724 return ExprError();
6725 } else {
6726 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00006727 OwningExprResult InputInit
6728 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006729 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00006730 SourceLocation(),
6731 move(input));
6732 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00006733 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006734
Douglas Gregore6600372009-12-23 17:40:29 +00006735 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006736 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00006737 }
6738
John McCall4fa0d5f2010-05-06 18:15:07 +00006739 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6740
Douglas Gregor084d8552009-03-13 23:49:33 +00006741 // Determine the result type
Douglas Gregor603d81b2010-07-13 08:18:22 +00006742 QualType ResultTy = FnDecl->getCallResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006743
Douglas Gregor084d8552009-03-13 23:49:33 +00006744 // Build the actual expression node.
6745 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6746 SourceLocation());
6747 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00006748
Douglas Gregor084d8552009-03-13 23:49:33 +00006749 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00006750 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006751 ExprOwningPtr<CallExpr> TheCall(this,
6752 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00006753 Args, NumArgs, ResultTy, OpLoc));
John McCall4fa0d5f2010-05-06 18:15:07 +00006754
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006755 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6756 FnDecl))
6757 return ExprError();
6758
6759 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00006760 } else {
6761 // We matched a built-in operator. Convert the arguments, then
6762 // break out so that we will build the appropriate built-in
6763 // operator node.
6764 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006765 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00006766 return ExprError();
6767
6768 break;
6769 }
6770 }
6771
6772 case OR_No_Viable_Function:
6773 // No viable function; fall through to handling this as a
6774 // built-in operator, which will produce an error message for us.
6775 break;
6776
6777 case OR_Ambiguous:
6778 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6779 << UnaryOperator::getOpcodeStr(Opc)
6780 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006781 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006782 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006783 return ExprError();
6784
6785 case OR_Deleted:
6786 Diag(OpLoc, diag::err_ovl_deleted_oper)
6787 << Best->Function->isDeleted()
6788 << UnaryOperator::getOpcodeStr(Opc)
6789 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006790 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00006791 return ExprError();
6792 }
6793
6794 // Either we found no viable overloaded operator or we matched a
6795 // built-in operator. In either case, fall through to trying to
6796 // build a built-in operation.
6797 input.release();
6798 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
6799}
6800
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006801/// \brief Create a binary operation that may resolve to an overloaded
6802/// operator.
6803///
6804/// \param OpLoc The location of the operator itself (e.g., '+').
6805///
6806/// \param OpcIn The BinaryOperator::Opcode that describes this
6807/// operator.
6808///
6809/// \param Functions The set of non-member functions that will be
6810/// considered by overload resolution. The caller needs to build this
6811/// set based on the context using, e.g.,
6812/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6813/// set should not contain any member functions; those will be added
6814/// by CreateOverloadedBinOp().
6815///
6816/// \param LHS Left-hand argument.
6817/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00006818Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006819Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006820 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00006821 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006822 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006823 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00006824 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006825
6826 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6827 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6828 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6829
6830 // If either side is type-dependent, create an appropriate dependent
6831 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00006832 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00006833 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006834 // If there are no functions to store, just build a dependent
6835 // BinaryOperator or CompoundAssignment.
6836 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
6837 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6838 Context.DependentTy, OpLoc));
6839
6840 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6841 Context.DependentTy,
6842 Context.DependentTy,
6843 Context.DependentTy,
6844 OpLoc));
6845 }
John McCall4c4c1df2010-01-26 03:27:55 +00006846
6847 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00006848 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006849 // TODO: provide better source location info in DNLoc component.
6850 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00006851 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006852 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006853 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006854 /*ADL*/ true, IsOverloaded(Fns),
6855 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006856 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00006857 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006858 Context.DependentTy,
6859 OpLoc));
6860 }
6861
6862 // If this is the .* operator, which is not overloadable, just
6863 // create a built-in binary operator.
6864 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00006865 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006866
Sebastian Redl6a96bf72009-11-18 23:10:33 +00006867 // If this is the assignment operator, we only perform overload resolution
6868 // if the left-hand side is a class or enumeration type. This is actually
6869 // a hack. The standard requires that we do overload resolution between the
6870 // various built-in candidates, but as DR507 points out, this can lead to
6871 // problems. So we do it this way, which pretty much follows what GCC does.
6872 // Note that we go the traditional code path for compound assignment forms.
6873 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00006874 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006875
Douglas Gregor084d8552009-03-13 23:49:33 +00006876 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006877 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006878
6879 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006880 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006881
6882 // Add operator candidates that are member functions.
6883 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6884
John McCall4c4c1df2010-01-26 03:27:55 +00006885 // Add candidates from ADL.
6886 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6887 Args, 2,
6888 /*ExplicitTemplateArgs*/ 0,
6889 CandidateSet);
6890
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006891 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006892 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006893
6894 // Perform overload resolution.
6895 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006896 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00006897 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006898 // We found a built-in operator or an overloaded operator.
6899 FunctionDecl *FnDecl = Best->Function;
6900
6901 if (FnDecl) {
6902 // We matched an overloaded operator. Build a call to that
6903 // operator.
6904
6905 // Convert the arguments.
6906 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00006907 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00006908 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006909
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006910 OwningExprResult Arg1
6911 = PerformCopyInitialization(
6912 InitializedEntity::InitializeParameter(
6913 FnDecl->getParamDecl(0)),
6914 SourceLocation(),
6915 Owned(Args[1]));
6916 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006917 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006918
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006919 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006920 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006921 return ExprError();
6922
6923 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006924 } else {
6925 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006926 OwningExprResult Arg0
6927 = PerformCopyInitialization(
6928 InitializedEntity::InitializeParameter(
6929 FnDecl->getParamDecl(0)),
6930 SourceLocation(),
6931 Owned(Args[0]));
6932 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006933 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006934
6935 OwningExprResult Arg1
6936 = PerformCopyInitialization(
6937 InitializedEntity::InitializeParameter(
6938 FnDecl->getParamDecl(1)),
6939 SourceLocation(),
6940 Owned(Args[1]));
6941 if (Arg1.isInvalid())
6942 return ExprError();
6943 Args[0] = LHS = Arg0.takeAs<Expr>();
6944 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006945 }
6946
John McCall4fa0d5f2010-05-06 18:15:07 +00006947 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6948
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006949 // Determine the result type
6950 QualType ResultTy
Douglas Gregor603d81b2010-07-13 08:18:22 +00006951 = FnDecl->getType()->getAs<FunctionType>()
6952 ->getCallResultType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006953
6954 // Build the actual expression node.
6955 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00006956 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006957 UsualUnaryConversions(FnExpr);
6958
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006959 ExprOwningPtr<CXXOperatorCallExpr>
6960 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6961 Args, 2, ResultTy,
6962 OpLoc));
6963
6964 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6965 FnDecl))
6966 return ExprError();
6967
6968 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006969 } else {
6970 // We matched a built-in operator. Convert the arguments, then
6971 // break out so that we will build the appropriate built-in
6972 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00006973 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006974 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00006975 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006976 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006977 return ExprError();
6978
6979 break;
6980 }
6981 }
6982
Douglas Gregor66950a32009-09-30 21:46:01 +00006983 case OR_No_Viable_Function: {
6984 // C++ [over.match.oper]p9:
6985 // If the operator is the operator , [...] and there are no
6986 // viable functions, then the operator is assumed to be the
6987 // built-in operator and interpreted according to clause 5.
6988 if (Opc == BinaryOperator::Comma)
6989 break;
6990
Sebastian Redl027de2a2009-05-21 11:50:50 +00006991 // For class as left operand for assignment or compound assigment operator
6992 // do not fall through to handling in built-in, but report that no overloaded
6993 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00006994 OwningExprResult Result = ExprError();
6995 if (Args[0]->getType()->isRecordType() &&
6996 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00006997 Diag(OpLoc, diag::err_ovl_no_viable_oper)
6998 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006999 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00007000 } else {
7001 // No viable function; try to create a built-in operation, which will
7002 // produce an error. Then, show the non-viable candidates.
7003 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00007004 }
Douglas Gregor66950a32009-09-30 21:46:01 +00007005 assert(Result.isInvalid() &&
7006 "C++ binary operator overloading is missing candidates!");
7007 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00007008 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00007009 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00007010 return move(Result);
7011 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007012
7013 case OR_Ambiguous:
7014 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
7015 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007016 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007017 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00007018 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007019 return ExprError();
7020
7021 case OR_Deleted:
7022 Diag(OpLoc, diag::err_ovl_deleted_oper)
7023 << Best->Function->isDeleted()
7024 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007025 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007026 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007027 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00007028 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007029
Douglas Gregor66950a32009-09-30 21:46:01 +00007030 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00007031 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007032}
7033
Sebastian Redladba46e2009-10-29 20:17:01 +00007034Action::OwningExprResult
7035Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7036 SourceLocation RLoc,
7037 ExprArg Base, ExprArg Idx) {
7038 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
7039 static_cast<Expr*>(Idx.get()) };
7040 DeclarationName OpName =
7041 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7042
7043 // If either side is type-dependent, create an appropriate dependent
7044 // expression.
7045 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7046
John McCall58cc69d2010-01-27 01:50:18 +00007047 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007048 // CHECKME: no 'operator' keyword?
7049 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7050 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00007051 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00007052 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007053 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007054 /*ADL*/ true, /*Overloaded*/ false,
7055 UnresolvedSetIterator(),
7056 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00007057 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00007058
7059 Base.release();
7060 Idx.release();
7061 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7062 Args, 2,
7063 Context.DependentTy,
7064 RLoc));
7065 }
7066
7067 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007068 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007069
7070 // Subscript can only be overloaded as a member function.
7071
7072 // Add operator candidates that are member functions.
7073 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7074
7075 // Add builtin operator candidates.
7076 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7077
7078 // Perform overload resolution.
7079 OverloadCandidateSet::iterator Best;
7080 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
7081 case OR_Success: {
7082 // We found a built-in operator or an overloaded operator.
7083 FunctionDecl *FnDecl = Best->Function;
7084
7085 if (FnDecl) {
7086 // We matched an overloaded operator. Build a call to that
7087 // operator.
7088
John McCalla0296f72010-03-19 07:35:19 +00007089 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007090 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00007091
Sebastian Redladba46e2009-10-29 20:17:01 +00007092 // Convert the arguments.
7093 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007094 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007095 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00007096 return ExprError();
7097
Anders Carlssona68e51e2010-01-29 18:37:50 +00007098 // Convert the arguments.
7099 OwningExprResult InputInit
7100 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7101 FnDecl->getParamDecl(0)),
7102 SourceLocation(),
7103 Owned(Args[1]));
7104 if (InputInit.isInvalid())
7105 return ExprError();
7106
7107 Args[1] = InputInit.takeAs<Expr>();
7108
Sebastian Redladba46e2009-10-29 20:17:01 +00007109 // Determine the result type
7110 QualType ResultTy
Douglas Gregor603d81b2010-07-13 08:18:22 +00007111 = FnDecl->getType()->getAs<FunctionType>()
7112 ->getCallResultType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00007113
7114 // Build the actual expression node.
7115 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7116 LLoc);
7117 UsualUnaryConversions(FnExpr);
7118
7119 Base.release();
7120 Idx.release();
7121 ExprOwningPtr<CXXOperatorCallExpr>
7122 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7123 FnExpr, Args, 2,
7124 ResultTy, RLoc));
7125
7126 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
7127 FnDecl))
7128 return ExprError();
7129
7130 return MaybeBindToTemporary(TheCall.release());
7131 } else {
7132 // We matched a built-in operator. Convert the arguments, then
7133 // break out so that we will build the appropriate built-in
7134 // operator node.
7135 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007136 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00007137 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007138 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00007139 return ExprError();
7140
7141 break;
7142 }
7143 }
7144
7145 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00007146 if (CandidateSet.empty())
7147 Diag(LLoc, diag::err_ovl_no_oper)
7148 << Args[0]->getType() << /*subscript*/ 0
7149 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7150 else
7151 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7152 << Args[0]->getType()
7153 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007154 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00007155 "[]", LLoc);
7156 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00007157 }
7158
7159 case OR_Ambiguous:
7160 Diag(LLoc, diag::err_ovl_ambiguous_oper)
7161 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007162 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00007163 "[]", LLoc);
7164 return ExprError();
7165
7166 case OR_Deleted:
7167 Diag(LLoc, diag::err_ovl_deleted_oper)
7168 << Best->Function->isDeleted() << "[]"
7169 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007170 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00007171 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007172 return ExprError();
7173 }
7174
7175 // We matched a built-in operator; build it.
7176 Base.release();
7177 Idx.release();
7178 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
7179 Owned(Args[1]), RLoc);
7180}
7181
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007182/// BuildCallToMemberFunction - Build a call to a member
7183/// function. MemExpr is the expression that refers to the member
7184/// function (and includes the object parameter), Args/NumArgs are the
7185/// arguments to the function call (not including the object
7186/// parameter). The caller needs to validate that the member
7187/// expression refers to a member function or an overloaded member
7188/// function.
John McCall2d74de92009-12-01 22:10:20 +00007189Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00007190Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7191 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007192 unsigned NumArgs, SourceLocation *CommaLocs,
7193 SourceLocation RParenLoc) {
7194 // Dig out the member expression. This holds both the object
7195 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00007196 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7197
John McCall10eae182009-11-30 22:42:35 +00007198 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007199 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00007200 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007201 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00007202 if (isa<MemberExpr>(NakedMemExpr)) {
7203 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00007204 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00007205 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007206 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00007207 } else {
7208 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007209 Qualifier = UnresExpr->getQualifier();
7210
John McCall6e9f8f62009-12-03 04:06:58 +00007211 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00007212
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007213 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00007214 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00007215
John McCall2d74de92009-12-01 22:10:20 +00007216 // FIXME: avoid copy.
7217 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7218 if (UnresExpr->hasExplicitTemplateArgs()) {
7219 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7220 TemplateArgs = &TemplateArgsBuffer;
7221 }
7222
John McCall10eae182009-11-30 22:42:35 +00007223 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7224 E = UnresExpr->decls_end(); I != E; ++I) {
7225
John McCall6e9f8f62009-12-03 04:06:58 +00007226 NamedDecl *Func = *I;
7227 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7228 if (isa<UsingShadowDecl>(Func))
7229 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7230
John McCall10eae182009-11-30 22:42:35 +00007231 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00007232 // If explicit template arguments were provided, we can't call a
7233 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00007234 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00007235 continue;
7236
John McCalla0296f72010-03-19 07:35:19 +00007237 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00007238 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007239 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007240 } else {
John McCall10eae182009-11-30 22:42:35 +00007241 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00007242 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007243 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007244 CandidateSet,
7245 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007246 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007247 }
Mike Stump11289f42009-09-09 15:08:12 +00007248
John McCall10eae182009-11-30 22:42:35 +00007249 DeclarationName DeclName = UnresExpr->getMemberName();
7250
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007251 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00007252 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007253 case OR_Success:
7254 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007255 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00007256 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007257 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007258 break;
7259
7260 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00007261 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007262 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007263 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007264 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007265 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007266 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007267
7268 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00007269 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007270 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007271 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007272 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007273 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007274
7275 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00007276 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00007277 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00007278 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007279 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007280 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007281 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007282 }
7283
John McCall16df1e52010-03-30 21:47:33 +00007284 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00007285
John McCall2d74de92009-12-01 22:10:20 +00007286 // If overload resolution picked a static member, build a
7287 // non-member call based on that function.
7288 if (Method->isStatic()) {
7289 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7290 Args, NumArgs, RParenLoc);
7291 }
7292
John McCall10eae182009-11-30 22:42:35 +00007293 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007294 }
7295
7296 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00007297 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00007298 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00007299 NumArgs,
Douglas Gregor603d81b2010-07-13 08:18:22 +00007300 Method->getCallResultType(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007301 RParenLoc));
7302
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007303 // Check for a valid return type.
7304 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
7305 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00007306 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007307
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007308 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00007309 // We only need to do this if there was actually an overload; otherwise
7310 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00007311 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00007312 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00007313 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7314 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00007315 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007316 MemExpr->setBase(ObjectArg);
7317
7318 // Convert the rest of the arguments
Douglas Gregorc8be9522010-05-04 18:18:31 +00007319 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00007320 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007321 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00007322 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007323
Anders Carlssonbc4c1072009-08-16 01:56:34 +00007324 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00007325 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00007326
John McCall2d74de92009-12-01 22:10:20 +00007327 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007328}
7329
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007330/// BuildCallToObjectOfClassType - Build a call to an object of class
7331/// type (C++ [over.call.object]), which can end up invoking an
7332/// overloaded function call operator (@c operator()) or performing a
7333/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00007334Sema::ExprResult
7335Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00007336 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007337 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00007338 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007339 SourceLocation RParenLoc) {
7340 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007341 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00007342
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007343 // C++ [over.call.object]p1:
7344 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00007345 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007346 // candidate functions includes at least the function call
7347 // operators of T. The function call operators of T are obtained by
7348 // ordinary lookup of the name operator() in the context of
7349 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00007350 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00007351 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007352
7353 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007354 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007355 << Object->getSourceRange()))
7356 return true;
7357
John McCall27b18f82009-11-17 02:14:36 +00007358 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7359 LookupQualifiedName(R, Record->getDecl());
7360 R.suppressDiagnostics();
7361
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007362 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00007363 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007364 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00007365 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00007366 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00007367 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007368
Douglas Gregorab7897a2008-11-19 22:57:39 +00007369 // C++ [over.call.object]p2:
7370 // In addition, for each conversion function declared in T of the
7371 // form
7372 //
7373 // operator conversion-type-id () cv-qualifier;
7374 //
7375 // where cv-qualifier is the same cv-qualification as, or a
7376 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00007377 // denotes the type "pointer to function of (P1,...,Pn) returning
7378 // R", or the type "reference to pointer to function of
7379 // (P1,...,Pn) returning R", or the type "reference to function
7380 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00007381 // is also considered as a candidate function. Similarly,
7382 // surrogate call functions are added to the set of candidate
7383 // functions for each conversion function declared in an
7384 // accessible base class provided the function is not hidden
7385 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00007386 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00007387 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00007388 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00007389 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00007390 NamedDecl *D = *I;
7391 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7392 if (isa<UsingShadowDecl>(D))
7393 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7394
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007395 // Skip over templated conversion functions; they aren't
7396 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00007397 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007398 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007399
John McCall6e9f8f62009-12-03 04:06:58 +00007400 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00007401
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007402 // Strip the reference type (if any) and then the pointer type (if
7403 // any) to get down to what might be a function type.
7404 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7405 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7406 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007407
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007408 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00007409 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00007410 Object->getType(), Args, NumArgs,
7411 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007412 }
Mike Stump11289f42009-09-09 15:08:12 +00007413
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007414 // Perform overload resolution.
7415 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007416 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007417 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00007418 // Overload resolution succeeded; we'll build the appropriate call
7419 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007420 break;
7421
7422 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00007423 if (CandidateSet.empty())
7424 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7425 << Object->getType() << /*call*/ 1
7426 << Object->getSourceRange();
7427 else
7428 Diag(Object->getSourceRange().getBegin(),
7429 diag::err_ovl_no_viable_object_call)
7430 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007431 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007432 break;
7433
7434 case OR_Ambiguous:
7435 Diag(Object->getSourceRange().getBegin(),
7436 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007437 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007438 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007439 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007440
7441 case OR_Deleted:
7442 Diag(Object->getSourceRange().getBegin(),
7443 diag::err_ovl_deleted_object_call)
7444 << Best->Function->isDeleted()
7445 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007446 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007447 break;
Mike Stump11289f42009-09-09 15:08:12 +00007448 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007449
Douglas Gregorb412e172010-07-25 18:17:45 +00007450 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007451 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007452
Douglas Gregorab7897a2008-11-19 22:57:39 +00007453 if (Best->Function == 0) {
7454 // Since there is no function declaration, this is one of the
7455 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00007456 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00007457 = cast<CXXConversionDecl>(
7458 Best->Conversions[0].UserDefined.ConversionFunction);
7459
John McCalla0296f72010-03-19 07:35:19 +00007460 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007461 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007462
Douglas Gregorab7897a2008-11-19 22:57:39 +00007463 // We selected one of the surrogate functions that converts the
7464 // object parameter to a function pointer. Perform the conversion
7465 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00007466
7467 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007468 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00007469 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7470 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007471
Fariborz Jahanian774cf792009-09-28 18:35:46 +00007472 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00007473 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
Douglas Gregore5e775b2010-04-13 15:50:39 +00007474 CommaLocs, RParenLoc).result();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007475 }
7476
John McCalla0296f72010-03-19 07:35:19 +00007477 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007478 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007479
Douglas Gregorab7897a2008-11-19 22:57:39 +00007480 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7481 // that calls this method, using Object for the implicit object
7482 // parameter and passing along the remaining arguments.
7483 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00007484 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007485
7486 unsigned NumArgsInProto = Proto->getNumArgs();
7487 unsigned NumArgsToCheck = NumArgs;
7488
7489 // Build the full argument list for the method call (the
7490 // implicit object parameter is placed at the beginning of the
7491 // list).
7492 Expr **MethodArgs;
7493 if (NumArgs < NumArgsInProto) {
7494 NumArgsToCheck = NumArgsInProto;
7495 MethodArgs = new Expr*[NumArgsInProto + 1];
7496 } else {
7497 MethodArgs = new Expr*[NumArgs + 1];
7498 }
7499 MethodArgs[0] = Object;
7500 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7501 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00007502
7503 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00007504 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007505 UsualUnaryConversions(NewFn);
7506
7507 // Once we've built TheCall, all of the expressions are properly
7508 // owned.
Douglas Gregor603d81b2010-07-13 08:18:22 +00007509 QualType ResultTy = Method->getCallResultType();
Mike Stump11289f42009-09-09 15:08:12 +00007510 ExprOwningPtr<CXXOperatorCallExpr>
7511 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007512 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00007513 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007514 delete [] MethodArgs;
7515
Anders Carlsson3d5829c2009-10-13 21:49:31 +00007516 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
7517 Method))
7518 return true;
7519
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007520 // We may have default arguments. If so, we need to allocate more
7521 // slots in the call for them.
7522 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00007523 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007524 else if (NumArgs > NumArgsInProto)
7525 NumArgsToCheck = NumArgsInProto;
7526
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007527 bool IsError = false;
7528
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007529 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007530 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007531 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007532 TheCall->setArg(0, Object);
7533
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007534
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007535 // Check the argument types.
7536 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007537 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007538 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007539 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00007540
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007541 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007542
7543 OwningExprResult InputInit
7544 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7545 Method->getParamDecl(i)),
7546 SourceLocation(), Owned(Arg));
7547
7548 IsError |= InputInit.isInvalid();
7549 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007550 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00007551 OwningExprResult DefArg
7552 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7553 if (DefArg.isInvalid()) {
7554 IsError = true;
7555 break;
7556 }
7557
7558 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007559 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007560
7561 TheCall->setArg(i + 1, Arg);
7562 }
7563
7564 // If this is a variadic call, handle args passed through "...".
7565 if (Proto->isVariadic()) {
7566 // Promote the arguments (C99 6.5.2.2p7).
7567 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7568 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00007569 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007570 TheCall->setArg(i + 1, Arg);
7571 }
7572 }
7573
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007574 if (IsError) return true;
7575
Anders Carlssonbc4c1072009-08-16 01:56:34 +00007576 if (CheckFunctionCall(Method, TheCall.get()))
7577 return true;
7578
Douglas Gregore5e775b2010-04-13 15:50:39 +00007579 return MaybeBindToTemporary(TheCall.release()).result();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007580}
7581
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007582/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00007583/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007584/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00007585Sema::OwningExprResult
7586Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
7587 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007588 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00007589
John McCallbc077cf2010-02-08 23:07:23 +00007590 SourceLocation Loc = Base->getExprLoc();
7591
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007592 // C++ [over.ref]p1:
7593 //
7594 // [...] An expression x->m is interpreted as (x.operator->())->m
7595 // for a class object x of type T if T::operator->() exists and if
7596 // the operator is selected as the best match function by the
7597 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007598 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00007599 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007600 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00007601
John McCallbc077cf2010-02-08 23:07:23 +00007602 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00007603 PDiag(diag::err_typecheck_incomplete_tag)
7604 << Base->getSourceRange()))
7605 return ExprError();
7606
John McCall27b18f82009-11-17 02:14:36 +00007607 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7608 LookupQualifiedName(R, BaseRecord->getDecl());
7609 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00007610
7611 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00007612 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007613 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007614 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00007615 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007616
7617 // Perform overload resolution.
7618 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007619 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007620 case OR_Success:
7621 // Overload resolution succeeded; we'll build the call below.
7622 break;
7623
7624 case OR_No_Viable_Function:
7625 if (CandidateSet.empty())
7626 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00007627 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007628 else
7629 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00007630 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007631 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007632 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007633
7634 case OR_Ambiguous:
7635 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00007636 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007637 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007638 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007639
7640 case OR_Deleted:
7641 Diag(OpLoc, diag::err_ovl_deleted_oper)
7642 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00007643 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007644 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007645 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007646 }
7647
John McCalla0296f72010-03-19 07:35:19 +00007648 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007649 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00007650
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007651 // Convert the object parameter.
7652 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007653 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7654 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00007655 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00007656
7657 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00007658 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007659
7660 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00007661 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7662 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007663 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007664
Douglas Gregor603d81b2010-07-13 08:18:22 +00007665 QualType ResultTy = Method->getCallResultType();
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007666 ExprOwningPtr<CXXOperatorCallExpr>
7667 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7668 &Base, 1, ResultTy, OpLoc));
7669
7670 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
7671 Method))
7672 return ExprError();
7673 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007674}
7675
Douglas Gregorcd695e52008-11-10 20:40:00 +00007676/// FixOverloadedFunctionReference - E is an expression that refers to
7677/// a C++ overloaded function (possibly with some parentheses and
7678/// perhaps a '&' around it). We have resolved the overloaded function
7679/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007680/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00007681Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00007682 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00007683 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007684 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7685 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007686 if (SubExpr == PE->getSubExpr())
7687 return PE->Retain();
7688
7689 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7690 }
7691
7692 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007693 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7694 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00007695 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00007696 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00007697 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00007698 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00007699 if (SubExpr == ICE->getSubExpr())
7700 return ICE->Retain();
7701
John McCallcf142162010-08-07 06:22:56 +00007702 return ImplicitCastExpr::Create(Context, ICE->getType(),
7703 ICE->getCastKind(),
7704 SubExpr, 0,
7705 ICE->getCategory());
Douglas Gregor51c538b2009-11-20 19:42:02 +00007706 }
7707
7708 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00007709 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00007710 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007711 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7712 if (Method->isStatic()) {
7713 // Do nothing: static member functions aren't any different
7714 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00007715 } else {
John McCalle66edc12009-11-24 19:00:30 +00007716 // Fix the sub expression, which really has to be an
7717 // UnresolvedLookupExpr holding an overloaded member function
7718 // or template.
John McCall16df1e52010-03-30 21:47:33 +00007719 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7720 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00007721 if (SubExpr == UnOp->getSubExpr())
7722 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00007723
John McCalld14a8642009-11-21 08:51:07 +00007724 assert(isa<DeclRefExpr>(SubExpr)
7725 && "fixed to something other than a decl ref");
7726 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7727 && "fixed to a member ref with no nested name qualifier");
7728
7729 // We have taken the address of a pointer to member
7730 // function. Perform the computation here so that we get the
7731 // appropriate pointer to member type.
7732 QualType ClassType
7733 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7734 QualType MemPtrType
7735 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7736
7737 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7738 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007739 }
7740 }
John McCall16df1e52010-03-30 21:47:33 +00007741 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7742 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007743 if (SubExpr == UnOp->getSubExpr())
7744 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007745
Douglas Gregor51c538b2009-11-20 19:42:02 +00007746 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7747 Context.getPointerType(SubExpr->getType()),
7748 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00007749 }
John McCalld14a8642009-11-21 08:51:07 +00007750
7751 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00007752 // FIXME: avoid copy.
7753 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00007754 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00007755 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7756 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00007757 }
7758
John McCalld14a8642009-11-21 08:51:07 +00007759 return DeclRefExpr::Create(Context,
7760 ULE->getQualifier(),
7761 ULE->getQualifierRange(),
7762 Fn,
7763 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00007764 Fn->getType(),
7765 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00007766 }
7767
John McCall10eae182009-11-30 22:42:35 +00007768 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00007769 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00007770 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7771 if (MemExpr->hasExplicitTemplateArgs()) {
7772 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7773 TemplateArgs = &TemplateArgsBuffer;
7774 }
John McCall6b51f282009-11-23 01:53:49 +00007775
John McCall2d74de92009-12-01 22:10:20 +00007776 Expr *Base;
7777
7778 // If we're filling in
7779 if (MemExpr->isImplicitAccess()) {
7780 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7781 return DeclRefExpr::Create(Context,
7782 MemExpr->getQualifier(),
7783 MemExpr->getQualifierRange(),
7784 Fn,
7785 MemExpr->getMemberLoc(),
7786 Fn->getType(),
7787 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00007788 } else {
7789 SourceLocation Loc = MemExpr->getMemberLoc();
7790 if (MemExpr->getQualifier())
7791 Loc = MemExpr->getQualifierRange().getBegin();
7792 Base = new (Context) CXXThisExpr(Loc,
7793 MemExpr->getBaseType(),
7794 /*isImplicit=*/true);
7795 }
John McCall2d74de92009-12-01 22:10:20 +00007796 } else
7797 Base = MemExpr->getBase()->Retain();
7798
7799 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007800 MemExpr->isArrow(),
7801 MemExpr->getQualifier(),
7802 MemExpr->getQualifierRange(),
7803 Fn,
John McCall16df1e52010-03-30 21:47:33 +00007804 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007805 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00007806 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007807 Fn->getType());
7808 }
7809
Douglas Gregor51c538b2009-11-20 19:42:02 +00007810 assert(false && "Invalid reference to overloaded function");
7811 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00007812}
7813
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007814Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCalla8ae2222010-04-06 21:38:20 +00007815 DeclAccessPair Found,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007816 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00007817 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007818}
7819
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007820} // end namespace clang