blob: f7382361333112573d33a9f7ae083191a57763f7 [file] [log] [blame]
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
John McCall5cebab12009-11-18 07:57:50 +000015#include "Lookup.h"
Douglas Gregor0a70c4d2009-12-22 21:44:34 +000016#include "SemaInit.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000017#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000018#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000023#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000025#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000027#include <algorithm>
28
29namespace clang {
30
31/// GetConversionCategory - Retrieve the implicit conversion
32/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000033ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000034GetConversionCategory(ImplicitConversionKind Kind) {
35 static const ImplicitConversionCategory
36 Category[(int)ICK_Num_Conversion_Kinds] = {
37 ICC_Identity,
38 ICC_Lvalue_Transformation,
39 ICC_Lvalue_Transformation,
40 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000041 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000042 ICC_Qualification_Adjustment,
43 ICC_Promotion,
44 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000045 ICC_Promotion,
46 ICC_Conversion,
47 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000048 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000053 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000054 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000055 ICC_Conversion
56 };
57 return Category[(int)Kind];
58}
59
60/// GetConversionRank - Retrieve the implicit conversion rank
61/// corresponding to the given implicit conversion kind.
62ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
63 static const ImplicitConversionRank
64 Rank[(int)ICK_Num_Conversion_Kinds] = {
65 ICR_Exact_Match,
66 ICR_Exact_Match,
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000070 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000071 ICR_Promotion,
72 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000073 ICR_Promotion,
74 ICR_Conversion,
75 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000076 ICR_Conversion,
77 ICR_Conversion,
78 ICR_Conversion,
79 ICR_Conversion,
80 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000081 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000082 ICR_Conversion,
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +000083 ICR_Complex_Real_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +000084 };
85 return Rank[(int)Kind];
86}
87
88/// GetImplicitConversionName - Return the name of this kind of
89/// implicit conversion.
90const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +000091 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +000092 "No conversion",
93 "Lvalue-to-rvalue",
94 "Array-to-pointer",
95 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000096 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +000097 "Qualification",
98 "Integral promotion",
99 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000100 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000101 "Integral conversion",
102 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000103 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000104 "Floating-integral conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000105 "Complex-real conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000106 "Pointer conversion",
107 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000108 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000109 "Compatible-types conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000110 "Derived-to-base conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000111 };
112 return Name[Kind];
113}
114
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000115/// StandardConversionSequence - Set the standard conversion
116/// sequence to the identity conversion.
117void StandardConversionSequence::setAsIdentityConversion() {
118 First = ICK_Identity;
119 Second = ICK_Identity;
120 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000121 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000122 ReferenceBinding = false;
123 DirectBinding = false;
Sebastian Redlf69a94a2009-03-29 22:46:24 +0000124 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000125 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000126}
127
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000128/// getRank - Retrieve the rank of this standard conversion sequence
129/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
130/// implicit conversions.
131ImplicitConversionRank StandardConversionSequence::getRank() const {
132 ImplicitConversionRank Rank = ICR_Exact_Match;
133 if (GetConversionRank(First) > Rank)
134 Rank = GetConversionRank(First);
135 if (GetConversionRank(Second) > Rank)
136 Rank = GetConversionRank(Second);
137 if (GetConversionRank(Third) > Rank)
138 Rank = GetConversionRank(Third);
139 return Rank;
140}
141
142/// isPointerConversionToBool - Determines whether this conversion is
143/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000144/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000145/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000146bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000147 // Note that FromType has not necessarily been transformed by the
148 // array-to-pointer or function-to-pointer implicit conversions, so
149 // check for their presence as well as checking whether FromType is
150 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000151 if (getToType(1)->isBooleanType() &&
John McCall0d1da222010-01-12 00:44:57 +0000152 (getFromType()->isPointerType() || getFromType()->isBlockPointerType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000153 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
154 return true;
155
156 return false;
157}
158
Douglas Gregor5c407d92008-10-23 00:40:37 +0000159/// isPointerConversionToVoidPointer - Determines whether this
160/// conversion is a conversion of a pointer to a void pointer. This is
161/// used as part of the ranking of standard conversion sequences (C++
162/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000163bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000164StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000165isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000166 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000167 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000168
169 // Note that FromType has not necessarily been transformed by the
170 // array-to-pointer implicit conversion, so check for its presence
171 // and redo the conversion to get a pointer.
172 if (First == ICK_Array_To_Pointer)
173 FromType = Context.getArrayDecayedType(FromType);
174
Douglas Gregor1aa450a2009-12-13 21:37:05 +0000175 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000176 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000177 return ToPtrType->getPointeeType()->isVoidType();
178
179 return false;
180}
181
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000182/// DebugPrint - Print this standard conversion sequence to standard
183/// error. Useful for debugging overloading issues.
184void StandardConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000185 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000186 bool PrintedSomething = false;
187 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000188 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000189 PrintedSomething = true;
190 }
191
192 if (Second != ICK_Identity) {
193 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000194 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000195 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000196 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000197
198 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000199 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000200 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000201 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000202 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000203 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000204 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000205 PrintedSomething = true;
206 }
207
208 if (Third != ICK_Identity) {
209 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000210 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000211 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000212 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000213 PrintedSomething = true;
214 }
215
216 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000217 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000218 }
219}
220
221/// DebugPrint - Print this user-defined conversion sequence to standard
222/// error. Useful for debugging overloading issues.
223void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000224 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000225 if (Before.First || Before.Second || Before.Third) {
226 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000227 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000228 }
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000229 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000230 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000231 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000232 After.DebugPrint();
233 }
234}
235
236/// DebugPrint - Print this implicit conversion sequence to standard
237/// error. Useful for debugging overloading issues.
238void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000239 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000240 switch (ConversionKind) {
241 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000242 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000243 Standard.DebugPrint();
244 break;
245 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000246 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000247 UserDefined.DebugPrint();
248 break;
249 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000250 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000251 break;
John McCall0d1da222010-01-12 00:44:57 +0000252 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000253 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000254 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000255 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000256 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000257 break;
258 }
259
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000260 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000261}
262
John McCall0d1da222010-01-12 00:44:57 +0000263void AmbiguousConversionSequence::construct() {
264 new (&conversions()) ConversionSet();
265}
266
267void AmbiguousConversionSequence::destruct() {
268 conversions().~ConversionSet();
269}
270
271void
272AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
273 FromTypePtr = O.FromTypePtr;
274 ToTypePtr = O.ToTypePtr;
275 new (&conversions()) ConversionSet(O.conversions());
276}
277
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000278namespace {
279 // Structure used by OverloadCandidate::DeductionFailureInfo to store
280 // template parameter and template argument information.
281 struct DFIParamWithArguments {
282 TemplateParameter Param;
283 TemplateArgument FirstArg;
284 TemplateArgument SecondArg;
285 };
286}
287
288/// \brief Convert from Sema's representation of template deduction information
289/// to the form used in overload-candidate information.
290OverloadCandidate::DeductionFailureInfo
291static MakeDeductionFailureInfo(Sema::TemplateDeductionResult TDK,
292 const Sema::TemplateDeductionInfo &Info) {
293 OverloadCandidate::DeductionFailureInfo Result;
294 Result.Result = static_cast<unsigned>(TDK);
295 Result.Data = 0;
296 switch (TDK) {
297 case Sema::TDK_Success:
298 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000299 case Sema::TDK_TooManyArguments:
300 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000301 break;
302
303 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000304 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000305 Result.Data = Info.Param.getOpaqueValue();
306 break;
307
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000308 case Sema::TDK_Inconsistent:
309 case Sema::TDK_InconsistentQuals: {
310 DFIParamWithArguments *Saved = new DFIParamWithArguments;
311 Saved->Param = Info.Param;
312 Saved->FirstArg = Info.FirstArg;
313 Saved->SecondArg = Info.SecondArg;
314 Result.Data = Saved;
315 break;
316 }
317
318 case Sema::TDK_SubstitutionFailure:
319 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000320 case Sema::TDK_FailedOverloadResolution:
321 break;
322 }
323
324 return Result;
325}
John McCall0d1da222010-01-12 00:44:57 +0000326
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000327void OverloadCandidate::DeductionFailureInfo::Destroy() {
328 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
329 case Sema::TDK_Success:
330 case Sema::TDK_InstantiationDepth:
331 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000332 case Sema::TDK_TooManyArguments:
333 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000334 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000335 break;
336
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000337 case Sema::TDK_Inconsistent:
338 case Sema::TDK_InconsistentQuals:
339 delete static_cast<DFIParamWithArguments*>(Data);
340 Data = 0;
341 break;
342
Douglas Gregor461761d2010-05-08 18:20:53 +0000343 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000344 case Sema::TDK_SubstitutionFailure:
345 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000346 case Sema::TDK_FailedOverloadResolution:
347 break;
348 }
349}
350
351TemplateParameter
352OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
353 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
354 case Sema::TDK_Success:
355 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000356 case Sema::TDK_TooManyArguments:
357 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000358 return TemplateParameter();
359
360 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000361 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000362 return TemplateParameter::getFromOpaqueValue(Data);
363
364 case Sema::TDK_Inconsistent:
365 case Sema::TDK_InconsistentQuals:
366 return static_cast<DFIParamWithArguments*>(Data)->Param;
367
368 // Unhandled
369 case Sema::TDK_SubstitutionFailure:
370 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000371 case Sema::TDK_FailedOverloadResolution:
372 break;
373 }
374
375 return TemplateParameter();
376}
377
378const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
379 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
380 case Sema::TDK_Success:
381 case Sema::TDK_InstantiationDepth:
382 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000383 case Sema::TDK_TooManyArguments:
384 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000385 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000386 return 0;
387
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000388 case Sema::TDK_Inconsistent:
389 case Sema::TDK_InconsistentQuals:
390 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
391
Douglas Gregor461761d2010-05-08 18:20:53 +0000392 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000393 case Sema::TDK_SubstitutionFailure:
394 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000395 case Sema::TDK_FailedOverloadResolution:
396 break;
397 }
398
399 return 0;
400}
401
402const TemplateArgument *
403OverloadCandidate::DeductionFailureInfo::getSecondArg() {
404 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
405 case Sema::TDK_Success:
406 case Sema::TDK_InstantiationDepth:
407 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000408 case Sema::TDK_TooManyArguments:
409 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000410 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000411 return 0;
412
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000413 case Sema::TDK_Inconsistent:
414 case Sema::TDK_InconsistentQuals:
415 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
416
Douglas Gregor461761d2010-05-08 18:20:53 +0000417 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000418 case Sema::TDK_SubstitutionFailure:
419 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000420 case Sema::TDK_FailedOverloadResolution:
421 break;
422 }
423
424 return 0;
425}
426
427void OverloadCandidateSet::clear() {
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000428 //
429 for (iterator C = begin(), CEnd = end(); C != CEnd; ++C) {
430 if (C->FailureKind == ovl_fail_bad_deduction)
431 C->DeductionFailure.Destroy();
432 }
433
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000434 inherited::clear();
435 Functions.clear();
436}
437
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000438// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000439// overload of the declarations in Old. This routine returns false if
440// New and Old cannot be overloaded, e.g., if New has the same
441// signature as some function in Old (C++ 1.3.10) or if the Old
442// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000443// it does return false, MatchedDecl will point to the decl that New
444// cannot be overloaded with. This decl may be a UsingShadowDecl on
445// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000446//
447// Example: Given the following input:
448//
449// void f(int, float); // #1
450// void f(int, int); // #2
451// int f(int, int); // #3
452//
453// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000454// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000455//
John McCall3d988d92009-12-02 08:47:38 +0000456// When we process #2, Old contains only the FunctionDecl for #1. By
457// comparing the parameter types, we see that #1 and #2 are overloaded
458// (since they have different signatures), so this routine returns
459// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000460//
John McCall3d988d92009-12-02 08:47:38 +0000461// When we process #3, Old is an overload set containing #1 and #2. We
462// compare the signatures of #3 to #1 (they're overloaded, so we do
463// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
464// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000465// signature), IsOverload returns false and MatchedDecl will be set to
466// point to the FunctionDecl for #2.
John McCalldaa3d6b2009-12-09 03:35:25 +0000467Sema::OverloadKind
John McCall84d87672009-12-10 09:41:52 +0000468Sema::CheckOverload(FunctionDecl *New, const LookupResult &Old,
469 NamedDecl *&Match) {
John McCall3d988d92009-12-02 08:47:38 +0000470 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000471 I != E; ++I) {
John McCall3d988d92009-12-02 08:47:38 +0000472 NamedDecl *OldD = (*I)->getUnderlyingDecl();
473 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000474 if (!IsOverload(New, OldT->getTemplatedDecl())) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000475 Match = *I;
476 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000477 }
John McCall3d988d92009-12-02 08:47:38 +0000478 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCall1f82f242009-11-18 22:49:29 +0000479 if (!IsOverload(New, OldF)) {
John McCalldaa3d6b2009-12-09 03:35:25 +0000480 Match = *I;
481 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000482 }
John McCall84d87672009-12-10 09:41:52 +0000483 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
484 // We can overload with these, which can show up when doing
485 // redeclaration checks for UsingDecls.
486 assert(Old.getLookupKind() == LookupUsingDeclName);
487 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
488 // Optimistically assume that an unresolved using decl will
489 // overload; if it doesn't, we'll have to diagnose during
490 // template instantiation.
491 } else {
John McCall1f82f242009-11-18 22:49:29 +0000492 // (C++ 13p1):
493 // Only function declarations can be overloaded; object and type
494 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000495 Match = *I;
496 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000497 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000498 }
John McCall1f82f242009-11-18 22:49:29 +0000499
John McCalldaa3d6b2009-12-09 03:35:25 +0000500 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000501}
502
503bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old) {
504 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
505 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
506
507 // C++ [temp.fct]p2:
508 // A function template can be overloaded with other function templates
509 // and with normal (non-template) functions.
510 if ((OldTemplate == 0) != (NewTemplate == 0))
511 return true;
512
513 // Is the function New an overload of the function Old?
514 QualType OldQType = Context.getCanonicalType(Old->getType());
515 QualType NewQType = Context.getCanonicalType(New->getType());
516
517 // Compare the signatures (C++ 1.3.10) of the two functions to
518 // determine whether they are overloads. If we find any mismatch
519 // in the signature, they are overloads.
520
521 // If either of these functions is a K&R-style function (no
522 // prototype), then we consider them to have matching signatures.
523 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
524 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
525 return false;
526
527 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
528 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
529
530 // The signature of a function includes the types of its
531 // parameters (C++ 1.3.10), which includes the presence or absence
532 // of the ellipsis; see C++ DR 357).
533 if (OldQType != NewQType &&
534 (OldType->getNumArgs() != NewType->getNumArgs() ||
535 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000536 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000537 return true;
538
539 // C++ [temp.over.link]p4:
540 // The signature of a function template consists of its function
541 // signature, its return type and its template parameter list. The names
542 // of the template parameters are significant only for establishing the
543 // relationship between the template parameters and the rest of the
544 // signature.
545 //
546 // We check the return type and template parameter lists for function
547 // templates first; the remaining checks follow.
548 if (NewTemplate &&
549 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
550 OldTemplate->getTemplateParameters(),
551 false, TPL_TemplateMatch) ||
552 OldType->getResultType() != NewType->getResultType()))
553 return true;
554
555 // If the function is a class member, its signature includes the
556 // cv-qualifiers (if any) on the function itself.
557 //
558 // As part of this, also check whether one of the member functions
559 // is static, in which case they are not overloads (C++
560 // 13.1p2). While not part of the definition of the signature,
561 // this check is important to determine whether these functions
562 // can be overloaded.
563 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
564 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
565 if (OldMethod && NewMethod &&
566 !OldMethod->isStatic() && !NewMethod->isStatic() &&
567 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
568 return true;
569
570 // The signatures match; this is not an overload.
571 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000572}
573
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000574/// TryImplicitConversion - Attempt to perform an implicit conversion
575/// from the given expression (Expr) to the given type (ToType). This
576/// function returns an implicit conversion sequence that can be used
577/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000578///
579/// void f(float f);
580/// void g(int i) { f(i); }
581///
582/// this routine would produce an implicit conversion sequence to
583/// describe the initialization of f from i, which will be a standard
584/// conversion sequence containing an lvalue-to-rvalue conversion (C++
585/// 4.1) followed by a floating-integral conversion (C++ 4.9).
586//
587/// Note that this routine only determines how the conversion can be
588/// performed; it does not actually perform the conversion. As such,
589/// it will not produce any diagnostics if no conversion is available,
590/// but will instead return an implicit conversion sequence of kind
591/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000592///
593/// If @p SuppressUserConversions, then user-defined conversions are
594/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000595/// If @p AllowExplicit, then explicit user-defined conversions are
596/// permitted.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000597ImplicitConversionSequence
Anders Carlsson5ec4abf2009-08-27 17:14:02 +0000598Sema::TryImplicitConversion(Expr* From, QualType ToType,
599 bool SuppressUserConversions,
Douglas Gregore81335c2010-04-16 18:00:29 +0000600 bool AllowExplicit,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000601 bool InOverloadResolution) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000602 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +0000603 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000604 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000605 return ICS;
606 }
607
608 if (!getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000609 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000610 return ICS;
611 }
612
Douglas Gregor5ab11652010-04-17 22:01:05 +0000613 if (SuppressUserConversions) {
614 // C++ [over.ics.user]p4:
615 // A conversion of an expression of class type to the same class
616 // type is given Exact Match rank, and a conversion of an
617 // expression of class type to a base class of that type is
618 // given Conversion rank, in spite of the fact that a copy/move
619 // constructor (i.e., a user-defined conversion function) is
620 // called for those cases.
621 QualType FromType = From->getType();
622 if (!ToType->getAs<RecordType>() || !FromType->getAs<RecordType>() ||
623 !(Context.hasSameUnqualifiedType(FromType, ToType) ||
624 IsDerivedFrom(FromType, ToType))) {
625 // We're not in the case above, so there is no conversion that
626 // we can perform.
627 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
628 return ICS;
629 }
630
631 ICS.setStandard();
632 ICS.Standard.setAsIdentityConversion();
633 ICS.Standard.setFromType(FromType);
634 ICS.Standard.setAllToTypes(ToType);
635
636 // We don't actually check at this point whether there is a valid
637 // copy/move constructor, since overloading just assumes that it
638 // exists. When we actually perform initialization, we'll find the
639 // appropriate constructor to copy the returned object, if needed.
640 ICS.Standard.CopyConstructor = 0;
641
642 // Determine whether this is considered a derived-to-base conversion.
643 if (!Context.hasSameUnqualifiedType(FromType, ToType))
644 ICS.Standard.Second = ICK_Derived_To_Base;
645
646 return ICS;
647 }
648
649 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000650 OverloadCandidateSet Conversions(From->getExprLoc());
651 OverloadingResult UserDefResult
652 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000653 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000654
655 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000656 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000657 // C++ [over.ics.user]p4:
658 // A conversion of an expression of class type to the same class
659 // type is given Exact Match rank, and a conversion of an
660 // expression of class type to a base class of that type is
661 // given Conversion rank, in spite of the fact that a copy
662 // constructor (i.e., a user-defined conversion function) is
663 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000664 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000665 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000666 QualType FromCanon
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000667 = Context.getCanonicalType(From->getType().getUnqualifiedType());
668 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000669 if (Constructor->isCopyConstructor() &&
Douglas Gregor4141d5b2009-12-22 00:21:20 +0000670 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000671 // Turn this into a "standard" conversion sequence, so that it
672 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000673 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000674 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000675 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000676 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000677 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000678 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000679 ICS.Standard.Second = ICK_Derived_To_Base;
680 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000681 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000682
683 // C++ [over.best.ics]p4:
684 // However, when considering the argument of a user-defined
685 // conversion function that is a candidate by 13.3.1.3 when
686 // invoked for the copying of the temporary in the second step
687 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
688 // 13.3.1.6 in all cases, only standard conversion sequences and
689 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000690 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000691 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000692 }
John McCalle8c8cd22010-01-13 22:30:33 +0000693 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000694 ICS.setAmbiguous();
695 ICS.Ambiguous.setFromType(From->getType());
696 ICS.Ambiguous.setToType(ToType);
697 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
698 Cand != Conversions.end(); ++Cand)
699 if (Cand->Viable)
700 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000701 } else {
John McCall65eb8792010-02-25 01:37:24 +0000702 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000703 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000704
705 return ICS;
706}
707
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000708/// PerformImplicitConversion - Perform an implicit conversion of the
709/// expression From to the type ToType. Returns true if there was an
710/// error, false otherwise. The expression From is replaced with the
711/// converted expression. Flavor is the kind of conversion we're
712/// performing, used in the error message. If @p AllowExplicit,
713/// explicit user-defined conversions are permitted.
714bool
715Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
716 AssignmentAction Action, bool AllowExplicit) {
717 ImplicitConversionSequence ICS;
718 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
719}
720
721bool
722Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
723 AssignmentAction Action, bool AllowExplicit,
724 ImplicitConversionSequence& ICS) {
725 ICS = TryImplicitConversion(From, ToType,
726 /*SuppressUserConversions=*/false,
727 AllowExplicit,
728 /*InOverloadResolution=*/false);
729 return PerformImplicitConversion(From, ToType, ICS, Action);
730}
731
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000732/// \brief Determine whether the conversion from FromType to ToType is a valid
733/// conversion that strips "noreturn" off the nested function type.
734static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
735 QualType ToType, QualType &ResultTy) {
736 if (Context.hasSameUnqualifiedType(FromType, ToType))
737 return false;
738
739 // Strip the noreturn off the type we're converting from; noreturn can
740 // safely be removed.
741 FromType = Context.getNoReturnType(FromType, false);
742 if (!Context.hasSameUnqualifiedType(FromType, ToType))
743 return false;
744
745 ResultTy = FromType;
746 return true;
747}
748
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000749/// IsStandardConversion - Determines whether there is a standard
750/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
751/// expression From to the type ToType. Standard conversion sequences
752/// only consider non-class types; for conversions that involve class
753/// types, use TryImplicitConversion. If a conversion exists, SCS will
754/// contain the standard conversion sequence required to perform this
755/// conversion and this routine will return true. Otherwise, this
756/// routine will return false and the value of SCS is unspecified.
Mike Stump11289f42009-09-09 15:08:12 +0000757bool
758Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +0000759 bool InOverloadResolution,
Mike Stump11289f42009-09-09 15:08:12 +0000760 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000761 QualType FromType = From->getType();
762
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000763 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000764 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000765 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000766 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000767 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000768 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000769
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000770 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000771 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000772 if (FromType->isRecordType() || ToType->isRecordType()) {
773 if (getLangOptions().CPlusPlus)
774 return false;
775
Mike Stump11289f42009-09-09 15:08:12 +0000776 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000777 }
778
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000779 // The first conversion can be an lvalue-to-rvalue conversion,
780 // array-to-pointer conversion, or function-to-pointer conversion
781 // (C++ 4p1).
782
Douglas Gregor980fb162010-04-29 18:24:40 +0000783 if (FromType == Context.OverloadTy) {
784 DeclAccessPair AccessPair;
785 if (FunctionDecl *Fn
786 = ResolveAddressOfOverloadedFunction(From, ToType, false,
787 AccessPair)) {
788 // We were able to resolve the address of the overloaded function,
789 // so we can convert to the type of that function.
790 FromType = Fn->getType();
791 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
792 if (!Method->isStatic()) {
793 Type *ClassType
794 = Context.getTypeDeclType(Method->getParent()).getTypePtr();
795 FromType = Context.getMemberPointerType(FromType, ClassType);
796 }
797 }
798
799 // If the "from" expression takes the address of the overloaded
800 // function, update the type of the resulting expression accordingly.
801 if (FromType->getAs<FunctionType>())
802 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
803 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
804 FromType = Context.getPointerType(FromType);
805
806 // Check that we've computed the proper type after overload resolution.
807 assert(Context.hasSameType(FromType,
808 FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
809 } else {
810 return false;
811 }
812 }
Mike Stump11289f42009-09-09 15:08:12 +0000813 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000814 // An lvalue (3.10) of a non-function, non-array type T can be
815 // converted to an rvalue.
816 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump11289f42009-09-09 15:08:12 +0000817 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000818 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor1baf54e2009-03-13 18:40:31 +0000819 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000820 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000821
822 // If T is a non-class type, the type of the rvalue is the
823 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000824 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
825 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000826 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000827 } else if (FromType->isArrayType()) {
828 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000829 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000830
831 // An lvalue or rvalue of type "array of N T" or "array of unknown
832 // bound of T" can be converted to an rvalue of type "pointer to
833 // T" (C++ 4.2p1).
834 FromType = Context.getArrayDecayedType(FromType);
835
836 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
837 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +0000838 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000839
840 // For the purpose of ranking in overload resolution
841 // (13.3.3.1.1), this conversion is considered an
842 // array-to-pointer conversion followed by a qualification
843 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000844 SCS.Second = ICK_Identity;
845 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000846 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000847 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000848 }
Mike Stump12b8ce12009-08-04 21:02:39 +0000849 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
850 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000851 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000852
853 // An lvalue of function type T can be converted to an rvalue of
854 // type "pointer to T." The result is a pointer to the
855 // function. (C++ 4.3p1).
856 FromType = Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +0000857 } else {
858 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000859 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000860 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000861 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000862
863 // The second conversion can be an integral promotion, floating
864 // point promotion, integral conversion, floating point conversion,
865 // floating-integral conversion, pointer conversion,
866 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000867 // For overloading in C, this can also be a "compatible-type"
868 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +0000869 bool IncompatibleObjC = false;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000870 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000871 // The unqualified versions of the types are the same: there's no
872 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000873 SCS.Second = ICK_Identity;
Mike Stump12b8ce12009-08-04 21:02:39 +0000874 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000875 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000876 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000877 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000878 } else if (IsFloatingPointPromotion(FromType, ToType)) {
879 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000880 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000881 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000882 } else if (IsComplexPromotion(FromType, ToType)) {
883 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000884 SCS.Second = ICK_Complex_Promotion;
885 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000886 } else if ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000887 (ToType->isIntegralType() && !ToType->isEnumeralType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000888 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000889 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000890 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000891 } else if (FromType->isComplexType() && ToType->isComplexType()) {
892 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000893 SCS.Second = ICK_Complex_Conversion;
894 FromType = ToType.getUnqualifiedType();
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +0000895 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
896 (ToType->isComplexType() && FromType->isArithmeticType())) {
897 // Complex-real conversions (C99 6.3.1.7)
898 SCS.Second = ICK_Complex_Real;
899 FromType = ToType.getUnqualifiedType();
900 } else if (FromType->isFloatingType() && ToType->isFloatingType()) {
901 // Floating point conversions (C++ 4.8).
902 SCS.Second = ICK_Floating_Conversion;
903 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +0000904 } else if ((FromType->isFloatingType() &&
905 ToType->isIntegralType() && (!ToType->isBooleanType() &&
906 !ToType->isEnumeralType())) ||
Mike Stump11289f42009-09-09 15:08:12 +0000907 ((FromType->isIntegralType() || FromType->isEnumeralType()) &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000908 ToType->isFloatingType())) {
909 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000910 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000911 FromType = ToType.getUnqualifiedType();
Anders Carlsson228eea32009-08-28 15:33:32 +0000912 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
913 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000914 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000915 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000916 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor56751b52009-09-25 04:25:58 +0000917 } else if (IsMemberPointerConversion(From, FromType, ToType,
918 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +0000919 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +0000920 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +0000921 } else if (ToType->isBooleanType() &&
922 (FromType->isArithmeticType() ||
923 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +0000924 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +0000925 FromType->isBlockPointerType() ||
926 FromType->isMemberPointerType() ||
927 FromType->isNullPtrType())) {
928 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000929 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000930 FromType = Context.BoolTy;
Mike Stump11289f42009-09-09 15:08:12 +0000931 } else if (!getLangOptions().CPlusPlus &&
Mike Stump12b8ce12009-08-04 21:02:39 +0000932 Context.typesAreCompatible(ToType, FromType)) {
933 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000934 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000935 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
936 // Treat a conversion that strips "noreturn" as an identity conversion.
937 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000938 } else {
939 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000940 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000941 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000942 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000943
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000944 QualType CanonFrom;
945 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000946 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor9a657932008-10-21 23:43:52 +0000947 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000948 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000949 FromType = ToType;
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000950 CanonFrom = Context.getCanonicalType(FromType);
951 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000952 } else {
953 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000954 SCS.Third = ICK_Identity;
955
Mike Stump11289f42009-09-09 15:08:12 +0000956 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000957 // [...] Any difference in top-level cv-qualification is
958 // subsumed by the initialization itself and does not constitute
959 // a conversion. [...]
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000960 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump11289f42009-09-09 15:08:12 +0000961 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +0000962 if (CanonFrom.getLocalUnqualifiedType()
963 == CanonTo.getLocalUnqualifiedType() &&
964 CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000965 FromType = ToType;
966 CanonFrom = CanonTo;
967 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000968 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000969 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000970
971 // If we have not converted the argument type to the parameter type,
972 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000973 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000974 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000975
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000976 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000977}
978
979/// IsIntegralPromotion - Determines whether the conversion from the
980/// expression From (whose potentially-adjusted type is FromType) to
981/// ToType is an integral promotion (C++ 4.5). If so, returns true and
982/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +0000983bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +0000984 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +0000985 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +0000986 if (!To) {
987 return false;
988 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000989
990 // An rvalue of type char, signed char, unsigned char, short int, or
991 // unsigned short int can be converted to an rvalue of type int if
992 // int can represent all the values of the source type; otherwise,
993 // the source rvalue can be converted to an rvalue of type unsigned
994 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +0000995 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
996 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000997 if (// We can promote any signed, promotable integer type to an int
998 (FromType->isSignedIntegerType() ||
999 // We can promote any unsigned integer type whose size is
1000 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001001 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001002 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001003 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001004 }
1005
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001006 return To->getKind() == BuiltinType::UInt;
1007 }
1008
1009 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
1010 // can be converted to an rvalue of the first of the following types
1011 // that can represent all the values of its underlying type: int,
1012 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +00001013
1014 // We pre-calculate the promotion type for enum types.
1015 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
1016 if (ToType->isIntegerType())
1017 return Context.hasSameUnqualifiedType(ToType,
1018 FromEnumType->getDecl()->getPromotionType());
1019
1020 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001021 // Determine whether the type we're converting from is signed or
1022 // unsigned.
1023 bool FromIsSigned;
1024 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +00001025
1026 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1027 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001028
1029 // The types we'll try to promote to, in the appropriate
1030 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001031 QualType PromoteTypes[6] = {
1032 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001033 Context.LongTy, Context.UnsignedLongTy ,
1034 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001035 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001036 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001037 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1038 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001039 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001040 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1041 // We found the type that we can promote to. If this is the
1042 // type we wanted, we have a promotion. Otherwise, no
1043 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001044 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001045 }
1046 }
1047 }
1048
1049 // An rvalue for an integral bit-field (9.6) can be converted to an
1050 // rvalue of type int if int can represent all the values of the
1051 // bit-field; otherwise, it can be converted to unsigned int if
1052 // unsigned int can represent all the values of the bit-field. If
1053 // the bit-field is larger yet, no integral promotion applies to
1054 // it. If the bit-field has an enumerated type, it is treated as any
1055 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001056 // FIXME: We should delay checking of bit-fields until we actually perform the
1057 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001058 using llvm::APSInt;
1059 if (From)
1060 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001061 APSInt BitWidth;
Douglas Gregor71235ec2009-05-02 02:18:30 +00001062 if (FromType->isIntegralType() && !FromType->isEnumeralType() &&
1063 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1064 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1065 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001066
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001067 // Are we promoting to an int from a bitfield that fits in an int?
1068 if (BitWidth < ToSize ||
1069 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1070 return To->getKind() == BuiltinType::Int;
1071 }
Mike Stump11289f42009-09-09 15:08:12 +00001072
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001073 // Are we promoting to an unsigned int from an unsigned bitfield
1074 // that fits into an unsigned int?
1075 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1076 return To->getKind() == BuiltinType::UInt;
1077 }
Mike Stump11289f42009-09-09 15:08:12 +00001078
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001079 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001080 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001081 }
Mike Stump11289f42009-09-09 15:08:12 +00001082
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001083 // An rvalue of type bool can be converted to an rvalue of type int,
1084 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001085 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001086 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001087 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001088
1089 return false;
1090}
1091
1092/// IsFloatingPointPromotion - Determines whether the conversion from
1093/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1094/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001095bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001096 /// An rvalue of type float can be converted to an rvalue of type
1097 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001098 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1099 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001100 if (FromBuiltin->getKind() == BuiltinType::Float &&
1101 ToBuiltin->getKind() == BuiltinType::Double)
1102 return true;
1103
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001104 // C99 6.3.1.5p1:
1105 // When a float is promoted to double or long double, or a
1106 // double is promoted to long double [...].
1107 if (!getLangOptions().CPlusPlus &&
1108 (FromBuiltin->getKind() == BuiltinType::Float ||
1109 FromBuiltin->getKind() == BuiltinType::Double) &&
1110 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1111 return true;
1112 }
1113
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001114 return false;
1115}
1116
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001117/// \brief Determine if a conversion is a complex promotion.
1118///
1119/// A complex promotion is defined as a complex -> complex conversion
1120/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001121/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001122bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001123 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001124 if (!FromComplex)
1125 return false;
1126
John McCall9dd450b2009-09-21 23:43:11 +00001127 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001128 if (!ToComplex)
1129 return false;
1130
1131 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001132 ToComplex->getElementType()) ||
1133 IsIntegralPromotion(0, FromComplex->getElementType(),
1134 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001135}
1136
Douglas Gregor237f96c2008-11-26 23:31:11 +00001137/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1138/// the pointer type FromPtr to a pointer to type ToPointee, with the
1139/// same type qualifiers as FromPtr has on its pointee type. ToType,
1140/// if non-empty, will be a pointer to ToType that may or may not have
1141/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001142static QualType
1143BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001144 QualType ToPointee, QualType ToType,
1145 ASTContext &Context) {
1146 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1147 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001148 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001149
1150 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001151 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001152 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001153 if (!ToType.isNull())
Douglas Gregor237f96c2008-11-26 23:31:11 +00001154 return ToType;
1155
1156 // Build a pointer to ToPointee. It has the right qualifiers
1157 // already.
1158 return Context.getPointerType(ToPointee);
1159 }
1160
1161 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +00001162 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001163 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1164 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +00001165}
1166
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001167/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1168/// the FromType, which is an objective-c pointer, to ToType, which may or may
1169/// not have the right set of qualifiers.
1170static QualType
1171BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1172 QualType ToType,
1173 ASTContext &Context) {
1174 QualType CanonFromType = Context.getCanonicalType(FromType);
1175 QualType CanonToType = Context.getCanonicalType(ToType);
1176 Qualifiers Quals = CanonFromType.getQualifiers();
1177
1178 // Exact qualifier match -> return the pointer type we're converting to.
1179 if (CanonToType.getLocalQualifiers() == Quals)
1180 return ToType;
1181
1182 // Just build a canonical type that has the right qualifiers.
1183 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1184}
1185
Mike Stump11289f42009-09-09 15:08:12 +00001186static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001187 bool InOverloadResolution,
1188 ASTContext &Context) {
1189 // Handle value-dependent integral null pointer constants correctly.
1190 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1191 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
1192 Expr->getType()->isIntegralType())
1193 return !InOverloadResolution;
1194
Douglas Gregor56751b52009-09-25 04:25:58 +00001195 return Expr->isNullPointerConstant(Context,
1196 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1197 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001198}
Mike Stump11289f42009-09-09 15:08:12 +00001199
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001200/// IsPointerConversion - Determines whether the conversion of the
1201/// expression From, which has the (possibly adjusted) type FromType,
1202/// can be converted to the type ToType via a pointer conversion (C++
1203/// 4.10). If so, returns true and places the converted type (that
1204/// might differ from ToType in its cv-qualifiers at some level) into
1205/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001206///
Douglas Gregora29dc052008-11-27 01:19:21 +00001207/// This routine also supports conversions to and from block pointers
1208/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1209/// pointers to interfaces. FIXME: Once we've determined the
1210/// appropriate overloading rules for Objective-C, we may want to
1211/// split the Objective-C checks into a different routine; however,
1212/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001213/// conversions, so for now they live here. IncompatibleObjC will be
1214/// set if the conversion is an allowed Objective-C conversion that
1215/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001216bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001217 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001218 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001219 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001220 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001221 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1222 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001223
Mike Stump11289f42009-09-09 15:08:12 +00001224 // Conversion from a null pointer constant to any Objective-C pointer type.
1225 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001226 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001227 ConvertedType = ToType;
1228 return true;
1229 }
1230
Douglas Gregor231d1c62008-11-27 00:15:41 +00001231 // Blocks: Block pointers can be converted to void*.
1232 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001233 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001234 ConvertedType = ToType;
1235 return true;
1236 }
1237 // Blocks: A null pointer constant can be converted to a block
1238 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001239 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001240 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001241 ConvertedType = ToType;
1242 return true;
1243 }
1244
Sebastian Redl576fd422009-05-10 18:38:11 +00001245 // If the left-hand-side is nullptr_t, the right side can be a null
1246 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001247 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001248 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001249 ConvertedType = ToType;
1250 return true;
1251 }
1252
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001253 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001254 if (!ToTypePtr)
1255 return false;
1256
1257 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001258 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001259 ConvertedType = ToType;
1260 return true;
1261 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001262
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001263 // Beyond this point, both types need to be pointers
1264 // , including objective-c pointers.
1265 QualType ToPointeeType = ToTypePtr->getPointeeType();
1266 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1267 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1268 ToType, Context);
1269 return true;
1270
1271 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001272 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001273 if (!FromTypePtr)
1274 return false;
1275
1276 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001277
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001278 // An rvalue of type "pointer to cv T," where T is an object type,
1279 // can be converted to an rvalue of type "pointer to cv void" (C++
1280 // 4.10p2).
Douglas Gregor64259f52009-03-24 20:32:41 +00001281 if (FromPointeeType->isObjectType() && ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001282 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001283 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001284 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001285 return true;
1286 }
1287
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001288 // When we're overloading in C, we allow a special kind of pointer
1289 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001290 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001291 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001292 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001293 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001294 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001295 return true;
1296 }
1297
Douglas Gregor5c407d92008-10-23 00:40:37 +00001298 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001299 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001300 // An rvalue of type "pointer to cv D," where D is a class type,
1301 // can be converted to an rvalue of type "pointer to cv B," where
1302 // B is a base class (clause 10) of D. If B is an inaccessible
1303 // (clause 11) or ambiguous (10.2) base class of D, a program that
1304 // necessitates this conversion is ill-formed. The result of the
1305 // conversion is a pointer to the base class sub-object of the
1306 // derived class object. The null pointer value is converted to
1307 // the null pointer value of the destination type.
1308 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001309 // Note that we do not check for ambiguity or inaccessibility
1310 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001311 if (getLangOptions().CPlusPlus &&
1312 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001313 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001314 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001315 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001316 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001317 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001318 ToType, Context);
1319 return true;
1320 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001321
Douglas Gregora119f102008-12-19 19:13:09 +00001322 return false;
1323}
1324
1325/// isObjCPointerConversion - Determines whether this is an
1326/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1327/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001328bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001329 QualType& ConvertedType,
1330 bool &IncompatibleObjC) {
1331 if (!getLangOptions().ObjC1)
1332 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001333
Steve Naroff7cae42b2009-07-10 23:34:53 +00001334 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001335 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001336 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001337 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001338
Steve Naroff7cae42b2009-07-10 23:34:53 +00001339 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001340 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001341 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001342 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001343 ConvertedType = ToType;
1344 return true;
1345 }
1346 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001347 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001348 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001349 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001350 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001351 ConvertedType = ToType;
1352 return true;
1353 }
1354 // Objective C++: We're able to convert from a pointer to an
1355 // interface to a pointer to a different interface.
1356 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001357 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1358 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1359 if (getLangOptions().CPlusPlus && LHS && RHS &&
1360 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1361 FromObjCPtr->getPointeeType()))
1362 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001363 ConvertedType = ToType;
1364 return true;
1365 }
1366
1367 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1368 // Okay: this is some kind of implicit downcast of Objective-C
1369 // interfaces, which is permitted. However, we're going to
1370 // complain about it.
1371 IncompatibleObjC = true;
1372 ConvertedType = FromType;
1373 return true;
1374 }
Mike Stump11289f42009-09-09 15:08:12 +00001375 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001376 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001377 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001378 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001379 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001380 else if (const BlockPointerType *ToBlockPtr =
1381 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001382 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001383 // to a block pointer type.
1384 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1385 ConvertedType = ToType;
1386 return true;
1387 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001388 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001389 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001390 else if (FromType->getAs<BlockPointerType>() &&
1391 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1392 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001393 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001394 ConvertedType = ToType;
1395 return true;
1396 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001397 else
Douglas Gregora119f102008-12-19 19:13:09 +00001398 return false;
1399
Douglas Gregor033f56d2008-12-23 00:53:59 +00001400 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001401 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001402 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001403 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001404 FromPointeeType = FromBlockPtr->getPointeeType();
1405 else
Douglas Gregora119f102008-12-19 19:13:09 +00001406 return false;
1407
Douglas Gregora119f102008-12-19 19:13:09 +00001408 // If we have pointers to pointers, recursively check whether this
1409 // is an Objective-C conversion.
1410 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1411 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1412 IncompatibleObjC)) {
1413 // We always complain about this conversion.
1414 IncompatibleObjC = true;
1415 ConvertedType = ToType;
1416 return true;
1417 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001418 // Allow conversion of pointee being objective-c pointer to another one;
1419 // as in I* to id.
1420 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1421 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1422 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1423 IncompatibleObjC)) {
1424 ConvertedType = ToType;
1425 return true;
1426 }
1427
Douglas Gregor033f56d2008-12-23 00:53:59 +00001428 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001429 // differences in the argument and result types are in Objective-C
1430 // pointer conversions. If so, we permit the conversion (but
1431 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001432 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001433 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001434 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001435 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001436 if (FromFunctionType && ToFunctionType) {
1437 // If the function types are exactly the same, this isn't an
1438 // Objective-C pointer conversion.
1439 if (Context.getCanonicalType(FromPointeeType)
1440 == Context.getCanonicalType(ToPointeeType))
1441 return false;
1442
1443 // Perform the quick checks that will tell us whether these
1444 // function types are obviously different.
1445 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1446 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1447 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1448 return false;
1449
1450 bool HasObjCConversion = false;
1451 if (Context.getCanonicalType(FromFunctionType->getResultType())
1452 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1453 // Okay, the types match exactly. Nothing to do.
1454 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1455 ToFunctionType->getResultType(),
1456 ConvertedType, IncompatibleObjC)) {
1457 // Okay, we have an Objective-C pointer conversion.
1458 HasObjCConversion = true;
1459 } else {
1460 // Function types are too different. Abort.
1461 return false;
1462 }
Mike Stump11289f42009-09-09 15:08:12 +00001463
Douglas Gregora119f102008-12-19 19:13:09 +00001464 // Check argument types.
1465 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1466 ArgIdx != NumArgs; ++ArgIdx) {
1467 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1468 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1469 if (Context.getCanonicalType(FromArgType)
1470 == Context.getCanonicalType(ToArgType)) {
1471 // Okay, the types match exactly. Nothing to do.
1472 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1473 ConvertedType, IncompatibleObjC)) {
1474 // Okay, we have an Objective-C pointer conversion.
1475 HasObjCConversion = true;
1476 } else {
1477 // Argument types are too different. Abort.
1478 return false;
1479 }
1480 }
1481
1482 if (HasObjCConversion) {
1483 // We had an Objective-C conversion. Allow this pointer
1484 // conversion, but complain about it.
1485 ConvertedType = ToType;
1486 IncompatibleObjC = true;
1487 return true;
1488 }
1489 }
1490
Sebastian Redl72b597d2009-01-25 19:43:20 +00001491 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001492}
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001493
1494/// FunctionArgTypesAreEqual - This routine checks two function proto types
1495/// for equlity of their argument types. Caller has already checked that
1496/// they have same number of arguments. This routine assumes that Objective-C
1497/// pointer types which only differ in their protocol qualifiers are equal.
1498bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1499 FunctionProtoType* NewType){
1500 if (!getLangOptions().ObjC1)
1501 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1502 NewType->arg_type_begin());
1503
1504 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1505 N = NewType->arg_type_begin(),
1506 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1507 QualType ToType = (*O);
1508 QualType FromType = (*N);
1509 if (ToType != FromType) {
1510 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1511 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001512 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1513 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1514 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1515 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001516 continue;
1517 }
1518 else if (ToType->isObjCObjectPointerType() &&
1519 FromType->isObjCObjectPointerType()) {
1520 QualType ToInterfaceTy = ToType->getPointeeType();
1521 QualType FromInterfaceTy = FromType->getPointeeType();
1522 if (const ObjCInterfaceType *OITTo =
1523 ToInterfaceTy->getAs<ObjCInterfaceType>())
1524 if (const ObjCInterfaceType *OITFr =
1525 FromInterfaceTy->getAs<ObjCInterfaceType>())
1526 if (OITTo->getDecl() == OITFr->getDecl())
1527 continue;
1528 }
1529 return false;
1530 }
1531 }
1532 return true;
1533}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001534
Douglas Gregor39c16d42008-10-24 04:54:22 +00001535/// CheckPointerConversion - Check the pointer conversion from the
1536/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001537/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001538/// conversions for which IsPointerConversion has already returned
1539/// true. It returns true and produces a diagnostic if there was an
1540/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001541bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001542 CastExpr::CastKind &Kind,
Anders Carlssona70cff62010-04-24 19:06:50 +00001543 CXXBaseSpecifierArray& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001544 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001545 QualType FromType = From->getType();
1546
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001547 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1548 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001549 QualType FromPointeeType = FromPtrType->getPointeeType(),
1550 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001551
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001552 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1553 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001554 // We must have a derived-to-base conversion. Check an
1555 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001556 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1557 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001558 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001559 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001560 return true;
1561
1562 // The conversion was successful.
1563 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001564 }
1565 }
Mike Stump11289f42009-09-09 15:08:12 +00001566 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001567 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001568 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001569 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001570 // Objective-C++ conversions are always okay.
1571 // FIXME: We should have a different class of conversions for the
1572 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001573 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001574 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001575
Steve Naroff7cae42b2009-07-10 23:34:53 +00001576 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001577 return false;
1578}
1579
Sebastian Redl72b597d2009-01-25 19:43:20 +00001580/// IsMemberPointerConversion - Determines whether the conversion of the
1581/// expression From, which has the (possibly adjusted) type FromType, can be
1582/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1583/// If so, returns true and places the converted type (that might differ from
1584/// ToType in its cv-qualifiers at some level) into ConvertedType.
1585bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001586 QualType ToType,
1587 bool InOverloadResolution,
1588 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001589 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001590 if (!ToTypePtr)
1591 return false;
1592
1593 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001594 if (From->isNullPointerConstant(Context,
1595 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1596 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001597 ConvertedType = ToType;
1598 return true;
1599 }
1600
1601 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001602 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001603 if (!FromTypePtr)
1604 return false;
1605
1606 // A pointer to member of B can be converted to a pointer to member of D,
1607 // where D is derived from B (C++ 4.11p2).
1608 QualType FromClass(FromTypePtr->getClass(), 0);
1609 QualType ToClass(ToTypePtr->getClass(), 0);
1610 // FIXME: What happens when these are dependent? Is this function even called?
1611
1612 if (IsDerivedFrom(ToClass, FromClass)) {
1613 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1614 ToClass.getTypePtr());
1615 return true;
1616 }
1617
1618 return false;
1619}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001620
Sebastian Redl72b597d2009-01-25 19:43:20 +00001621/// CheckMemberPointerConversion - Check the member pointer conversion from the
1622/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001623/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001624/// for which IsMemberPointerConversion has already returned true. It returns
1625/// true and produces a diagnostic if there was an error, or returns false
1626/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001627bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redl7c353682009-11-14 21:15:49 +00001628 CastExpr::CastKind &Kind,
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001629 CXXBaseSpecifierArray &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001630 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001631 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001632 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001633 if (!FromPtrType) {
1634 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001635 assert(From->isNullPointerConstant(Context,
1636 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001637 "Expr must be null pointer constant!");
1638 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001639 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001640 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001641
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001642 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001643 assert(ToPtrType && "No member pointer cast has a target type "
1644 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001645
Sebastian Redled8f2002009-01-28 18:33:18 +00001646 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1647 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001648
Sebastian Redled8f2002009-01-28 18:33:18 +00001649 // FIXME: What about dependent types?
1650 assert(FromClass->isRecordType() && "Pointer into non-class.");
1651 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001652
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001653 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001654 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001655 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1656 assert(DerivationOkay &&
1657 "Should not have been called if derivation isn't OK.");
1658 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001659
Sebastian Redled8f2002009-01-28 18:33:18 +00001660 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1661 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001662 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1663 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1664 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1665 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001666 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001667
Douglas Gregor89ee6822009-02-28 01:32:25 +00001668 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001669 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1670 << FromClass << ToClass << QualType(VBase, 0)
1671 << From->getSourceRange();
1672 return true;
1673 }
1674
John McCall5b0829a2010-02-10 09:31:12 +00001675 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001676 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1677 Paths.front(),
1678 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001679
Anders Carlssond7923c62009-08-22 23:33:40 +00001680 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001681 BuildBasePathArray(Paths, BasePath);
Anders Carlssond7923c62009-08-22 23:33:40 +00001682 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001683 return false;
1684}
1685
Douglas Gregor9a657932008-10-21 23:43:52 +00001686/// IsQualificationConversion - Determines whether the conversion from
1687/// an rvalue of type FromType to ToType is a qualification conversion
1688/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001689bool
1690Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001691 FromType = Context.getCanonicalType(FromType);
1692 ToType = Context.getCanonicalType(ToType);
1693
1694 // If FromType and ToType are the same type, this is not a
1695 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001696 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001697 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001698
Douglas Gregor9a657932008-10-21 23:43:52 +00001699 // (C++ 4.4p4):
1700 // A conversion can add cv-qualifiers at levels other than the first
1701 // in multi-level pointers, subject to the following rules: [...]
1702 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001703 bool UnwrappedAnyPointer = false;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001704 while (UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001705 // Within each iteration of the loop, we check the qualifiers to
1706 // determine if this still looks like a qualification
1707 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001708 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001709 // until there are no more pointers or pointers-to-members left to
1710 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001711 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001712
1713 // -- for every j > 0, if const is in cv 1,j then const is in cv
1714 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001715 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001716 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001717
Douglas Gregor9a657932008-10-21 23:43:52 +00001718 // -- if the cv 1,j and cv 2,j are different, then const is in
1719 // every cv for 0 < k < j.
1720 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001721 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001722 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001723
Douglas Gregor9a657932008-10-21 23:43:52 +00001724 // Keep track of whether all prior cv-qualifiers in the "to" type
1725 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001726 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001727 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001728 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001729
1730 // We are left with FromType and ToType being the pointee types
1731 // after unwrapping the original FromType and ToType the same number
1732 // of types. If we unwrapped any pointers, and if FromType and
1733 // ToType have the same unqualified type (since we checked
1734 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001735 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001736}
1737
Douglas Gregor576e98c2009-01-30 23:27:23 +00001738/// Determines whether there is a user-defined conversion sequence
1739/// (C++ [over.ics.user]) that converts expression From to the type
1740/// ToType. If such a conversion exists, User will contain the
1741/// user-defined conversion sequence that performs such a conversion
1742/// and this routine will return true. Otherwise, this routine returns
1743/// false and User is unspecified.
1744///
Douglas Gregor576e98c2009-01-30 23:27:23 +00001745/// \param AllowExplicit true if the conversion should consider C++0x
1746/// "explicit" conversion functions as well as non-explicit conversion
1747/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor3e1e5272009-12-09 23:02:17 +00001748OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1749 UserDefinedConversionSequence& User,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001750 OverloadCandidateSet& CandidateSet,
1751 bool AllowExplicit) {
1752 // Whether we will only visit constructors.
1753 bool ConstructorsOnly = false;
1754
1755 // If the type we are conversion to is a class type, enumerate its
1756 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001757 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001758 // C++ [over.match.ctor]p1:
1759 // When objects of class type are direct-initialized (8.5), or
1760 // copy-initialized from an expression of the same or a
1761 // derived class type (8.5), overload resolution selects the
1762 // constructor. [...] For copy-initialization, the candidate
1763 // functions are all the converting constructors (12.3.1) of
1764 // that class. The argument list is the expression-list within
1765 // the parentheses of the initializer.
1766 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1767 (From->getType()->getAs<RecordType>() &&
1768 IsDerivedFrom(From->getType(), ToType)))
1769 ConstructorsOnly = true;
1770
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001771 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1772 // We're not going to find any constructors.
1773 } else if (CXXRecordDecl *ToRecordDecl
1774 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00001775 DeclarationName ConstructorName
Douglas Gregor89ee6822009-02-28 01:32:25 +00001776 = Context.DeclarationNames.getCXXConstructorName(
Douglas Gregor5ab11652010-04-17 22:01:05 +00001777 Context.getCanonicalType(ToType).getUnqualifiedType());
Douglas Gregor89ee6822009-02-28 01:32:25 +00001778 DeclContext::lookup_iterator Con, ConEnd;
Mike Stump11289f42009-09-09 15:08:12 +00001779 for (llvm::tie(Con, ConEnd)
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001780 = ToRecordDecl->lookup(ConstructorName);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001781 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00001782 NamedDecl *D = *Con;
1783 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1784
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001785 // Find the constructor (which may be a template).
1786 CXXConstructorDecl *Constructor = 0;
1787 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00001788 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001789 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001790 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001791 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1792 else
John McCalla0296f72010-03-19 07:35:19 +00001793 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001794
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001795 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001796 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001797 if (ConstructorTmpl)
John McCalla0296f72010-03-19 07:35:19 +00001798 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001799 /*ExplicitArgs*/ 0,
John McCall6b51f282009-11-23 01:53:49 +00001800 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001801 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001802 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001803 // Allow one user-defined conversion when user specifies a
1804 // From->ToType conversion via an static cast (c-style, etc).
John McCalla0296f72010-03-19 07:35:19 +00001805 AddOverloadCandidate(Constructor, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001806 &From, 1, CandidateSet,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001807 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001808 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00001809 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001810 }
1811 }
1812
Douglas Gregor5ab11652010-04-17 22:01:05 +00001813 // Enumerate conversion functions, if we're allowed to.
1814 if (ConstructorsOnly) {
Mike Stump11289f42009-09-09 15:08:12 +00001815 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
Douglas Gregor5ab11652010-04-17 22:01:05 +00001816 PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00001817 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00001818 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00001819 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001820 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001821 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1822 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00001823 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00001824 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00001825 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00001826 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00001827 DeclAccessPair FoundDecl = I.getPair();
1828 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00001829 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1830 if (isa<UsingShadowDecl>(D))
1831 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1832
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001833 CXXConversionDecl *Conv;
1834 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00001835 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1836 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001837 else
John McCallda4458e2010-03-31 01:36:47 +00001838 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001839
1840 if (AllowExplicit || !Conv->isExplicit()) {
1841 if (ConvTemplate)
John McCalla0296f72010-03-19 07:35:19 +00001842 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00001843 ActingContext, From, ToType,
1844 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001845 else
John McCalla0296f72010-03-19 07:35:19 +00001846 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCallb89836b2010-01-26 01:37:31 +00001847 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00001848 }
1849 }
1850 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00001851 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001852
1853 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00001854 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001855 case OR_Success:
1856 // Record the standard conversion we used and the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00001857 if (CXXConstructorDecl *Constructor
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001858 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1859 // C++ [over.ics.user]p1:
1860 // If the user-defined conversion is specified by a
1861 // constructor (12.3.1), the initial standard conversion
1862 // sequence converts the source type to the type required by
1863 // the argument of the constructor.
1864 //
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001865 QualType ThisType = Constructor->getThisType(Context);
John McCall0d1da222010-01-12 00:44:57 +00001866 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian55824512009-11-06 00:23:08 +00001867 User.EllipsisConversion = true;
1868 else {
1869 User.Before = Best->Conversions[0].Standard;
1870 User.EllipsisConversion = false;
1871 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001872 User.ConversionFunction = Constructor;
1873 User.After.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +00001874 User.After.setFromType(
1875 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001876 User.After.setAllToTypes(ToType);
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001877 return OR_Success;
Douglas Gregora1f013e2008-11-07 22:36:19 +00001878 } else if (CXXConversionDecl *Conversion
1879 = dyn_cast<CXXConversionDecl>(Best->Function)) {
1880 // C++ [over.ics.user]p1:
1881 //
1882 // [...] If the user-defined conversion is specified by a
1883 // conversion function (12.3.2), the initial standard
1884 // conversion sequence converts the source type to the
1885 // implicit object parameter of the conversion function.
1886 User.Before = Best->Conversions[0].Standard;
1887 User.ConversionFunction = Conversion;
Fariborz Jahanian55824512009-11-06 00:23:08 +00001888 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00001889
1890 // C++ [over.ics.user]p2:
Douglas Gregora1f013e2008-11-07 22:36:19 +00001891 // The second standard conversion sequence converts the
1892 // result of the user-defined conversion to the target type
1893 // for the sequence. Since an implicit conversion sequence
1894 // is an initialization, the special rules for
1895 // initialization by user-defined conversion apply when
1896 // selecting the best user-defined conversion for a
1897 // user-defined conversion sequence (see 13.3.3 and
1898 // 13.3.3.1).
1899 User.After = Best->FinalConversion;
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001900 return OR_Success;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001901 } else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00001902 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001903 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001904 }
Mike Stump11289f42009-09-09 15:08:12 +00001905
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001906 case OR_No_Viable_Function:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001907 return OR_No_Viable_Function;
Douglas Gregor171c45a2009-02-18 21:56:37 +00001908 case OR_Deleted:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001909 // No conversion here! We're done.
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001910 return OR_Deleted;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001911
1912 case OR_Ambiguous:
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001913 return OR_Ambiguous;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001914 }
1915
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00001916 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001917}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001918
1919bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00001920Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001921 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00001922 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001923 OverloadingResult OvResult =
1924 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00001925 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00001926 if (OvResult == OR_Ambiguous)
1927 Diag(From->getSourceRange().getBegin(),
1928 diag::err_typecheck_ambiguous_condition)
1929 << From->getType() << ToType << From->getSourceRange();
1930 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
1931 Diag(From->getSourceRange().getBegin(),
1932 diag::err_typecheck_nonviable_condition)
1933 << From->getType() << ToType << From->getSourceRange();
1934 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001935 return false;
John McCallad907772010-01-12 07:18:19 +00001936 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00001937 return true;
1938}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001939
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001940/// CompareImplicitConversionSequences - Compare two implicit
1941/// conversion sequences to determine whether one is better than the
1942/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump11289f42009-09-09 15:08:12 +00001943ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001944Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
1945 const ImplicitConversionSequence& ICS2)
1946{
1947 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
1948 // conversion sequences (as defined in 13.3.3.1)
1949 // -- a standard conversion sequence (13.3.3.1.1) is a better
1950 // conversion sequence than a user-defined conversion sequence or
1951 // an ellipsis conversion sequence, and
1952 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
1953 // conversion sequence than an ellipsis conversion sequence
1954 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00001955 //
John McCall0d1da222010-01-12 00:44:57 +00001956 // C++0x [over.best.ics]p10:
1957 // For the purpose of ranking implicit conversion sequences as
1958 // described in 13.3.3.2, the ambiguous conversion sequence is
1959 // treated as a user-defined sequence that is indistinguishable
1960 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00001961 if (ICS1.getKindRank() < ICS2.getKindRank())
1962 return ImplicitConversionSequence::Better;
1963 else if (ICS2.getKindRank() < ICS1.getKindRank())
1964 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001965
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00001966 // The following checks require both conversion sequences to be of
1967 // the same kind.
1968 if (ICS1.getKind() != ICS2.getKind())
1969 return ImplicitConversionSequence::Indistinguishable;
1970
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001971 // Two implicit conversion sequences of the same form are
1972 // indistinguishable conversion sequences unless one of the
1973 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00001974 if (ICS1.isStandard())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001975 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00001976 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001977 // User-defined conversion sequence U1 is a better conversion
1978 // sequence than another user-defined conversion sequence U2 if
1979 // they contain the same user-defined conversion function or
1980 // constructor and if the second standard conversion sequence of
1981 // U1 is better than the second standard conversion sequence of
1982 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00001983 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001984 ICS2.UserDefined.ConversionFunction)
1985 return CompareStandardConversionSequences(ICS1.UserDefined.After,
1986 ICS2.UserDefined.After);
1987 }
1988
1989 return ImplicitConversionSequence::Indistinguishable;
1990}
1991
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001992// Per 13.3.3.2p3, compare the given standard conversion sequences to
1993// determine if one is a proper subset of the other.
1994static ImplicitConversionSequence::CompareKind
1995compareStandardConversionSubsets(ASTContext &Context,
1996 const StandardConversionSequence& SCS1,
1997 const StandardConversionSequence& SCS2) {
1998 ImplicitConversionSequence::CompareKind Result
1999 = ImplicitConversionSequence::Indistinguishable;
2000
2001 if (SCS1.Second != SCS2.Second) {
2002 if (SCS1.Second == ICK_Identity)
2003 Result = ImplicitConversionSequence::Better;
2004 else if (SCS2.Second == ICK_Identity)
2005 Result = ImplicitConversionSequence::Worse;
2006 else
2007 return ImplicitConversionSequence::Indistinguishable;
2008 } else if (!Context.hasSameType(SCS1.getToType(1), SCS2.getToType(1)))
2009 return ImplicitConversionSequence::Indistinguishable;
2010
2011 if (SCS1.Third == SCS2.Third) {
2012 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2013 : ImplicitConversionSequence::Indistinguishable;
2014 }
2015
2016 if (SCS1.Third == ICK_Identity)
2017 return Result == ImplicitConversionSequence::Worse
2018 ? ImplicitConversionSequence::Indistinguishable
2019 : ImplicitConversionSequence::Better;
2020
2021 if (SCS2.Third == ICK_Identity)
2022 return Result == ImplicitConversionSequence::Better
2023 ? ImplicitConversionSequence::Indistinguishable
2024 : ImplicitConversionSequence::Worse;
2025
2026 return ImplicitConversionSequence::Indistinguishable;
2027}
2028
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002029/// CompareStandardConversionSequences - Compare two standard
2030/// conversion sequences to determine whether one is better than the
2031/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002032ImplicitConversionSequence::CompareKind
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002033Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
2034 const StandardConversionSequence& SCS2)
2035{
2036 // Standard conversion sequence S1 is a better conversion sequence
2037 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2038
2039 // -- S1 is a proper subsequence of S2 (comparing the conversion
2040 // sequences in the canonical form defined by 13.3.3.1.1,
2041 // excluding any Lvalue Transformation; the identity conversion
2042 // sequence is considered to be a subsequence of any
2043 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002044 if (ImplicitConversionSequence::CompareKind CK
2045 = compareStandardConversionSubsets(Context, SCS1, SCS2))
2046 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002047
2048 // -- the rank of S1 is better than the rank of S2 (by the rules
2049 // defined below), or, if not that,
2050 ImplicitConversionRank Rank1 = SCS1.getRank();
2051 ImplicitConversionRank Rank2 = SCS2.getRank();
2052 if (Rank1 < Rank2)
2053 return ImplicitConversionSequence::Better;
2054 else if (Rank2 < Rank1)
2055 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002056
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002057 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2058 // are indistinguishable unless one of the following rules
2059 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002060
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002061 // A conversion that is not a conversion of a pointer, or
2062 // pointer to member, to bool is better than another conversion
2063 // that is such a conversion.
2064 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2065 return SCS2.isPointerConversionToBool()
2066 ? ImplicitConversionSequence::Better
2067 : ImplicitConversionSequence::Worse;
2068
Douglas Gregor5c407d92008-10-23 00:40:37 +00002069 // C++ [over.ics.rank]p4b2:
2070 //
2071 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002072 // conversion of B* to A* is better than conversion of B* to
2073 // void*, and conversion of A* to void* is better than conversion
2074 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002075 bool SCS1ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00002076 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump11289f42009-09-09 15:08:12 +00002077 bool SCS2ConvertsToVoid
Douglas Gregor5c407d92008-10-23 00:40:37 +00002078 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002079 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2080 // Exactly one of the conversion sequences is a conversion to
2081 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002082 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2083 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002084 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2085 // Neither conversion sequence converts to a void pointer; compare
2086 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002087 if (ImplicitConversionSequence::CompareKind DerivedCK
2088 = CompareDerivedToBaseConversions(SCS1, SCS2))
2089 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002090 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2091 // Both conversion sequences are conversions to void
2092 // pointers. Compare the source types to determine if there's an
2093 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002094 QualType FromType1 = SCS1.getFromType();
2095 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002096
2097 // Adjust the types we're converting from via the array-to-pointer
2098 // conversion, if we need to.
2099 if (SCS1.First == ICK_Array_To_Pointer)
2100 FromType1 = Context.getArrayDecayedType(FromType1);
2101 if (SCS2.First == ICK_Array_To_Pointer)
2102 FromType2 = Context.getArrayDecayedType(FromType2);
2103
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002104 QualType FromPointee1
2105 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2106 QualType FromPointee2
2107 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002108
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002109 if (IsDerivedFrom(FromPointee2, FromPointee1))
2110 return ImplicitConversionSequence::Better;
2111 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2112 return ImplicitConversionSequence::Worse;
2113
2114 // Objective-C++: If one interface is more specific than the
2115 // other, it is the better one.
2116 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2117 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2118 if (FromIface1 && FromIface1) {
2119 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2120 return ImplicitConversionSequence::Better;
2121 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2122 return ImplicitConversionSequence::Worse;
2123 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002124 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002125
2126 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2127 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002128 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002129 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002130 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002131
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002132 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00002133 // C++0x [over.ics.rank]p3b4:
2134 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2135 // implicit object parameter of a non-static member function declared
2136 // without a ref-qualifier, and S1 binds an rvalue reference to an
2137 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00002138 // FIXME: We don't know if we're dealing with the implicit object parameter,
2139 // or if the member function in this case has a ref qualifier.
2140 // (Of course, we don't have ref qualifiers yet.)
2141 if (SCS1.RRefBinding != SCS2.RRefBinding)
2142 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2143 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00002144
2145 // C++ [over.ics.rank]p3b4:
2146 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2147 // which the references refer are the same type except for
2148 // top-level cv-qualifiers, and the type to which the reference
2149 // initialized by S2 refers is more cv-qualified than the type
2150 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002151 QualType T1 = SCS1.getToType(2);
2152 QualType T2 = SCS2.getToType(2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002153 T1 = Context.getCanonicalType(T1);
2154 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002155 Qualifiers T1Quals, T2Quals;
2156 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2157 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2158 if (UnqualT1 == UnqualT2) {
2159 // If the type is an array type, promote the element qualifiers to the type
2160 // for comparison.
2161 if (isa<ArrayType>(T1) && T1Quals)
2162 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2163 if (isa<ArrayType>(T2) && T2Quals)
2164 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002165 if (T2.isMoreQualifiedThan(T1))
2166 return ImplicitConversionSequence::Better;
2167 else if (T1.isMoreQualifiedThan(T2))
2168 return ImplicitConversionSequence::Worse;
2169 }
2170 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002171
2172 return ImplicitConversionSequence::Indistinguishable;
2173}
2174
2175/// CompareQualificationConversions - Compares two standard conversion
2176/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002177/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2178ImplicitConversionSequence::CompareKind
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002179Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump11289f42009-09-09 15:08:12 +00002180 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002181 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002182 // -- S1 and S2 differ only in their qualification conversion and
2183 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2184 // cv-qualification signature of type T1 is a proper subset of
2185 // the cv-qualification signature of type T2, and S1 is not the
2186 // deprecated string literal array-to-pointer conversion (4.2).
2187 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2188 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2189 return ImplicitConversionSequence::Indistinguishable;
2190
2191 // FIXME: the example in the standard doesn't use a qualification
2192 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002193 QualType T1 = SCS1.getToType(2);
2194 QualType T2 = SCS2.getToType(2);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002195 T1 = Context.getCanonicalType(T1);
2196 T2 = Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002197 Qualifiers T1Quals, T2Quals;
2198 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2199 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002200
2201 // If the types are the same, we won't learn anything by unwrapped
2202 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002203 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002204 return ImplicitConversionSequence::Indistinguishable;
2205
Chandler Carruth607f38e2009-12-29 07:16:59 +00002206 // If the type is an array type, promote the element qualifiers to the type
2207 // for comparison.
2208 if (isa<ArrayType>(T1) && T1Quals)
2209 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2210 if (isa<ArrayType>(T2) && T2Quals)
2211 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2212
Mike Stump11289f42009-09-09 15:08:12 +00002213 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002214 = ImplicitConversionSequence::Indistinguishable;
2215 while (UnwrapSimilarPointerTypes(T1, T2)) {
2216 // Within each iteration of the loop, we check the qualifiers to
2217 // determine if this still looks like a qualification
2218 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002219 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002220 // until there are no more pointers or pointers-to-members left
2221 // to unwrap. This essentially mimics what
2222 // IsQualificationConversion does, but here we're checking for a
2223 // strict subset of qualifiers.
2224 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2225 // The qualifiers are the same, so this doesn't tell us anything
2226 // about how the sequences rank.
2227 ;
2228 else if (T2.isMoreQualifiedThan(T1)) {
2229 // T1 has fewer qualifiers, so it could be the better sequence.
2230 if (Result == ImplicitConversionSequence::Worse)
2231 // Neither has qualifiers that are a subset of the other's
2232 // qualifiers.
2233 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002234
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002235 Result = ImplicitConversionSequence::Better;
2236 } else if (T1.isMoreQualifiedThan(T2)) {
2237 // T2 has fewer qualifiers, so it could be the better sequence.
2238 if (Result == ImplicitConversionSequence::Better)
2239 // Neither has qualifiers that are a subset of the other's
2240 // qualifiers.
2241 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002242
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002243 Result = ImplicitConversionSequence::Worse;
2244 } else {
2245 // Qualifiers are disjoint.
2246 return ImplicitConversionSequence::Indistinguishable;
2247 }
2248
2249 // If the types after this point are equivalent, we're done.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002250 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002251 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002252 }
2253
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002254 // Check that the winning standard conversion sequence isn't using
2255 // the deprecated string literal array to pointer conversion.
2256 switch (Result) {
2257 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002258 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002259 Result = ImplicitConversionSequence::Indistinguishable;
2260 break;
2261
2262 case ImplicitConversionSequence::Indistinguishable:
2263 break;
2264
2265 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002266 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002267 Result = ImplicitConversionSequence::Indistinguishable;
2268 break;
2269 }
2270
2271 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002272}
2273
Douglas Gregor5c407d92008-10-23 00:40:37 +00002274/// CompareDerivedToBaseConversions - Compares two standard conversion
2275/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002276/// various kinds of derived-to-base conversions (C++
2277/// [over.ics.rank]p4b3). As part of these checks, we also look at
2278/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002279ImplicitConversionSequence::CompareKind
2280Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2281 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002282 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002283 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002284 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002285 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002286
2287 // Adjust the types we're converting from via the array-to-pointer
2288 // conversion, if we need to.
2289 if (SCS1.First == ICK_Array_To_Pointer)
2290 FromType1 = Context.getArrayDecayedType(FromType1);
2291 if (SCS2.First == ICK_Array_To_Pointer)
2292 FromType2 = Context.getArrayDecayedType(FromType2);
2293
2294 // Canonicalize all of the types.
2295 FromType1 = Context.getCanonicalType(FromType1);
2296 ToType1 = Context.getCanonicalType(ToType1);
2297 FromType2 = Context.getCanonicalType(FromType2);
2298 ToType2 = Context.getCanonicalType(ToType2);
2299
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002300 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002301 //
2302 // If class B is derived directly or indirectly from class A and
2303 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002304 //
2305 // For Objective-C, we let A, B, and C also be Objective-C
2306 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002307
2308 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002309 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002310 SCS2.Second == ICK_Pointer_Conversion &&
2311 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2312 FromType1->isPointerType() && FromType2->isPointerType() &&
2313 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002314 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002315 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002316 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002317 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002318 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002319 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002320 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002321 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002322
John McCall9dd450b2009-09-21 23:43:11 +00002323 const ObjCInterfaceType* FromIface1 = FromPointee1->getAs<ObjCInterfaceType>();
2324 const ObjCInterfaceType* FromIface2 = FromPointee2->getAs<ObjCInterfaceType>();
2325 const ObjCInterfaceType* ToIface1 = ToPointee1->getAs<ObjCInterfaceType>();
2326 const ObjCInterfaceType* ToIface2 = ToPointee2->getAs<ObjCInterfaceType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002327
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002328 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002329 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2330 if (IsDerivedFrom(ToPointee1, ToPointee2))
2331 return ImplicitConversionSequence::Better;
2332 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2333 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002334
2335 if (ToIface1 && ToIface2) {
2336 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2337 return ImplicitConversionSequence::Better;
2338 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2339 return ImplicitConversionSequence::Worse;
2340 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002341 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002342
2343 // -- conversion of B* to A* is better than conversion of C* to A*,
2344 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2345 if (IsDerivedFrom(FromPointee2, FromPointee1))
2346 return ImplicitConversionSequence::Better;
2347 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2348 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002349
Douglas Gregor237f96c2008-11-26 23:31:11 +00002350 if (FromIface1 && FromIface2) {
2351 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2352 return ImplicitConversionSequence::Better;
2353 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2354 return ImplicitConversionSequence::Worse;
2355 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002356 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002357 }
2358
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002359 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002360 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2361 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2362 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2363 const MemberPointerType * FromMemPointer1 =
2364 FromType1->getAs<MemberPointerType>();
2365 const MemberPointerType * ToMemPointer1 =
2366 ToType1->getAs<MemberPointerType>();
2367 const MemberPointerType * FromMemPointer2 =
2368 FromType2->getAs<MemberPointerType>();
2369 const MemberPointerType * ToMemPointer2 =
2370 ToType2->getAs<MemberPointerType>();
2371 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2372 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2373 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2374 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2375 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2376 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2377 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2378 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002379 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002380 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2381 if (IsDerivedFrom(ToPointee1, ToPointee2))
2382 return ImplicitConversionSequence::Worse;
2383 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2384 return ImplicitConversionSequence::Better;
2385 }
2386 // conversion of B::* to C::* is better than conversion of A::* to C::*
2387 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2388 if (IsDerivedFrom(FromPointee1, FromPointee2))
2389 return ImplicitConversionSequence::Better;
2390 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2391 return ImplicitConversionSequence::Worse;
2392 }
2393 }
2394
Douglas Gregor5ab11652010-04-17 22:01:05 +00002395 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002396 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002397 // -- binding of an expression of type C to a reference of type
2398 // B& is better than binding an expression of type C to a
2399 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002400 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2401 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002402 if (IsDerivedFrom(ToType1, ToType2))
2403 return ImplicitConversionSequence::Better;
2404 else if (IsDerivedFrom(ToType2, ToType1))
2405 return ImplicitConversionSequence::Worse;
2406 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002407
Douglas Gregor2fe98832008-11-03 19:09:14 +00002408 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002409 // -- binding of an expression of type B to a reference of type
2410 // A& is better than binding an expression of type C to a
2411 // reference of type A&,
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002412 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2413 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002414 if (IsDerivedFrom(FromType2, FromType1))
2415 return ImplicitConversionSequence::Better;
2416 else if (IsDerivedFrom(FromType1, FromType2))
2417 return ImplicitConversionSequence::Worse;
2418 }
2419 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002420
Douglas Gregor5c407d92008-10-23 00:40:37 +00002421 return ImplicitConversionSequence::Indistinguishable;
2422}
2423
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002424/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2425/// determine whether they are reference-related,
2426/// reference-compatible, reference-compatible with added
2427/// qualification, or incompatible, for use in C++ initialization by
2428/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2429/// type, and the first type (T1) is the pointee type of the reference
2430/// type being initialized.
2431Sema::ReferenceCompareResult
2432Sema::CompareReferenceRelationship(SourceLocation Loc,
2433 QualType OrigT1, QualType OrigT2,
2434 bool& DerivedToBase) {
2435 assert(!OrigT1->isReferenceType() &&
2436 "T1 must be the pointee type of the reference type");
2437 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2438
2439 QualType T1 = Context.getCanonicalType(OrigT1);
2440 QualType T2 = Context.getCanonicalType(OrigT2);
2441 Qualifiers T1Quals, T2Quals;
2442 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2443 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2444
2445 // C++ [dcl.init.ref]p4:
2446 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2447 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2448 // T1 is a base class of T2.
2449 if (UnqualT1 == UnqualT2)
2450 DerivedToBase = false;
Douglas Gregor496e8b342010-05-07 19:42:26 +00002451 else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002452 IsDerivedFrom(UnqualT2, UnqualT1))
2453 DerivedToBase = true;
2454 else
2455 return Ref_Incompatible;
2456
2457 // At this point, we know that T1 and T2 are reference-related (at
2458 // least).
2459
2460 // If the type is an array type, promote the element qualifiers to the type
2461 // for comparison.
2462 if (isa<ArrayType>(T1) && T1Quals)
2463 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2464 if (isa<ArrayType>(T2) && T2Quals)
2465 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2466
2467 // C++ [dcl.init.ref]p4:
2468 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2469 // reference-related to T2 and cv1 is the same cv-qualification
2470 // as, or greater cv-qualification than, cv2. For purposes of
2471 // overload resolution, cases for which cv1 is greater
2472 // cv-qualification than cv2 are identified as
2473 // reference-compatible with added qualification (see 13.3.3.2).
2474 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2475 return Ref_Compatible;
2476 else if (T1.isMoreQualifiedThan(T2))
2477 return Ref_Compatible_With_Added_Qualification;
2478 else
2479 return Ref_Related;
2480}
2481
2482/// \brief Compute an implicit conversion sequence for reference
2483/// initialization.
2484static ImplicitConversionSequence
2485TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2486 SourceLocation DeclLoc,
2487 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002488 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002489 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2490
2491 // Most paths end in a failed conversion.
2492 ImplicitConversionSequence ICS;
2493 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2494
2495 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2496 QualType T2 = Init->getType();
2497
2498 // If the initializer is the address of an overloaded function, try
2499 // to resolve the overloaded function. If all goes well, T2 is the
2500 // type of the resulting function.
2501 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2502 DeclAccessPair Found;
2503 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2504 false, Found))
2505 T2 = Fn->getType();
2506 }
2507
2508 // Compute some basic properties of the types and the initializer.
2509 bool isRValRef = DeclType->isRValueReferenceType();
2510 bool DerivedToBase = false;
Douglas Gregoradc7a702010-04-16 17:45:54 +00002511 Expr::isLvalueResult InitLvalue = Init->isLvalue(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002512 Sema::ReferenceCompareResult RefRelationship
2513 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase);
2514
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002515
2516 // C++ [over.ics.ref]p3:
2517 // Except for an implicit object parameter, for which see 13.3.1,
2518 // a standard conversion sequence cannot be formed if it requires
2519 // binding an lvalue reference to non-const to an rvalue or
2520 // binding an rvalue reference to an lvalue.
Douglas Gregor870f3742010-04-18 09:22:00 +00002521 //
2522 // FIXME: DPG doesn't trust this code. It seems far too early to
2523 // abort because of a binding of an rvalue reference to an lvalue.
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002524 if (isRValRef && InitLvalue == Expr::LV_Valid)
2525 return ICS;
2526
Douglas Gregor870f3742010-04-18 09:22:00 +00002527 // C++0x [dcl.init.ref]p16:
2528 // A reference to type "cv1 T1" is initialized by an expression
2529 // of type "cv2 T2" as follows:
2530
2531 // -- If the initializer expression
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002532 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2533 // reference-compatible with "cv2 T2," or
2534 //
2535 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2536 if (InitLvalue == Expr::LV_Valid &&
2537 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2538 // C++ [over.ics.ref]p1:
2539 // When a parameter of reference type binds directly (8.5.3)
2540 // to an argument expression, the implicit conversion sequence
2541 // is the identity conversion, unless the argument expression
2542 // has a type that is a derived class of the parameter type,
2543 // in which case the implicit conversion sequence is a
2544 // derived-to-base Conversion (13.3.3.1).
2545 ICS.setStandard();
2546 ICS.Standard.First = ICK_Identity;
2547 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2548 ICS.Standard.Third = ICK_Identity;
2549 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2550 ICS.Standard.setToType(0, T2);
2551 ICS.Standard.setToType(1, T1);
2552 ICS.Standard.setToType(2, T1);
2553 ICS.Standard.ReferenceBinding = true;
2554 ICS.Standard.DirectBinding = true;
2555 ICS.Standard.RRefBinding = false;
2556 ICS.Standard.CopyConstructor = 0;
2557
2558 // Nothing more to do: the inaccessibility/ambiguity check for
2559 // derived-to-base conversions is suppressed when we're
2560 // computing the implicit conversion sequence (C++
2561 // [over.best.ics]p2).
2562 return ICS;
2563 }
2564
2565 // -- has a class type (i.e., T2 is a class type), where T1 is
2566 // not reference-related to T2, and can be implicitly
2567 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2568 // is reference-compatible with "cv3 T3" 92) (this
2569 // conversion is selected by enumerating the applicable
2570 // conversion functions (13.3.1.6) and choosing the best
2571 // one through overload resolution (13.3)),
2572 if (!isRValRef && !SuppressUserConversions && T2->isRecordType() &&
2573 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2574 RefRelationship == Sema::Ref_Incompatible) {
2575 CXXRecordDecl *T2RecordDecl
2576 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2577
2578 OverloadCandidateSet CandidateSet(DeclLoc);
2579 const UnresolvedSetImpl *Conversions
2580 = T2RecordDecl->getVisibleConversionFunctions();
2581 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2582 E = Conversions->end(); I != E; ++I) {
2583 NamedDecl *D = *I;
2584 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2585 if (isa<UsingShadowDecl>(D))
2586 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2587
2588 FunctionTemplateDecl *ConvTemplate
2589 = dyn_cast<FunctionTemplateDecl>(D);
2590 CXXConversionDecl *Conv;
2591 if (ConvTemplate)
2592 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2593 else
2594 Conv = cast<CXXConversionDecl>(D);
2595
2596 // If the conversion function doesn't return a reference type,
2597 // it can't be considered for this conversion.
2598 if (Conv->getConversionType()->isLValueReferenceType() &&
2599 (AllowExplicit || !Conv->isExplicit())) {
2600 if (ConvTemplate)
2601 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2602 Init, DeclType, CandidateSet);
2603 else
2604 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2605 DeclType, CandidateSet);
2606 }
2607 }
2608
2609 OverloadCandidateSet::iterator Best;
2610 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2611 case OR_Success:
2612 // C++ [over.ics.ref]p1:
2613 //
2614 // [...] If the parameter binds directly to the result of
2615 // applying a conversion function to the argument
2616 // expression, the implicit conversion sequence is a
2617 // user-defined conversion sequence (13.3.3.1.2), with the
2618 // second standard conversion sequence either an identity
2619 // conversion or, if the conversion function returns an
2620 // entity of a type that is a derived class of the parameter
2621 // type, a derived-to-base Conversion.
2622 if (!Best->FinalConversion.DirectBinding)
2623 break;
2624
2625 ICS.setUserDefined();
2626 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2627 ICS.UserDefined.After = Best->FinalConversion;
2628 ICS.UserDefined.ConversionFunction = Best->Function;
2629 ICS.UserDefined.EllipsisConversion = false;
2630 assert(ICS.UserDefined.After.ReferenceBinding &&
2631 ICS.UserDefined.After.DirectBinding &&
2632 "Expected a direct reference binding!");
2633 return ICS;
2634
2635 case OR_Ambiguous:
2636 ICS.setAmbiguous();
2637 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2638 Cand != CandidateSet.end(); ++Cand)
2639 if (Cand->Viable)
2640 ICS.Ambiguous.addConversion(Cand->Function);
2641 return ICS;
2642
2643 case OR_No_Viable_Function:
2644 case OR_Deleted:
2645 // There was no suitable conversion, or we found a deleted
2646 // conversion; continue with other checks.
2647 break;
2648 }
2649 }
2650
2651 // -- Otherwise, the reference shall be to a non-volatile const
2652 // type (i.e., cv1 shall be const), or the reference shall be an
2653 // rvalue reference and the initializer expression shall be an rvalue.
Douglas Gregor870f3742010-04-18 09:22:00 +00002654 //
2655 // We actually handle one oddity of C++ [over.ics.ref] at this
2656 // point, which is that, due to p2 (which short-circuits reference
2657 // binding by only attempting a simple conversion for non-direct
2658 // bindings) and p3's strange wording, we allow a const volatile
2659 // reference to bind to an rvalue. Hence the check for the presence
2660 // of "const" rather than checking for "const" being the only
2661 // qualifier.
2662 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002663 return ICS;
2664
Douglas Gregorf93df192010-04-18 08:46:23 +00002665 // -- if T2 is a class type and
2666 // -- the initializer expression is an rvalue and "cv1 T1"
2667 // is reference-compatible with "cv2 T2," or
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002668 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002669 // -- T1 is not reference-related to T2 and the initializer
2670 // expression can be implicitly converted to an rvalue
2671 // of type "cv3 T3" (this conversion is selected by
2672 // enumerating the applicable conversion functions
2673 // (13.3.1.6) and choosing the best one through overload
2674 // resolution (13.3)),
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002675 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002676 // then the reference is bound to the initializer
2677 // expression rvalue in the first case and to the object
2678 // that is the result of the conversion in the second case
2679 // (or, in either case, to the appropriate base class
2680 // subobject of the object).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002681 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002682 // We're only checking the first case here, which is a direct
2683 // binding in C++0x but not in C++03.
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002684 if (InitLvalue != Expr::LV_Valid && T2->isRecordType() &&
2685 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2686 ICS.setStandard();
2687 ICS.Standard.First = ICK_Identity;
2688 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base : ICK_Identity;
2689 ICS.Standard.Third = ICK_Identity;
2690 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2691 ICS.Standard.setToType(0, T2);
2692 ICS.Standard.setToType(1, T1);
2693 ICS.Standard.setToType(2, T1);
2694 ICS.Standard.ReferenceBinding = true;
Douglas Gregorf93df192010-04-18 08:46:23 +00002695 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002696 ICS.Standard.RRefBinding = isRValRef;
2697 ICS.Standard.CopyConstructor = 0;
2698 return ICS;
2699 }
2700
2701 // -- Otherwise, a temporary of type "cv1 T1" is created and
2702 // initialized from the initializer expression using the
2703 // rules for a non-reference copy initialization (8.5). The
2704 // reference is then bound to the temporary. If T1 is
2705 // reference-related to T2, cv1 must be the same
2706 // cv-qualification as, or greater cv-qualification than,
2707 // cv2; otherwise, the program is ill-formed.
2708 if (RefRelationship == Sema::Ref_Related) {
2709 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2710 // we would be reference-compatible or reference-compatible with
2711 // added qualification. But that wasn't the case, so the reference
2712 // initialization fails.
2713 return ICS;
2714 }
2715
2716 // If at least one of the types is a class type, the types are not
2717 // related, and we aren't allowed any user conversions, the
2718 // reference binding fails. This case is important for breaking
2719 // recursion, since TryImplicitConversion below will attempt to
2720 // create a temporary through the use of a copy constructor.
2721 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2722 (T1->isRecordType() || T2->isRecordType()))
2723 return ICS;
2724
2725 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002726 // When a parameter of reference type is not bound directly to
2727 // an argument expression, the conversion sequence is the one
2728 // required to convert the argument expression to the
2729 // underlying type of the reference according to
2730 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2731 // to copy-initializing a temporary of the underlying type with
2732 // the argument expression. Any difference in top-level
2733 // cv-qualification is subsumed by the initialization itself
2734 // and does not constitute a conversion.
2735 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2736 /*AllowExplicit=*/false,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002737 /*InOverloadResolution=*/false);
2738
2739 // Of course, that's still a reference binding.
2740 if (ICS.isStandard()) {
2741 ICS.Standard.ReferenceBinding = true;
2742 ICS.Standard.RRefBinding = isRValRef;
2743 } else if (ICS.isUserDefined()) {
2744 ICS.UserDefined.After.ReferenceBinding = true;
2745 ICS.UserDefined.After.RRefBinding = isRValRef;
2746 }
2747 return ICS;
2748}
2749
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002750/// TryCopyInitialization - Try to copy-initialize a value of type
2751/// ToType from the expression From. Return the implicit conversion
2752/// sequence required to pass this argument, which may be a bad
2753/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00002754/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00002755/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002756static ImplicitConversionSequence
2757TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00002758 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002759 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002760 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002761 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002762 /*FIXME:*/From->getLocStart(),
2763 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002764 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002765
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002766 return S.TryImplicitConversion(From, ToType,
2767 SuppressUserConversions,
2768 /*AllowExplicit=*/false,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00002769 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002770}
2771
Douglas Gregor436424c2008-11-18 23:14:02 +00002772/// TryObjectArgumentInitialization - Try to initialize the object
2773/// parameter of the given member function (@c Method) from the
2774/// expression @p From.
2775ImplicitConversionSequence
John McCall47000992010-01-14 03:28:57 +00002776Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall6e9f8f62009-12-03 04:06:58 +00002777 CXXMethodDecl *Method,
2778 CXXRecordDecl *ActingContext) {
2779 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002780 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
2781 // const volatile object.
2782 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
2783 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
2784 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00002785
2786 // Set up the conversion sequence as a "bad" conversion, to allow us
2787 // to exit early.
2788 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00002789
2790 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00002791 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002792 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002793 FromType = PT->getPointeeType();
2794
2795 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002796
Sebastian Redl931e0bd2009-11-18 20:55:52 +00002797 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00002798 // where X is the class of which the function is a member
2799 // (C++ [over.match.funcs]p4). However, when finding an implicit
2800 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00002801 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00002802 // (C++ [over.match.funcs]p5). We perform a simplified version of
2803 // reference binding here, that allows class rvalues to bind to
2804 // non-constant references.
2805
2806 // First check the qualifiers. We don't care about lvalue-vs-rvalue
2807 // with the implicit object parameter (C++ [over.match.funcs]p5).
2808 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002809 if (ImplicitParamType.getCVRQualifiers()
2810 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00002811 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00002812 ICS.setBad(BadConversionSequence::bad_qualifiers,
2813 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002814 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002815 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002816
2817 // Check that we have either the same type or a derived type. It
2818 // affects the conversion rank.
2819 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00002820 ImplicitConversionKind SecondKind;
2821 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
2822 SecondKind = ICK_Identity;
2823 } else if (IsDerivedFrom(FromType, ClassType))
2824 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00002825 else {
John McCall65eb8792010-02-25 01:37:24 +00002826 ICS.setBad(BadConversionSequence::unrelated_class,
2827 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002828 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00002829 }
Douglas Gregor436424c2008-11-18 23:14:02 +00002830
2831 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00002832 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00002833 ICS.Standard.setAsIdentityConversion();
2834 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00002835 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002836 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00002837 ICS.Standard.ReferenceBinding = true;
2838 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00002839 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00002840 return ICS;
2841}
2842
2843/// PerformObjectArgumentInitialization - Perform initialization of
2844/// the implicit object parameter for the given Method with the given
2845/// expression.
2846bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002847Sema::PerformObjectArgumentInitialization(Expr *&From,
2848 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00002849 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002850 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002851 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00002852 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002853 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00002854
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002855 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002856 FromRecordType = PT->getPointeeType();
2857 DestType = Method->getThisType(Context);
2858 } else {
2859 FromRecordType = From->getType();
2860 DestType = ImplicitParamRecordType;
2861 }
2862
John McCall6e9f8f62009-12-03 04:06:58 +00002863 // Note that we always use the true parent context when performing
2864 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00002865 ImplicitConversionSequence ICS
John McCall6e9f8f62009-12-03 04:06:58 +00002866 = TryObjectArgumentInitialization(From->getType(), Method,
2867 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00002868 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00002869 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00002870 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00002871 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00002872
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002873 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00002874 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00002875
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002876 if (!Context.hasSameType(From->getType(), DestType))
Anders Carlsson0c509ee2010-04-24 16:57:13 +00002877 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
2878 /*isLvalue=*/!From->getType()->isPointerType());
Douglas Gregor436424c2008-11-18 23:14:02 +00002879 return false;
2880}
2881
Douglas Gregor5fb53972009-01-14 15:45:31 +00002882/// TryContextuallyConvertToBool - Attempt to contextually convert the
2883/// expression From to bool (C++0x [conv]p3).
2884ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Mike Stump11289f42009-09-09 15:08:12 +00002885 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00002886 // FIXME: Are these flags correct?
2887 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00002888 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00002889 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00002890}
2891
2892/// PerformContextuallyConvertToBool - Perform a contextual conversion
2893/// of the expression From to bool (C++0x [conv]p3).
2894bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
2895 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall0d1da222010-01-12 00:44:57 +00002896 if (!ICS.isBad())
2897 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002898
Fariborz Jahanian76197412009-11-18 18:26:29 +00002899 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002900 return Diag(From->getSourceRange().getBegin(),
2901 diag::err_typecheck_bool_condition)
2902 << From->getType() << From->getSourceRange();
2903 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00002904}
2905
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002906/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00002907/// candidate functions, using the given function call arguments. If
2908/// @p SuppressUserConversions, then don't allow user-defined
2909/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00002910///
2911/// \para PartialOverloading true if we are performing "partial" overloading
2912/// based on an incomplete set of function arguments. This feature is used by
2913/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00002914void
2915Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00002916 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002917 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00002918 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00002919 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00002920 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00002921 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00002922 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002923 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00002924 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00002925 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00002926
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002927 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00002928 if (!isa<CXXConstructorDecl>(Method)) {
2929 // If we get here, it's because we're calling a member function
2930 // that is named without a member access expression (e.g.,
2931 // "this->f") that was either written explicitly or created
2932 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00002933 // function, e.g., X::f(). We use an empty type for the implied
2934 // object argument (C++ [over.call.func]p3), and the acting context
2935 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00002936 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00002937 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00002938 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00002939 return;
2940 }
2941 // We treat a constructor like a non-member function, since its object
2942 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002943 }
2944
Douglas Gregorff7028a2009-11-13 23:59:09 +00002945 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00002946 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00002947
Douglas Gregor27381f32009-11-23 12:27:39 +00002948 // Overload resolution is always an unevaluated context.
2949 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
2950
Douglas Gregorffe14e32009-11-14 01:20:54 +00002951 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
2952 // C++ [class.copy]p3:
2953 // A member function template is never instantiated to perform the copy
2954 // of a class object to an object of its class type.
2955 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
2956 if (NumArgs == 1 &&
2957 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00002958 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
2959 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00002960 return;
2961 }
2962
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002963 // Add this candidate
2964 CandidateSet.push_back(OverloadCandidate());
2965 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00002966 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002967 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002968 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00002969 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00002970 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002971
2972 unsigned NumArgsInProto = Proto->getNumArgs();
2973
2974 // (C++ 13.3.2p2): A candidate function having fewer than m
2975 // parameters is viable only if it has an ellipsis in its parameter
2976 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00002977 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
2978 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002979 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002980 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002981 return;
2982 }
2983
2984 // (C++ 13.3.2p2): A candidate function having more than m parameters
2985 // is viable only if the (m+1)st parameter has a default argument
2986 // (8.3.6). For the purposes of overload resolution, the
2987 // parameter list is truncated on the right, so that there are
2988 // exactly m parameters.
2989 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00002990 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002991 // Not enough arguments.
2992 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00002993 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002994 return;
2995 }
2996
2997 // Determine the implicit conversion sequences for each of the
2998 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002999 Candidate.Conversions.resize(NumArgs);
3000 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3001 if (ArgIdx < NumArgsInProto) {
3002 // (C++ 13.3.2p3): for F to be a viable function, there shall
3003 // exist for each argument an implicit conversion sequence
3004 // (13.3.3.1) that converts that argument to the corresponding
3005 // parameter of F.
3006 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003007 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003008 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00003009 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003010 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003011 if (Candidate.Conversions[ArgIdx].isBad()) {
3012 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003013 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003014 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003015 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003016 } else {
3017 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3018 // argument for which there is no corresponding parameter is
3019 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003020 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003021 }
3022 }
3023}
3024
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003025/// \brief Add all of the function declarations in the given function set to
3026/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003027void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003028 Expr **Args, unsigned NumArgs,
3029 OverloadCandidateSet& CandidateSet,
3030 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003031 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003032 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3033 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003034 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003035 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003036 cast<CXXMethodDecl>(FD)->getParent(),
3037 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003038 CandidateSet, SuppressUserConversions);
3039 else
John McCalla0296f72010-03-19 07:35:19 +00003040 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003041 SuppressUserConversions);
3042 } else {
John McCalla0296f72010-03-19 07:35:19 +00003043 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003044 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3045 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003046 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003047 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003048 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003049 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003050 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003051 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003052 else
John McCalla0296f72010-03-19 07:35:19 +00003053 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003054 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003055 Args, NumArgs, CandidateSet,
3056 SuppressUserConversions);
3057 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003058 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003059}
3060
John McCallf0f1cf02009-11-17 07:50:12 +00003061/// AddMethodCandidate - Adds a named decl (which is some kind of
3062/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003063void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003064 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00003065 Expr **Args, unsigned NumArgs,
3066 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003067 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003068 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003069 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003070
3071 if (isa<UsingShadowDecl>(Decl))
3072 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3073
3074 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3075 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3076 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003077 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3078 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003079 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003080 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003081 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003082 } else {
John McCalla0296f72010-03-19 07:35:19 +00003083 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00003084 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003085 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003086 }
3087}
3088
Douglas Gregor436424c2008-11-18 23:14:02 +00003089/// AddMethodCandidate - Adds the given C++ member function to the set
3090/// of candidate functions, using the given function call arguments
3091/// and the object argument (@c Object). For example, in a call
3092/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3093/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3094/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003095/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003096void
John McCalla0296f72010-03-19 07:35:19 +00003097Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003098 CXXRecordDecl *ActingContext, QualType ObjectType,
3099 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003100 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003101 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003102 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003103 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003104 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003105 assert(!isa<CXXConstructorDecl>(Method) &&
3106 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003107
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003108 if (!CandidateSet.isNewCandidate(Method))
3109 return;
3110
Douglas Gregor27381f32009-11-23 12:27:39 +00003111 // Overload resolution is always an unevaluated context.
3112 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3113
Douglas Gregor436424c2008-11-18 23:14:02 +00003114 // Add this candidate
3115 CandidateSet.push_back(OverloadCandidate());
3116 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003117 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003118 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003119 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003120 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003121
3122 unsigned NumArgsInProto = Proto->getNumArgs();
3123
3124 // (C++ 13.3.2p2): A candidate function having fewer than m
3125 // parameters is viable only if it has an ellipsis in its parameter
3126 // list (8.3.5).
3127 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3128 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003129 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003130 return;
3131 }
3132
3133 // (C++ 13.3.2p2): A candidate function having more than m parameters
3134 // is viable only if the (m+1)st parameter has a default argument
3135 // (8.3.6). For the purposes of overload resolution, the
3136 // parameter list is truncated on the right, so that there are
3137 // exactly m parameters.
3138 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3139 if (NumArgs < MinRequiredArgs) {
3140 // Not enough arguments.
3141 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003142 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003143 return;
3144 }
3145
3146 Candidate.Viable = true;
3147 Candidate.Conversions.resize(NumArgs + 1);
3148
John McCall6e9f8f62009-12-03 04:06:58 +00003149 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003150 // The implicit object argument is ignored.
3151 Candidate.IgnoreObjectArgument = true;
3152 else {
3153 // Determine the implicit conversion sequence for the object
3154 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00003155 Candidate.Conversions[0]
3156 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003157 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003158 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003159 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003160 return;
3161 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003162 }
3163
3164 // Determine the implicit conversion sequences for each of the
3165 // arguments.
3166 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3167 if (ArgIdx < NumArgsInProto) {
3168 // (C++ 13.3.2p3): for F to be a viable function, there shall
3169 // exist for each argument an implicit conversion sequence
3170 // (13.3.3.1) that converts that argument to the corresponding
3171 // parameter of F.
3172 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003173 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003174 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003175 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003176 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003177 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003178 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003179 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003180 break;
3181 }
3182 } else {
3183 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3184 // argument for which there is no corresponding parameter is
3185 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003186 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003187 }
3188 }
3189}
Douglas Gregor3626a5c2010-05-08 17:41:32 +00003190
Douglas Gregor97628d62009-08-21 00:16:32 +00003191/// \brief Add a C++ member function template as a candidate to the candidate
3192/// set, using template argument deduction to produce an appropriate member
3193/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003194void
Douglas Gregor97628d62009-08-21 00:16:32 +00003195Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003196 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003197 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003198 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003199 QualType ObjectType,
3200 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003201 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003202 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003203 if (!CandidateSet.isNewCandidate(MethodTmpl))
3204 return;
3205
Douglas Gregor97628d62009-08-21 00:16:32 +00003206 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003207 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003208 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003209 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003210 // candidate functions in the usual way.113) A given name can refer to one
3211 // or more function templates and also to a set of overloaded non-template
3212 // functions. In such a case, the candidate functions generated from each
3213 // function template are combined with the set of non-template candidate
3214 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003215 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003216 FunctionDecl *Specialization = 0;
3217 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003218 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003219 Args, NumArgs, Specialization, Info)) {
3220 // FIXME: Record what happened with template argument deduction, so
3221 // that we can give the user a beautiful diagnostic.
3222 (void)Result;
3223 return;
3224 }
Mike Stump11289f42009-09-09 15:08:12 +00003225
Douglas Gregor97628d62009-08-21 00:16:32 +00003226 // Add the function template specialization produced by template argument
3227 // deduction as a candidate.
3228 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003229 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003230 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003231 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003232 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003233 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003234}
3235
Douglas Gregor05155d82009-08-21 23:19:43 +00003236/// \brief Add a C++ function template specialization as a candidate
3237/// in the candidate set, using template argument deduction to produce
3238/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003239void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003240Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003241 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003242 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003243 Expr **Args, unsigned NumArgs,
3244 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003245 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003246 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3247 return;
3248
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003249 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003250 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003251 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003252 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003253 // candidate functions in the usual way.113) A given name can refer to one
3254 // or more function templates and also to a set of overloaded non-template
3255 // functions. In such a case, the candidate functions generated from each
3256 // function template are combined with the set of non-template candidate
3257 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003258 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003259 FunctionDecl *Specialization = 0;
3260 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003261 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003262 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003263 CandidateSet.push_back(OverloadCandidate());
3264 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003265 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003266 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3267 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003268 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003269 Candidate.IsSurrogate = false;
3270 Candidate.IgnoreObjectArgument = false;
Douglas Gregor3626a5c2010-05-08 17:41:32 +00003271 Candidate.DeductionFailure = MakeDeductionFailureInfo(Result, Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003272 return;
3273 }
Mike Stump11289f42009-09-09 15:08:12 +00003274
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003275 // Add the function template specialization produced by template argument
3276 // deduction as a candidate.
3277 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003278 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003279 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003280}
Mike Stump11289f42009-09-09 15:08:12 +00003281
Douglas Gregora1f013e2008-11-07 22:36:19 +00003282/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003283/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003284/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003285/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003286/// (which may or may not be the same type as the type that the
3287/// conversion function produces).
3288void
3289Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003290 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003291 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003292 Expr *From, QualType ToType,
3293 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003294 assert(!Conversion->getDescribedFunctionTemplate() &&
3295 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003296 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003297 if (!CandidateSet.isNewCandidate(Conversion))
3298 return;
3299
Douglas Gregor27381f32009-11-23 12:27:39 +00003300 // Overload resolution is always an unevaluated context.
3301 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3302
Douglas Gregora1f013e2008-11-07 22:36:19 +00003303 // Add this candidate
3304 CandidateSet.push_back(OverloadCandidate());
3305 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003306 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003307 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003308 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003309 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003310 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003311 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003312 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003313
Douglas Gregor436424c2008-11-18 23:14:02 +00003314 // Determine the implicit conversion sequence for the implicit
3315 // object parameter.
Douglas Gregora1f013e2008-11-07 22:36:19 +00003316 Candidate.Viable = true;
3317 Candidate.Conversions.resize(1);
John McCall6e9f8f62009-12-03 04:06:58 +00003318 Candidate.Conversions[0]
3319 = TryObjectArgumentInitialization(From->getType(), Conversion,
3320 ActingContext);
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00003321 // Conversion functions to a different type in the base class is visible in
3322 // the derived class. So, a derived to base conversion should not participate
3323 // in overload resolution.
3324 if (Candidate.Conversions[0].Standard.Second == ICK_Derived_To_Base)
3325 Candidate.Conversions[0].Standard.Second = ICK_Identity;
John McCall0d1da222010-01-12 00:44:57 +00003326 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003327 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003328 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003329 return;
3330 }
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003331
3332 // We won't go through a user-define type conversion function to convert a
3333 // derived to base as such conversions are given Conversion Rank. They only
3334 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3335 QualType FromCanon
3336 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3337 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3338 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3339 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003340 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003341 return;
3342 }
3343
Douglas Gregora1f013e2008-11-07 22:36:19 +00003344 // To determine what the conversion from the result of calling the
3345 // conversion function to the type we're eventually trying to
3346 // convert to (ToType), we need to synthesize a call to the
3347 // conversion function and attempt copy initialization from it. This
3348 // makes sure that we get the right semantics with respect to
3349 // lvalues/rvalues and the type. Fortunately, we can allocate this
3350 // call on the stack and we don't need its arguments to be
3351 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003352 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003353 From->getLocStart());
Douglas Gregora1f013e2008-11-07 22:36:19 +00003354 ImplicitCastExpr ConversionFn(Context.getPointerType(Conversion->getType()),
Eli Friedman06ed2a52009-10-20 08:27:19 +00003355 CastExpr::CK_FunctionToPointerDecay,
Anders Carlsson0c509ee2010-04-24 16:57:13 +00003356 &ConversionRef, CXXBaseSpecifierArray(), false);
Mike Stump11289f42009-09-09 15:08:12 +00003357
3358 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003359 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3360 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00003361 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003362 Conversion->getConversionType().getNonReferenceType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003363 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003364 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003365 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003366 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003367 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003368
John McCall0d1da222010-01-12 00:44:57 +00003369 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003370 case ImplicitConversionSequence::StandardConversion:
3371 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003372
3373 // C++ [over.ics.user]p3:
3374 // If the user-defined conversion is specified by a specialization of a
3375 // conversion function template, the second standard conversion sequence
3376 // shall have exact match rank.
3377 if (Conversion->getPrimaryTemplate() &&
3378 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3379 Candidate.Viable = false;
3380 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3381 }
3382
Douglas Gregora1f013e2008-11-07 22:36:19 +00003383 break;
3384
3385 case ImplicitConversionSequence::BadConversion:
3386 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003387 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003388 break;
3389
3390 default:
Mike Stump11289f42009-09-09 15:08:12 +00003391 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003392 "Can only end up with a standard conversion sequence or failure");
3393 }
3394}
3395
Douglas Gregor05155d82009-08-21 23:19:43 +00003396/// \brief Adds a conversion function template specialization
3397/// candidate to the overload set, using template argument deduction
3398/// to deduce the template arguments of the conversion function
3399/// template from the type that we are converting to (C++
3400/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003401void
Douglas Gregor05155d82009-08-21 23:19:43 +00003402Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003403 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003404 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003405 Expr *From, QualType ToType,
3406 OverloadCandidateSet &CandidateSet) {
3407 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3408 "Only conversion function templates permitted here");
3409
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003410 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3411 return;
3412
John McCallbc077cf2010-02-08 23:07:23 +00003413 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003414 CXXConversionDecl *Specialization = 0;
3415 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003416 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003417 Specialization, Info)) {
3418 // FIXME: Record what happened with template argument deduction, so
3419 // that we can give the user a beautiful diagnostic.
3420 (void)Result;
3421 return;
3422 }
Mike Stump11289f42009-09-09 15:08:12 +00003423
Douglas Gregor05155d82009-08-21 23:19:43 +00003424 // Add the conversion function template specialization produced by
3425 // template argument deduction as a candidate.
3426 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003427 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00003428 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003429}
3430
Douglas Gregorab7897a2008-11-19 22:57:39 +00003431/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3432/// converts the given @c Object to a function pointer via the
3433/// conversion function @c Conversion, and then attempts to call it
3434/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3435/// the type of function that we'll eventually be calling.
3436void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003437 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003438 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003439 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00003440 QualType ObjectType,
3441 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00003442 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003443 if (!CandidateSet.isNewCandidate(Conversion))
3444 return;
3445
Douglas Gregor27381f32009-11-23 12:27:39 +00003446 // Overload resolution is always an unevaluated context.
3447 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3448
Douglas Gregorab7897a2008-11-19 22:57:39 +00003449 CandidateSet.push_back(OverloadCandidate());
3450 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003451 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003452 Candidate.Function = 0;
3453 Candidate.Surrogate = Conversion;
3454 Candidate.Viable = true;
3455 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003456 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003457 Candidate.Conversions.resize(NumArgs + 1);
3458
3459 // Determine the implicit conversion sequence for the implicit
3460 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003461 ImplicitConversionSequence ObjectInit
John McCall6e9f8f62009-12-03 04:06:58 +00003462 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003463 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003464 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003465 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00003466 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003467 return;
3468 }
3469
3470 // The first conversion is actually a user-defined conversion whose
3471 // first conversion is ObjectInit's standard conversion (which is
3472 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00003473 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003474 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003475 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003476 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00003477 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00003478 = Candidate.Conversions[0].UserDefined.Before;
3479 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3480
Mike Stump11289f42009-09-09 15:08:12 +00003481 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00003482 unsigned NumArgsInProto = Proto->getNumArgs();
3483
3484 // (C++ 13.3.2p2): A candidate function having fewer than m
3485 // parameters is viable only if it has an ellipsis in its parameter
3486 // list (8.3.5).
3487 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3488 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003489 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003490 return;
3491 }
3492
3493 // Function types don't have any default arguments, so just check if
3494 // we have enough arguments.
3495 if (NumArgs < NumArgsInProto) {
3496 // Not enough arguments.
3497 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003498 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003499 return;
3500 }
3501
3502 // Determine the implicit conversion sequences for each of the
3503 // arguments.
3504 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3505 if (ArgIdx < NumArgsInProto) {
3506 // (C++ 13.3.2p3): for F to be a viable function, there shall
3507 // exist for each argument an implicit conversion sequence
3508 // (13.3.3.1) that converts that argument to the corresponding
3509 // parameter of F.
3510 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003511 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003512 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003513 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00003514 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00003515 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003516 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003517 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003518 break;
3519 }
3520 } else {
3521 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3522 // argument for which there is no corresponding parameter is
3523 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003524 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003525 }
3526 }
3527}
3528
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003529/// \brief Add overload candidates for overloaded operators that are
3530/// member functions.
3531///
3532/// Add the overloaded operator candidates that are member functions
3533/// for the operator Op that was used in an operator expression such
3534/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3535/// CandidateSet will store the added overload candidates. (C++
3536/// [over.match.oper]).
3537void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3538 SourceLocation OpLoc,
3539 Expr **Args, unsigned NumArgs,
3540 OverloadCandidateSet& CandidateSet,
3541 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003542 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3543
3544 // C++ [over.match.oper]p3:
3545 // For a unary operator @ with an operand of a type whose
3546 // cv-unqualified version is T1, and for a binary operator @ with
3547 // a left operand of a type whose cv-unqualified version is T1 and
3548 // a right operand of a type whose cv-unqualified version is T2,
3549 // three sets of candidate functions, designated member
3550 // candidates, non-member candidates and built-in candidates, are
3551 // constructed as follows:
3552 QualType T1 = Args[0]->getType();
3553 QualType T2;
3554 if (NumArgs > 1)
3555 T2 = Args[1]->getType();
3556
3557 // -- If T1 is a class type, the set of member candidates is the
3558 // result of the qualified lookup of T1::operator@
3559 // (13.3.1.1.1); otherwise, the set of member candidates is
3560 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003561 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003562 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00003563 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003564 return;
Mike Stump11289f42009-09-09 15:08:12 +00003565
John McCall27b18f82009-11-17 02:14:36 +00003566 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
3567 LookupQualifiedName(Operators, T1Rec->getDecl());
3568 Operators.suppressDiagnostics();
3569
Mike Stump11289f42009-09-09 15:08:12 +00003570 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00003571 OperEnd = Operators.end();
3572 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00003573 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00003574 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00003575 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00003576 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00003577 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003578}
3579
Douglas Gregora11693b2008-11-12 17:17:38 +00003580/// AddBuiltinCandidate - Add a candidate for a built-in
3581/// operator. ResultTy and ParamTys are the result and parameter types
3582/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00003583/// arguments being passed to the candidate. IsAssignmentOperator
3584/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00003585/// operator. NumContextualBoolArguments is the number of arguments
3586/// (at the beginning of the argument list) that will be contextually
3587/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00003588void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00003589 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00003590 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003591 bool IsAssignmentOperator,
3592 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00003593 // Overload resolution is always an unevaluated context.
3594 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3595
Douglas Gregora11693b2008-11-12 17:17:38 +00003596 // Add this candidate
3597 CandidateSet.push_back(OverloadCandidate());
3598 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003599 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00003600 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00003601 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003602 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00003603 Candidate.BuiltinTypes.ResultTy = ResultTy;
3604 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3605 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
3606
3607 // Determine the implicit conversion sequences for each of the
3608 // arguments.
3609 Candidate.Viable = true;
3610 Candidate.Conversions.resize(NumArgs);
3611 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00003612 // C++ [over.match.oper]p4:
3613 // For the built-in assignment operators, conversions of the
3614 // left operand are restricted as follows:
3615 // -- no temporaries are introduced to hold the left operand, and
3616 // -- no user-defined conversions are applied to the left
3617 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00003618 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00003619 //
3620 // We block these conversions by turning off user-defined
3621 // conversions, since that is the only way that initialization of
3622 // a reference to a non-class type can occur from something that
3623 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003624 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00003625 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00003626 "Contextual conversion to bool requires bool type");
3627 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
3628 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003629 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003630 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00003631 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00003632 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003633 }
John McCall0d1da222010-01-12 00:44:57 +00003634 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003635 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003636 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003637 break;
3638 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003639 }
3640}
3641
3642/// BuiltinCandidateTypeSet - A set of types that will be used for the
3643/// candidate operator functions for built-in operators (C++
3644/// [over.built]). The types are separated into pointer types and
3645/// enumeration types.
3646class BuiltinCandidateTypeSet {
3647 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003648 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00003649
3650 /// PointerTypes - The set of pointer types that will be used in the
3651 /// built-in candidates.
3652 TypeSet PointerTypes;
3653
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003654 /// MemberPointerTypes - The set of member pointer types that will be
3655 /// used in the built-in candidates.
3656 TypeSet MemberPointerTypes;
3657
Douglas Gregora11693b2008-11-12 17:17:38 +00003658 /// EnumerationTypes - The set of enumeration types that will be
3659 /// used in the built-in candidates.
3660 TypeSet EnumerationTypes;
3661
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003662 /// Sema - The semantic analysis instance where we are building the
3663 /// candidate type set.
3664 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00003665
Douglas Gregora11693b2008-11-12 17:17:38 +00003666 /// Context - The AST context in which we will build the type sets.
3667 ASTContext &Context;
3668
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003669 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3670 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003671 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003672
3673public:
3674 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003675 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00003676
Mike Stump11289f42009-09-09 15:08:12 +00003677 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003678 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00003679
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003680 void AddTypesConvertedFrom(QualType Ty,
3681 SourceLocation Loc,
3682 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003683 bool AllowExplicitConversions,
3684 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00003685
3686 /// pointer_begin - First pointer type found;
3687 iterator pointer_begin() { return PointerTypes.begin(); }
3688
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003689 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003690 iterator pointer_end() { return PointerTypes.end(); }
3691
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003692 /// member_pointer_begin - First member pointer type found;
3693 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
3694
3695 /// member_pointer_end - Past the last member pointer type found;
3696 iterator member_pointer_end() { return MemberPointerTypes.end(); }
3697
Douglas Gregora11693b2008-11-12 17:17:38 +00003698 /// enumeration_begin - First enumeration type found;
3699 iterator enumeration_begin() { return EnumerationTypes.begin(); }
3700
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003701 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00003702 iterator enumeration_end() { return EnumerationTypes.end(); }
3703};
3704
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003705/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00003706/// the set of pointer types along with any more-qualified variants of
3707/// that type. For example, if @p Ty is "int const *", this routine
3708/// will add "int const *", "int const volatile *", "int const
3709/// restrict *", and "int const volatile restrict *" to the set of
3710/// pointer types. Returns true if the add of @p Ty itself succeeded,
3711/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003712///
3713/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003714bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003715BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
3716 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00003717
Douglas Gregora11693b2008-11-12 17:17:38 +00003718 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00003719 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00003720 return false;
3721
John McCall8ccfcb52009-09-24 19:53:00 +00003722 const PointerType *PointerTy = Ty->getAs<PointerType>();
3723 assert(PointerTy && "type was not a pointer type!");
Douglas Gregora11693b2008-11-12 17:17:38 +00003724
John McCall8ccfcb52009-09-24 19:53:00 +00003725 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003726 // Don't add qualified variants of arrays. For one, they're not allowed
3727 // (the qualifier would sink to the element type), and for another, the
3728 // only overload situation where it matters is subscript or pointer +- int,
3729 // and those shouldn't have qualifier variants anyway.
3730 if (PointeeTy->isArrayType())
3731 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003732 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00003733 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00003734 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003735 bool hasVolatile = VisibleQuals.hasVolatile();
3736 bool hasRestrict = VisibleQuals.hasRestrict();
3737
John McCall8ccfcb52009-09-24 19:53:00 +00003738 // Iterate through all strict supersets of BaseCVR.
3739 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3740 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003741 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
3742 // in the types.
3743 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
3744 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00003745 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3746 PointerTypes.insert(Context.getPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00003747 }
3748
3749 return true;
3750}
3751
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003752/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
3753/// to the set of pointer types along with any more-qualified variants of
3754/// that type. For example, if @p Ty is "int const *", this routine
3755/// will add "int const *", "int const volatile *", "int const
3756/// restrict *", and "int const volatile restrict *" to the set of
3757/// pointer types. Returns true if the add of @p Ty itself succeeded,
3758/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00003759///
3760/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003761bool
3762BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
3763 QualType Ty) {
3764 // Insert this type.
3765 if (!MemberPointerTypes.insert(Ty))
3766 return false;
3767
John McCall8ccfcb52009-09-24 19:53:00 +00003768 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
3769 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003770
John McCall8ccfcb52009-09-24 19:53:00 +00003771 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00003772 // Don't add qualified variants of arrays. For one, they're not allowed
3773 // (the qualifier would sink to the element type), and for another, the
3774 // only overload situation where it matters is subscript or pointer +- int,
3775 // and those shouldn't have qualifier variants anyway.
3776 if (PointeeTy->isArrayType())
3777 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00003778 const Type *ClassTy = PointerTy->getClass();
3779
3780 // Iterate through all strict supersets of the pointee type's CVR
3781 // qualifiers.
3782 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
3783 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
3784 if ((CVR | BaseCVR) != CVR) continue;
3785
3786 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
3787 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003788 }
3789
3790 return true;
3791}
3792
Douglas Gregora11693b2008-11-12 17:17:38 +00003793/// AddTypesConvertedFrom - Add each of the types to which the type @p
3794/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003795/// primarily interested in pointer types and enumeration types. We also
3796/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00003797/// AllowUserConversions is true if we should look at the conversion
3798/// functions of a class type, and AllowExplicitConversions if we
3799/// should also include the explicit conversion functions of a class
3800/// type.
Mike Stump11289f42009-09-09 15:08:12 +00003801void
Douglas Gregor5fb53972009-01-14 15:45:31 +00003802BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003803 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00003804 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003805 bool AllowExplicitConversions,
3806 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003807 // Only deal with canonical types.
3808 Ty = Context.getCanonicalType(Ty);
3809
3810 // Look through reference types; they aren't part of the type of an
3811 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003812 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00003813 Ty = RefTy->getPointeeType();
3814
3815 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003816 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00003817
Sebastian Redl65ae2002009-11-05 16:36:20 +00003818 // If we're dealing with an array type, decay to the pointer.
3819 if (Ty->isArrayType())
3820 Ty = SemaRef.Context.getArrayDecayedType(Ty);
3821
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003822 if (const PointerType *PointerTy = Ty->getAs<PointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003823 QualType PointeeTy = PointerTy->getPointeeType();
3824
3825 // Insert our type, and its more-qualified variants, into the set
3826 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003827 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00003828 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00003829 } else if (Ty->isMemberPointerType()) {
3830 // Member pointers are far easier, since the pointee can't be converted.
3831 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
3832 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00003833 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00003834 EnumerationTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00003835 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003836 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003837 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003838 // No conversion functions in incomplete types.
3839 return;
3840 }
Mike Stump11289f42009-09-09 15:08:12 +00003841
Douglas Gregora11693b2008-11-12 17:17:38 +00003842 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00003843 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00003844 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00003845 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003846 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00003847 NamedDecl *D = I.getDecl();
3848 if (isa<UsingShadowDecl>(D))
3849 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00003850
Mike Stump11289f42009-09-09 15:08:12 +00003851 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00003852 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00003853 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00003854 continue;
3855
John McCallda4458e2010-03-31 01:36:47 +00003856 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003857 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003858 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003859 VisibleQuals);
3860 }
Douglas Gregora11693b2008-11-12 17:17:38 +00003861 }
3862 }
3863 }
3864}
3865
Douglas Gregor84605ae2009-08-24 13:43:27 +00003866/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
3867/// the volatile- and non-volatile-qualified assignment operators for the
3868/// given type to the candidate set.
3869static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
3870 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00003871 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00003872 unsigned NumArgs,
3873 OverloadCandidateSet &CandidateSet) {
3874 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00003875
Douglas Gregor84605ae2009-08-24 13:43:27 +00003876 // T& operator=(T&, T)
3877 ParamTypes[0] = S.Context.getLValueReferenceType(T);
3878 ParamTypes[1] = T;
3879 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
3880 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00003881
Douglas Gregor84605ae2009-08-24 13:43:27 +00003882 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
3883 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00003884 ParamTypes[0]
3885 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00003886 ParamTypes[1] = T;
3887 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00003888 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00003889 }
3890}
Mike Stump11289f42009-09-09 15:08:12 +00003891
Sebastian Redl1054fae2009-10-25 17:03:50 +00003892/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
3893/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003894static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
3895 Qualifiers VRQuals;
3896 const RecordType *TyRec;
3897 if (const MemberPointerType *RHSMPType =
3898 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00003899 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003900 else
3901 TyRec = ArgExpr->getType()->getAs<RecordType>();
3902 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00003903 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003904 VRQuals.addVolatile();
3905 VRQuals.addRestrict();
3906 return VRQuals;
3907 }
3908
3909 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00003910 if (!ClassDecl->hasDefinition())
3911 return VRQuals;
3912
John McCallad371252010-01-20 00:46:10 +00003913 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00003914 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003915
John McCallad371252010-01-20 00:46:10 +00003916 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00003917 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00003918 NamedDecl *D = I.getDecl();
3919 if (isa<UsingShadowDecl>(D))
3920 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3921 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003922 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
3923 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
3924 CanTy = ResTypeRef->getPointeeType();
3925 // Need to go down the pointer/mempointer chain and add qualifiers
3926 // as see them.
3927 bool done = false;
3928 while (!done) {
3929 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
3930 CanTy = ResTypePtr->getPointeeType();
3931 else if (const MemberPointerType *ResTypeMPtr =
3932 CanTy->getAs<MemberPointerType>())
3933 CanTy = ResTypeMPtr->getPointeeType();
3934 else
3935 done = true;
3936 if (CanTy.isVolatileQualified())
3937 VRQuals.addVolatile();
3938 if (CanTy.isRestrictQualified())
3939 VRQuals.addRestrict();
3940 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
3941 return VRQuals;
3942 }
3943 }
3944 }
3945 return VRQuals;
3946}
3947
Douglas Gregord08452f2008-11-19 15:42:04 +00003948/// AddBuiltinOperatorCandidates - Add the appropriate built-in
3949/// operator overloads to the candidate set (C++ [over.built]), based
3950/// on the operator @p Op and the arguments given. For example, if the
3951/// operator is a binary '+', this routine might add "int
3952/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00003953void
Mike Stump11289f42009-09-09 15:08:12 +00003954Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00003955 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00003956 Expr **Args, unsigned NumArgs,
3957 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00003958 // The set of "promoted arithmetic types", which are the arithmetic
3959 // types are that preserved by promotion (C++ [over.built]p2). Note
3960 // that the first few of these types are the promoted integral
3961 // types; these types need to be first.
3962 // FIXME: What about complex?
3963 const unsigned FirstIntegralType = 0;
3964 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00003965 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00003966 LastPromotedIntegralType = 13;
3967 const unsigned FirstPromotedArithmeticType = 7,
3968 LastPromotedArithmeticType = 16;
3969 const unsigned NumArithmeticTypes = 16;
3970 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00003971 Context.BoolTy, Context.CharTy, Context.WCharTy,
3972// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00003973 Context.SignedCharTy, Context.ShortTy,
3974 Context.UnsignedCharTy, Context.UnsignedShortTy,
3975 Context.IntTy, Context.LongTy, Context.LongLongTy,
3976 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
3977 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
3978 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00003979 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
3980 "Invalid first promoted integral type");
3981 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
3982 == Context.UnsignedLongLongTy &&
3983 "Invalid last promoted integral type");
3984 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
3985 "Invalid first promoted arithmetic type");
3986 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
3987 == Context.LongDoubleTy &&
3988 "Invalid last promoted arithmetic type");
3989
Douglas Gregora11693b2008-11-12 17:17:38 +00003990 // Find all of the types that the arguments can convert to, but only
3991 // if the operator we're looking at has built-in operator candidates
3992 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00003993 Qualifiers VisibleTypeConversionsQuals;
3994 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00003995 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
3996 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
3997
Douglas Gregor8a2e6012009-08-24 15:23:48 +00003998 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregora11693b2008-11-12 17:17:38 +00003999 if (Op == OO_Less || Op == OO_Greater || Op == OO_LessEqual ||
4000 Op == OO_GreaterEqual || Op == OO_EqualEqual || Op == OO_ExclaimEqual ||
Douglas Gregord08452f2008-11-19 15:42:04 +00004001 Op == OO_Plus || (Op == OO_Minus && NumArgs == 2) || Op == OO_Equal ||
Douglas Gregora11693b2008-11-12 17:17:38 +00004002 Op == OO_PlusEqual || Op == OO_MinusEqual || Op == OO_Subscript ||
Douglas Gregord08452f2008-11-19 15:42:04 +00004003 Op == OO_ArrowStar || Op == OO_PlusPlus || Op == OO_MinusMinus ||
Sebastian Redl1a99f442009-04-16 17:51:27 +00004004 (Op == OO_Star && NumArgs == 1) || Op == OO_Conditional) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004005 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Douglas Gregor5fb53972009-01-14 15:45:31 +00004006 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004007 OpLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004008 true,
4009 (Op == OO_Exclaim ||
4010 Op == OO_AmpAmp ||
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004011 Op == OO_PipePipe),
4012 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004013 }
4014
4015 bool isComparison = false;
4016 switch (Op) {
4017 case OO_None:
4018 case NUM_OVERLOADED_OPERATORS:
4019 assert(false && "Expected an overloaded operator");
4020 break;
4021
Douglas Gregord08452f2008-11-19 15:42:04 +00004022 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00004023 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00004024 goto UnaryStar;
4025 else
4026 goto BinaryStar;
4027 break;
4028
4029 case OO_Plus: // '+' is either unary or binary
4030 if (NumArgs == 1)
4031 goto UnaryPlus;
4032 else
4033 goto BinaryPlus;
4034 break;
4035
4036 case OO_Minus: // '-' is either unary or binary
4037 if (NumArgs == 1)
4038 goto UnaryMinus;
4039 else
4040 goto BinaryMinus;
4041 break;
4042
4043 case OO_Amp: // '&' is either unary or binary
4044 if (NumArgs == 1)
4045 goto UnaryAmp;
4046 else
4047 goto BinaryAmp;
4048
4049 case OO_PlusPlus:
4050 case OO_MinusMinus:
4051 // C++ [over.built]p3:
4052 //
4053 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4054 // is either volatile or empty, there exist candidate operator
4055 // functions of the form
4056 //
4057 // VQ T& operator++(VQ T&);
4058 // T operator++(VQ T&, int);
4059 //
4060 // C++ [over.built]p4:
4061 //
4062 // For every pair (T, VQ), where T is an arithmetic type other
4063 // than bool, and VQ is either volatile or empty, there exist
4064 // candidate operator functions of the form
4065 //
4066 // VQ T& operator--(VQ T&);
4067 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00004068 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004069 Arith < NumArithmeticTypes; ++Arith) {
4070 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00004071 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004072 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00004073
4074 // Non-volatile version.
4075 if (NumArgs == 1)
4076 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4077 else
4078 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004079 // heuristic to reduce number of builtin candidates in the set.
4080 // Add volatile version only if there are conversions to a volatile type.
4081 if (VisibleTypeConversionsQuals.hasVolatile()) {
4082 // Volatile version
4083 ParamTypes[0]
4084 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4085 if (NumArgs == 1)
4086 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4087 else
4088 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4089 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004090 }
4091
4092 // C++ [over.built]p5:
4093 //
4094 // For every pair (T, VQ), where T is a cv-qualified or
4095 // cv-unqualified object type, and VQ is either volatile or
4096 // empty, there exist candidate operator functions of the form
4097 //
4098 // T*VQ& operator++(T*VQ&);
4099 // T*VQ& operator--(T*VQ&);
4100 // T* operator++(T*VQ&, int);
4101 // T* operator--(T*VQ&, int);
4102 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4103 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4104 // Skip pointer types that aren't pointers to object types.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004105 if (!(*Ptr)->getAs<PointerType>()->getPointeeType()->isObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00004106 continue;
4107
Mike Stump11289f42009-09-09 15:08:12 +00004108 QualType ParamTypes[2] = {
4109 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00004110 };
Mike Stump11289f42009-09-09 15:08:12 +00004111
Douglas Gregord08452f2008-11-19 15:42:04 +00004112 // Without volatile
4113 if (NumArgs == 1)
4114 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4115 else
4116 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4117
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004118 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4119 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004120 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00004121 ParamTypes[0]
4122 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00004123 if (NumArgs == 1)
4124 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4125 else
4126 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4127 }
4128 }
4129 break;
4130
4131 UnaryStar:
4132 // C++ [over.built]p6:
4133 // For every cv-qualified or cv-unqualified object type T, there
4134 // exist candidate operator functions of the form
4135 //
4136 // T& operator*(T*);
4137 //
4138 // C++ [over.built]p7:
4139 // For every function type T, there exist candidate operator
4140 // functions of the form
4141 // T& operator*(T*);
4142 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4143 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4144 QualType ParamTy = *Ptr;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004145 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004146 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00004147 &ParamTy, Args, 1, CandidateSet);
4148 }
4149 break;
4150
4151 UnaryPlus:
4152 // C++ [over.built]p8:
4153 // For every type T, there exist candidate operator functions of
4154 // the form
4155 //
4156 // T* operator+(T*);
4157 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4158 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4159 QualType ParamTy = *Ptr;
4160 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4161 }
Mike Stump11289f42009-09-09 15:08:12 +00004162
Douglas Gregord08452f2008-11-19 15:42:04 +00004163 // Fall through
4164
4165 UnaryMinus:
4166 // C++ [over.built]p9:
4167 // For every promoted arithmetic type T, there exist candidate
4168 // operator functions of the form
4169 //
4170 // T operator+(T);
4171 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00004172 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004173 Arith < LastPromotedArithmeticType; ++Arith) {
4174 QualType ArithTy = ArithmeticTypes[Arith];
4175 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4176 }
4177 break;
4178
4179 case OO_Tilde:
4180 // C++ [over.built]p10:
4181 // For every promoted integral type T, there exist candidate
4182 // operator functions of the form
4183 //
4184 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00004185 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004186 Int < LastPromotedIntegralType; ++Int) {
4187 QualType IntTy = ArithmeticTypes[Int];
4188 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4189 }
4190 break;
4191
Douglas Gregora11693b2008-11-12 17:17:38 +00004192 case OO_New:
4193 case OO_Delete:
4194 case OO_Array_New:
4195 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00004196 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00004197 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00004198 break;
4199
4200 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00004201 UnaryAmp:
4202 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00004203 // C++ [over.match.oper]p3:
4204 // -- For the operator ',', the unary operator '&', or the
4205 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00004206 break;
4207
Douglas Gregor84605ae2009-08-24 13:43:27 +00004208 case OO_EqualEqual:
4209 case OO_ExclaimEqual:
4210 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00004211 // For every pointer to member type T, there exist candidate operator
4212 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00004213 //
4214 // bool operator==(T,T);
4215 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00004216 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00004217 MemPtr = CandidateTypes.member_pointer_begin(),
4218 MemPtrEnd = CandidateTypes.member_pointer_end();
4219 MemPtr != MemPtrEnd;
4220 ++MemPtr) {
4221 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4222 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4223 }
Mike Stump11289f42009-09-09 15:08:12 +00004224
Douglas Gregor84605ae2009-08-24 13:43:27 +00004225 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004226
Douglas Gregora11693b2008-11-12 17:17:38 +00004227 case OO_Less:
4228 case OO_Greater:
4229 case OO_LessEqual:
4230 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004231 // C++ [over.built]p15:
4232 //
4233 // For every pointer or enumeration type T, there exist
4234 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004235 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004236 // bool operator<(T, T);
4237 // bool operator>(T, T);
4238 // bool operator<=(T, T);
4239 // bool operator>=(T, T);
4240 // bool operator==(T, T);
4241 // bool operator!=(T, T);
4242 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4243 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4244 QualType ParamTypes[2] = { *Ptr, *Ptr };
4245 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4246 }
Mike Stump11289f42009-09-09 15:08:12 +00004247 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00004248 = CandidateTypes.enumeration_begin();
4249 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4250 QualType ParamTypes[2] = { *Enum, *Enum };
4251 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4252 }
4253
4254 // Fall through.
4255 isComparison = true;
4256
Douglas Gregord08452f2008-11-19 15:42:04 +00004257 BinaryPlus:
4258 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00004259 if (!isComparison) {
4260 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4261
4262 // C++ [over.built]p13:
4263 //
4264 // For every cv-qualified or cv-unqualified object type T
4265 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004266 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004267 // T* operator+(T*, ptrdiff_t);
4268 // T& operator[](T*, ptrdiff_t); [BELOW]
4269 // T* operator-(T*, ptrdiff_t);
4270 // T* operator+(ptrdiff_t, T*);
4271 // T& operator[](ptrdiff_t, T*); [BELOW]
4272 //
4273 // C++ [over.built]p14:
4274 //
4275 // For every T, where T is a pointer to object type, there
4276 // exist candidate operator functions of the form
4277 //
4278 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00004279 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00004280 = CandidateTypes.pointer_begin();
4281 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4282 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4283
4284 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4285 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4286
4287 if (Op == OO_Plus) {
4288 // T* operator+(ptrdiff_t, T*);
4289 ParamTypes[0] = ParamTypes[1];
4290 ParamTypes[1] = *Ptr;
4291 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4292 } else {
4293 // ptrdiff_t operator-(T, T);
4294 ParamTypes[1] = *Ptr;
4295 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4296 Args, 2, CandidateSet);
4297 }
4298 }
4299 }
4300 // Fall through
4301
Douglas Gregora11693b2008-11-12 17:17:38 +00004302 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00004303 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00004304 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00004305 // C++ [over.built]p12:
4306 //
4307 // For every pair of promoted arithmetic types L and R, there
4308 // exist candidate operator functions of the form
4309 //
4310 // LR operator*(L, R);
4311 // LR operator/(L, R);
4312 // LR operator+(L, R);
4313 // LR operator-(L, R);
4314 // bool operator<(L, R);
4315 // bool operator>(L, R);
4316 // bool operator<=(L, R);
4317 // bool operator>=(L, R);
4318 // bool operator==(L, R);
4319 // bool operator!=(L, R);
4320 //
4321 // where LR is the result of the usual arithmetic conversions
4322 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004323 //
4324 // C++ [over.built]p24:
4325 //
4326 // For every pair of promoted arithmetic types L and R, there exist
4327 // candidate operator functions of the form
4328 //
4329 // LR operator?(bool, L, R);
4330 //
4331 // where LR is the result of the usual arithmetic conversions
4332 // between types L and R.
4333 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004334 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004335 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004336 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004337 Right < LastPromotedArithmeticType; ++Right) {
4338 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004339 QualType Result
4340 = isComparison
4341 ? Context.BoolTy
4342 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004343 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4344 }
4345 }
4346 break;
4347
4348 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00004349 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00004350 case OO_Caret:
4351 case OO_Pipe:
4352 case OO_LessLess:
4353 case OO_GreaterGreater:
4354 // C++ [over.built]p17:
4355 //
4356 // For every pair of promoted integral types L and R, there
4357 // exist candidate operator functions of the form
4358 //
4359 // LR operator%(L, R);
4360 // LR operator&(L, R);
4361 // LR operator^(L, R);
4362 // LR operator|(L, R);
4363 // L operator<<(L, R);
4364 // L operator>>(L, R);
4365 //
4366 // where LR is the result of the usual arithmetic conversions
4367 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00004368 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004369 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004370 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004371 Right < LastPromotedIntegralType; ++Right) {
4372 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4373 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4374 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004375 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004376 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4377 }
4378 }
4379 break;
4380
4381 case OO_Equal:
4382 // C++ [over.built]p20:
4383 //
4384 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00004385 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00004386 // empty, there exist candidate operator functions of the form
4387 //
4388 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004389 for (BuiltinCandidateTypeSet::iterator
4390 Enum = CandidateTypes.enumeration_begin(),
4391 EnumEnd = CandidateTypes.enumeration_end();
4392 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00004393 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004394 CandidateSet);
4395 for (BuiltinCandidateTypeSet::iterator
4396 MemPtr = CandidateTypes.member_pointer_begin(),
4397 MemPtrEnd = CandidateTypes.member_pointer_end();
4398 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00004399 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004400 CandidateSet);
4401 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00004402
4403 case OO_PlusEqual:
4404 case OO_MinusEqual:
4405 // C++ [over.built]p19:
4406 //
4407 // For every pair (T, VQ), where T is any type and VQ is either
4408 // volatile or empty, there exist candidate operator functions
4409 // of the form
4410 //
4411 // T*VQ& operator=(T*VQ&, T*);
4412 //
4413 // C++ [over.built]p21:
4414 //
4415 // For every pair (T, VQ), where T is a cv-qualified or
4416 // cv-unqualified object type and VQ is either volatile or
4417 // empty, there exist candidate operator functions of the form
4418 //
4419 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4420 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4421 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4422 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4423 QualType ParamTypes[2];
4424 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4425
4426 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004427 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004428 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4429 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004430
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004431 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4432 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004433 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00004434 ParamTypes[0]
4435 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00004436 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4437 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00004438 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004439 }
4440 // Fall through.
4441
4442 case OO_StarEqual:
4443 case OO_SlashEqual:
4444 // C++ [over.built]p18:
4445 //
4446 // For every triple (L, VQ, R), where L is an arithmetic type,
4447 // VQ is either volatile or empty, and R is a promoted
4448 // arithmetic type, there exist candidate operator functions of
4449 // the form
4450 //
4451 // VQ L& operator=(VQ L&, R);
4452 // VQ L& operator*=(VQ L&, R);
4453 // VQ L& operator/=(VQ L&, R);
4454 // VQ L& operator+=(VQ L&, R);
4455 // VQ L& operator-=(VQ L&, R);
4456 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004457 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004458 Right < LastPromotedArithmeticType; ++Right) {
4459 QualType ParamTypes[2];
4460 ParamTypes[1] = ArithmeticTypes[Right];
4461
4462 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004463 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00004464 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4465 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00004466
4467 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004468 if (VisibleTypeConversionsQuals.hasVolatile()) {
4469 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4470 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4471 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4472 /*IsAssigmentOperator=*/Op == OO_Equal);
4473 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004474 }
4475 }
4476 break;
4477
4478 case OO_PercentEqual:
4479 case OO_LessLessEqual:
4480 case OO_GreaterGreaterEqual:
4481 case OO_AmpEqual:
4482 case OO_CaretEqual:
4483 case OO_PipeEqual:
4484 // C++ [over.built]p22:
4485 //
4486 // For every triple (L, VQ, R), where L is an integral type, VQ
4487 // is either volatile or empty, and R is a promoted integral
4488 // type, there exist candidate operator functions of the form
4489 //
4490 // VQ L& operator%=(VQ L&, R);
4491 // VQ L& operator<<=(VQ L&, R);
4492 // VQ L& operator>>=(VQ L&, R);
4493 // VQ L& operator&=(VQ L&, R);
4494 // VQ L& operator^=(VQ L&, R);
4495 // VQ L& operator|=(VQ L&, R);
4496 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004497 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004498 Right < LastPromotedIntegralType; ++Right) {
4499 QualType ParamTypes[2];
4500 ParamTypes[1] = ArithmeticTypes[Right];
4501
4502 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004503 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004504 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00004505 if (VisibleTypeConversionsQuals.hasVolatile()) {
4506 // Add this built-in operator as a candidate (VQ is 'volatile').
4507 ParamTypes[0] = ArithmeticTypes[Left];
4508 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
4509 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4510 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
4511 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004512 }
4513 }
4514 break;
4515
Douglas Gregord08452f2008-11-19 15:42:04 +00004516 case OO_Exclaim: {
4517 // C++ [over.operator]p23:
4518 //
4519 // There also exist candidate operator functions of the form
4520 //
Mike Stump11289f42009-09-09 15:08:12 +00004521 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00004522 // bool operator&&(bool, bool); [BELOW]
4523 // bool operator||(bool, bool); [BELOW]
4524 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00004525 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
4526 /*IsAssignmentOperator=*/false,
4527 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004528 break;
4529 }
4530
Douglas Gregora11693b2008-11-12 17:17:38 +00004531 case OO_AmpAmp:
4532 case OO_PipePipe: {
4533 // C++ [over.operator]p23:
4534 //
4535 // There also exist candidate operator functions of the form
4536 //
Douglas Gregord08452f2008-11-19 15:42:04 +00004537 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00004538 // bool operator&&(bool, bool);
4539 // bool operator||(bool, bool);
4540 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00004541 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
4542 /*IsAssignmentOperator=*/false,
4543 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00004544 break;
4545 }
4546
4547 case OO_Subscript:
4548 // C++ [over.built]p13:
4549 //
4550 // For every cv-qualified or cv-unqualified object type T there
4551 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004552 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004553 // T* operator+(T*, ptrdiff_t); [ABOVE]
4554 // T& operator[](T*, ptrdiff_t);
4555 // T* operator-(T*, ptrdiff_t); [ABOVE]
4556 // T* operator+(ptrdiff_t, T*); [ABOVE]
4557 // T& operator[](ptrdiff_t, T*);
4558 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4559 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4560 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004561 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004562 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00004563
4564 // T& operator[](T*, ptrdiff_t)
4565 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4566
4567 // T& operator[](ptrdiff_t, T*);
4568 ParamTypes[0] = ParamTypes[1];
4569 ParamTypes[1] = *Ptr;
4570 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4571 }
4572 break;
4573
4574 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004575 // C++ [over.built]p11:
4576 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
4577 // C1 is the same type as C2 or is a derived class of C2, T is an object
4578 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
4579 // there exist candidate operator functions of the form
4580 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
4581 // where CV12 is the union of CV1 and CV2.
4582 {
4583 for (BuiltinCandidateTypeSet::iterator Ptr =
4584 CandidateTypes.pointer_begin();
4585 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4586 QualType C1Ty = (*Ptr);
4587 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004588 QualifierCollector Q1;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004589 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004590 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004591 if (!isa<RecordType>(C1))
4592 continue;
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004593 // heuristic to reduce number of builtin candidates in the set.
4594 // Add volatile/restrict version only if there are conversions to a
4595 // volatile/restrict type.
4596 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
4597 continue;
4598 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
4599 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004600 }
4601 for (BuiltinCandidateTypeSet::iterator
4602 MemPtr = CandidateTypes.member_pointer_begin(),
4603 MemPtrEnd = CandidateTypes.member_pointer_end();
4604 MemPtr != MemPtrEnd; ++MemPtr) {
4605 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
4606 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00004607 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004608 if (C1 != C2 && !IsDerivedFrom(C1, C2))
4609 break;
4610 QualType ParamTypes[2] = { *Ptr, *MemPtr };
4611 // build CV12 T&
4612 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004613 if (!VisibleTypeConversionsQuals.hasVolatile() &&
4614 T.isVolatileQualified())
4615 continue;
4616 if (!VisibleTypeConversionsQuals.hasRestrict() &&
4617 T.isRestrictQualified())
4618 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00004619 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00004620 QualType ResultTy = Context.getLValueReferenceType(T);
4621 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
4622 }
4623 }
4624 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004625 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00004626
4627 case OO_Conditional:
4628 // Note that we don't consider the first argument, since it has been
4629 // contextually converted to bool long ago. The candidates below are
4630 // therefore added as binary.
4631 //
4632 // C++ [over.built]p24:
4633 // For every type T, where T is a pointer or pointer-to-member type,
4634 // there exist candidate operator functions of the form
4635 //
4636 // T operator?(bool, T, T);
4637 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00004638 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
4639 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
4640 QualType ParamTypes[2] = { *Ptr, *Ptr };
4641 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4642 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004643 for (BuiltinCandidateTypeSet::iterator Ptr =
4644 CandidateTypes.member_pointer_begin(),
4645 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
4646 QualType ParamTypes[2] = { *Ptr, *Ptr };
4647 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4648 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00004649 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00004650 }
4651}
4652
Douglas Gregore254f902009-02-04 00:32:51 +00004653/// \brief Add function candidates found via argument-dependent lookup
4654/// to the set of overloading candidates.
4655///
4656/// This routine performs argument-dependent name lookup based on the
4657/// given function name (which may also be an operator name) and adds
4658/// all of the overload candidates found by ADL to the overload
4659/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00004660void
Douglas Gregore254f902009-02-04 00:32:51 +00004661Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00004662 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00004663 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00004664 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00004665 OverloadCandidateSet& CandidateSet,
4666 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00004667 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00004668
John McCall91f61fc2010-01-26 06:04:06 +00004669 // FIXME: This approach for uniquing ADL results (and removing
4670 // redundant candidates from the set) relies on pointer-equality,
4671 // which means we need to key off the canonical decl. However,
4672 // always going back to the canonical decl might not get us the
4673 // right set of default arguments. What default arguments are
4674 // we supposed to consider on ADL candidates, anyway?
4675
Douglas Gregorcabea402009-09-22 15:41:20 +00004676 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00004677 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00004678
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004679 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004680 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
4681 CandEnd = CandidateSet.end();
4682 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00004683 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00004684 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00004685 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00004686 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00004687 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00004688
4689 // For each of the ADL candidates we found, add it to the overload
4690 // set.
John McCall8fe68082010-01-26 07:16:45 +00004691 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00004692 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00004693 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00004694 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00004695 continue;
4696
John McCalla0296f72010-03-19 07:35:19 +00004697 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00004698 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00004699 } else
John McCall4c4c1df2010-01-26 03:27:55 +00004700 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00004701 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004702 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00004703 }
Douglas Gregore254f902009-02-04 00:32:51 +00004704}
4705
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004706/// isBetterOverloadCandidate - Determines whether the first overload
4707/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00004708bool
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004709Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCallbc077cf2010-02-08 23:07:23 +00004710 const OverloadCandidate& Cand2,
4711 SourceLocation Loc) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004712 // Define viable functions to be better candidates than non-viable
4713 // functions.
4714 if (!Cand2.Viable)
4715 return Cand1.Viable;
4716 else if (!Cand1.Viable)
4717 return false;
4718
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004719 // C++ [over.match.best]p1:
4720 //
4721 // -- if F is a static member function, ICS1(F) is defined such
4722 // that ICS1(F) is neither better nor worse than ICS1(G) for
4723 // any function G, and, symmetrically, ICS1(G) is neither
4724 // better nor worse than ICS1(F).
4725 unsigned StartArg = 0;
4726 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
4727 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004728
Douglas Gregord3cb3562009-07-07 23:38:56 +00004729 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00004730 // A viable function F1 is defined to be a better function than another
4731 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00004732 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004733 unsigned NumArgs = Cand1.Conversions.size();
4734 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
4735 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004736 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004737 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
4738 Cand2.Conversions[ArgIdx])) {
4739 case ImplicitConversionSequence::Better:
4740 // Cand1 has a better conversion sequence.
4741 HasBetterConversion = true;
4742 break;
4743
4744 case ImplicitConversionSequence::Worse:
4745 // Cand1 can't be better than Cand2.
4746 return false;
4747
4748 case ImplicitConversionSequence::Indistinguishable:
4749 // Do nothing.
4750 break;
4751 }
4752 }
4753
Mike Stump11289f42009-09-09 15:08:12 +00004754 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00004755 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004756 if (HasBetterConversion)
4757 return true;
4758
Mike Stump11289f42009-09-09 15:08:12 +00004759 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00004760 // specialization, or, if not that,
4761 if (Cand1.Function && !Cand1.Function->getPrimaryTemplate() &&
4762 Cand2.Function && Cand2.Function->getPrimaryTemplate())
4763 return true;
Mike Stump11289f42009-09-09 15:08:12 +00004764
4765 // -- F1 and F2 are function template specializations, and the function
4766 // template for F1 is more specialized than the template for F2
4767 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00004768 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00004769 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
4770 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00004771 if (FunctionTemplateDecl *BetterTemplate
4772 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
4773 Cand2.Function->getPrimaryTemplate(),
John McCallbc077cf2010-02-08 23:07:23 +00004774 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00004775 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
4776 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00004777 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004778
Douglas Gregora1f013e2008-11-07 22:36:19 +00004779 // -- the context is an initialization by user-defined conversion
4780 // (see 8.5, 13.3.1.5) and the standard conversion sequence
4781 // from the return type of F1 to the destination type (i.e.,
4782 // the type of the entity being initialized) is a better
4783 // conversion sequence than the standard conversion sequence
4784 // from the return type of F2 to the destination type.
Mike Stump11289f42009-09-09 15:08:12 +00004785 if (Cand1.Function && Cand2.Function &&
4786 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004787 isa<CXXConversionDecl>(Cand2.Function)) {
4788 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
4789 Cand2.FinalConversion)) {
4790 case ImplicitConversionSequence::Better:
4791 // Cand1 has a better conversion sequence.
4792 return true;
4793
4794 case ImplicitConversionSequence::Worse:
4795 // Cand1 can't be better than Cand2.
4796 return false;
4797
4798 case ImplicitConversionSequence::Indistinguishable:
4799 // Do nothing
4800 break;
4801 }
4802 }
4803
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004804 return false;
4805}
4806
Mike Stump11289f42009-09-09 15:08:12 +00004807/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004808/// within an overload candidate set.
4809///
4810/// \param CandidateSet the set of candidate functions.
4811///
4812/// \param Loc the location of the function name (or operator symbol) for
4813/// which overload resolution occurs.
4814///
Mike Stump11289f42009-09-09 15:08:12 +00004815/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004816/// function, Best points to the candidate function found.
4817///
4818/// \returns The result of overload resolution.
Douglas Gregor3e1e5272009-12-09 23:02:17 +00004819OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
4820 SourceLocation Loc,
4821 OverloadCandidateSet::iterator& Best) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004822 // Find the best viable function.
4823 Best = CandidateSet.end();
4824 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4825 Cand != CandidateSet.end(); ++Cand) {
4826 if (Cand->Viable) {
John McCallbc077cf2010-02-08 23:07:23 +00004827 if (Best == CandidateSet.end() ||
4828 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004829 Best = Cand;
4830 }
4831 }
4832
4833 // If we didn't find any viable functions, abort.
4834 if (Best == CandidateSet.end())
4835 return OR_No_Viable_Function;
4836
4837 // Make sure that this function is better than every other viable
4838 // function. If not, we have an ambiguity.
4839 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
4840 Cand != CandidateSet.end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00004841 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004842 Cand != Best &&
John McCallbc077cf2010-02-08 23:07:23 +00004843 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004844 Best = CandidateSet.end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004845 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004846 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004847 }
Mike Stump11289f42009-09-09 15:08:12 +00004848
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004849 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00004850 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00004851 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00004852 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00004853 return OR_Deleted;
4854
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004855 // C++ [basic.def.odr]p2:
4856 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00004857 // when referred to from a potentially-evaluated expression. [Note: this
4858 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00004859 // (clause 13), user-defined conversions (12.3.2), allocation function for
4860 // placement new (5.3.4), as well as non-default initialization (8.5).
4861 if (Best->Function)
4862 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004863 return OR_Success;
4864}
4865
John McCall53262c92010-01-12 02:15:36 +00004866namespace {
4867
4868enum OverloadCandidateKind {
4869 oc_function,
4870 oc_method,
4871 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004872 oc_function_template,
4873 oc_method_template,
4874 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00004875 oc_implicit_default_constructor,
4876 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00004877 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00004878};
4879
John McCalle1ac8d12010-01-13 00:25:19 +00004880OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
4881 FunctionDecl *Fn,
4882 std::string &Description) {
4883 bool isTemplate = false;
4884
4885 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
4886 isTemplate = true;
4887 Description = S.getTemplateArgumentBindingsText(
4888 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
4889 }
John McCallfd0b2f82010-01-06 09:43:14 +00004890
4891 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00004892 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004893 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004894
John McCall53262c92010-01-12 02:15:36 +00004895 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
4896 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00004897 }
4898
4899 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
4900 // This actually gets spelled 'candidate function' for now, but
4901 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00004902 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00004903 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00004904
4905 assert(Meth->isCopyAssignment()
4906 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00004907 return oc_implicit_copy_assignment;
4908 }
4909
John McCalle1ac8d12010-01-13 00:25:19 +00004910 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00004911}
4912
4913} // end anonymous namespace
4914
4915// Notes the location of an overload candidate.
4916void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00004917 std::string FnDesc;
4918 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
4919 Diag(Fn->getLocation(), diag::note_ovl_candidate)
4920 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00004921}
4922
John McCall0d1da222010-01-12 00:44:57 +00004923/// Diagnoses an ambiguous conversion. The partial diagnostic is the
4924/// "lead" diagnostic; it will be given two arguments, the source and
4925/// target types of the conversion.
4926void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
4927 SourceLocation CaretLoc,
4928 const PartialDiagnostic &PDiag) {
4929 Diag(CaretLoc, PDiag)
4930 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
4931 for (AmbiguousConversionSequence::const_iterator
4932 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
4933 NoteOverloadCandidate(*I);
4934 }
John McCall12f97bc2010-01-08 04:41:39 +00004935}
4936
John McCall0d1da222010-01-12 00:44:57 +00004937namespace {
4938
John McCall6a61b522010-01-13 09:16:55 +00004939void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
4940 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
4941 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00004942 assert(Cand->Function && "for now, candidate must be a function");
4943 FunctionDecl *Fn = Cand->Function;
4944
4945 // There's a conversion slot for the object argument if this is a
4946 // non-constructor method. Note that 'I' corresponds the
4947 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00004948 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00004949 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00004950 if (I == 0)
4951 isObjectArgument = true;
4952 else
4953 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00004954 }
4955
John McCalle1ac8d12010-01-13 00:25:19 +00004956 std::string FnDesc;
4957 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
4958
John McCall6a61b522010-01-13 09:16:55 +00004959 Expr *FromExpr = Conv.Bad.FromExpr;
4960 QualType FromTy = Conv.Bad.getFromType();
4961 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00004962
John McCallfb7ad0f2010-02-02 02:42:52 +00004963 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00004964 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00004965 Expr *E = FromExpr->IgnoreParens();
4966 if (isa<UnaryOperator>(E))
4967 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00004968 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00004969
4970 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
4971 << (unsigned) FnKind << FnDesc
4972 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
4973 << ToTy << Name << I+1;
4974 return;
4975 }
4976
John McCall6d174642010-01-23 08:10:49 +00004977 // Do some hand-waving analysis to see if the non-viability is due
4978 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00004979 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
4980 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
4981 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
4982 CToTy = RT->getPointeeType();
4983 else {
4984 // TODO: detect and diagnose the full richness of const mismatches.
4985 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
4986 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
4987 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
4988 }
4989
4990 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
4991 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
4992 // It is dumb that we have to do this here.
4993 while (isa<ArrayType>(CFromTy))
4994 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
4995 while (isa<ArrayType>(CToTy))
4996 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
4997
4998 Qualifiers FromQs = CFromTy.getQualifiers();
4999 Qualifiers ToQs = CToTy.getQualifiers();
5000
5001 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5002 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5003 << (unsigned) FnKind << FnDesc
5004 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5005 << FromTy
5006 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5007 << (unsigned) isObjectArgument << I+1;
5008 return;
5009 }
5010
5011 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5012 assert(CVR && "unexpected qualifiers mismatch");
5013
5014 if (isObjectArgument) {
5015 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5016 << (unsigned) FnKind << FnDesc
5017 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5018 << FromTy << (CVR - 1);
5019 } else {
5020 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5021 << (unsigned) FnKind << FnDesc
5022 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5023 << FromTy << (CVR - 1) << I+1;
5024 }
5025 return;
5026 }
5027
John McCall6d174642010-01-23 08:10:49 +00005028 // Diagnose references or pointers to incomplete types differently,
5029 // since it's far from impossible that the incompleteness triggered
5030 // the failure.
5031 QualType TempFromTy = FromTy.getNonReferenceType();
5032 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5033 TempFromTy = PTy->getPointeeType();
5034 if (TempFromTy->isIncompleteType()) {
5035 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5036 << (unsigned) FnKind << FnDesc
5037 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5038 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5039 return;
5040 }
5041
John McCall47000992010-01-14 03:28:57 +00005042 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00005043 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5044 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00005045 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00005046 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00005047}
5048
5049void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5050 unsigned NumFormalArgs) {
5051 // TODO: treat calls to a missing default constructor as a special case
5052
5053 FunctionDecl *Fn = Cand->Function;
5054 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5055
5056 unsigned MinParams = Fn->getMinRequiredArguments();
5057
5058 // at least / at most / exactly
Douglas Gregor02eb4832010-05-08 18:13:28 +00005059 // FIXME: variadic templates "at most" should account for parameter packs
John McCall6a61b522010-01-13 09:16:55 +00005060 unsigned mode, modeCount;
5061 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005062 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5063 (Cand->FailureKind == ovl_fail_bad_deduction &&
5064 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCall6a61b522010-01-13 09:16:55 +00005065 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5066 mode = 0; // "at least"
5067 else
5068 mode = 2; // "exactly"
5069 modeCount = MinParams;
5070 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005071 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5072 (Cand->FailureKind == ovl_fail_bad_deduction &&
5073 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00005074 if (MinParams != FnTy->getNumArgs())
5075 mode = 1; // "at most"
5076 else
5077 mode = 2; // "exactly"
5078 modeCount = FnTy->getNumArgs();
5079 }
5080
5081 std::string Description;
5082 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5083
5084 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregor02eb4832010-05-08 18:13:28 +00005085 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5086 << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00005087}
5088
John McCall8b9ed552010-02-01 18:53:26 +00005089/// Diagnose a failed template-argument deduction.
5090void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5091 Expr **Args, unsigned NumArgs) {
5092 FunctionDecl *Fn = Cand->Function; // pattern
5093
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005094 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005095 NamedDecl *ParamD;
5096 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5097 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5098 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00005099 switch (Cand->DeductionFailure.Result) {
5100 case Sema::TDK_Success:
5101 llvm_unreachable("TDK_success while diagnosing bad deduction");
5102
5103 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00005104 assert(ParamD && "no parameter found for incomplete deduction result");
5105 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5106 << ParamD->getDeclName();
5107 return;
5108 }
5109
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005110 case Sema::TDK_Inconsistent:
5111 case Sema::TDK_InconsistentQuals: {
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005112 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005113 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005114 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005115 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005116 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005117 which = 1;
5118 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005119 which = 2;
5120 }
5121
5122 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5123 << which << ParamD->getDeclName()
5124 << *Cand->DeductionFailure.getFirstArg()
5125 << *Cand->DeductionFailure.getSecondArg();
5126 return;
5127 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00005128
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005129 case Sema::TDK_InvalidExplicitArguments:
5130 assert(ParamD && "no parameter found for invalid explicit arguments");
5131 if (ParamD->getDeclName())
5132 S.Diag(Fn->getLocation(),
5133 diag::note_ovl_candidate_explicit_arg_mismatch_named)
5134 << ParamD->getDeclName();
5135 else {
5136 int index = 0;
5137 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5138 index = TTP->getIndex();
5139 else if (NonTypeTemplateParmDecl *NTTP
5140 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5141 index = NTTP->getIndex();
5142 else
5143 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
5144 S.Diag(Fn->getLocation(),
5145 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
5146 << (index + 1);
5147 }
5148 return;
5149
Douglas Gregor02eb4832010-05-08 18:13:28 +00005150 case Sema::TDK_TooManyArguments:
5151 case Sema::TDK_TooFewArguments:
5152 DiagnoseArityMismatch(S, Cand, NumArgs);
5153 return;
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005154
John McCall8b9ed552010-02-01 18:53:26 +00005155 // TODO: diagnose these individually, then kill off
5156 // note_ovl_candidate_bad_deduction, which is uselessly vague.
5157 case Sema::TDK_InstantiationDepth:
John McCall8b9ed552010-02-01 18:53:26 +00005158 case Sema::TDK_SubstitutionFailure:
5159 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00005160 case Sema::TDK_FailedOverloadResolution:
5161 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
5162 return;
5163 }
5164}
5165
5166/// Generates a 'note' diagnostic for an overload candidate. We've
5167/// already generated a primary error at the call site.
5168///
5169/// It really does need to be a single diagnostic with its caret
5170/// pointed at the candidate declaration. Yes, this creates some
5171/// major challenges of technical writing. Yes, this makes pointing
5172/// out problems with specific arguments quite awkward. It's still
5173/// better than generating twenty screens of text for every failed
5174/// overload.
5175///
5176/// It would be great to be able to express per-candidate problems
5177/// more richly for those diagnostic clients that cared, but we'd
5178/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00005179void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
5180 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00005181 FunctionDecl *Fn = Cand->Function;
5182
John McCall12f97bc2010-01-08 04:41:39 +00005183 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00005184 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00005185 std::string FnDesc;
5186 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00005187
5188 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00005189 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00005190 return;
John McCall12f97bc2010-01-08 04:41:39 +00005191 }
5192
John McCalle1ac8d12010-01-13 00:25:19 +00005193 // We don't really have anything else to say about viable candidates.
5194 if (Cand->Viable) {
5195 S.NoteOverloadCandidate(Fn);
5196 return;
5197 }
John McCall0d1da222010-01-12 00:44:57 +00005198
John McCall6a61b522010-01-13 09:16:55 +00005199 switch (Cand->FailureKind) {
5200 case ovl_fail_too_many_arguments:
5201 case ovl_fail_too_few_arguments:
5202 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00005203
John McCall6a61b522010-01-13 09:16:55 +00005204 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00005205 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5206
John McCallfe796dd2010-01-23 05:17:32 +00005207 case ovl_fail_trivial_conversion:
5208 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005209 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00005210 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005211
John McCall65eb8792010-02-25 01:37:24 +00005212 case ovl_fail_bad_conversion: {
5213 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5214 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00005215 if (Cand->Conversions[I].isBad())
5216 return DiagnoseBadConversion(S, Cand, I);
5217
5218 // FIXME: this currently happens when we're called from SemaInit
5219 // when user-conversion overload fails. Figure out how to handle
5220 // those conditions and diagnose them well.
5221 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005222 }
John McCall65eb8792010-02-25 01:37:24 +00005223 }
John McCalld3224162010-01-08 00:58:21 +00005224}
5225
5226void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5227 // Desugar the type of the surrogate down to a function type,
5228 // retaining as many typedefs as possible while still showing
5229 // the function type (and, therefore, its parameter types).
5230 QualType FnType = Cand->Surrogate->getConversionType();
5231 bool isLValueReference = false;
5232 bool isRValueReference = false;
5233 bool isPointer = false;
5234 if (const LValueReferenceType *FnTypeRef =
5235 FnType->getAs<LValueReferenceType>()) {
5236 FnType = FnTypeRef->getPointeeType();
5237 isLValueReference = true;
5238 } else if (const RValueReferenceType *FnTypeRef =
5239 FnType->getAs<RValueReferenceType>()) {
5240 FnType = FnTypeRef->getPointeeType();
5241 isRValueReference = true;
5242 }
5243 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5244 FnType = FnTypePtr->getPointeeType();
5245 isPointer = true;
5246 }
5247 // Desugar down to a function type.
5248 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5249 // Reconstruct the pointer/reference as appropriate.
5250 if (isPointer) FnType = S.Context.getPointerType(FnType);
5251 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5252 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5253
5254 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5255 << FnType;
5256}
5257
5258void NoteBuiltinOperatorCandidate(Sema &S,
5259 const char *Opc,
5260 SourceLocation OpLoc,
5261 OverloadCandidate *Cand) {
5262 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5263 std::string TypeStr("operator");
5264 TypeStr += Opc;
5265 TypeStr += "(";
5266 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5267 if (Cand->Conversions.size() == 1) {
5268 TypeStr += ")";
5269 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5270 } else {
5271 TypeStr += ", ";
5272 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5273 TypeStr += ")";
5274 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5275 }
5276}
5277
5278void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5279 OverloadCandidate *Cand) {
5280 unsigned NoOperands = Cand->Conversions.size();
5281 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5282 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00005283 if (ICS.isBad()) break; // all meaningless after first invalid
5284 if (!ICS.isAmbiguous()) continue;
5285
5286 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00005287 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00005288 }
5289}
5290
John McCall3712d9e2010-01-15 23:32:50 +00005291SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5292 if (Cand->Function)
5293 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00005294 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00005295 return Cand->Surrogate->getLocation();
5296 return SourceLocation();
5297}
5298
John McCallad2587a2010-01-12 00:48:53 +00005299struct CompareOverloadCandidatesForDisplay {
5300 Sema &S;
5301 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00005302
5303 bool operator()(const OverloadCandidate *L,
5304 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00005305 // Fast-path this check.
5306 if (L == R) return false;
5307
John McCall12f97bc2010-01-08 04:41:39 +00005308 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00005309 if (L->Viable) {
5310 if (!R->Viable) return true;
5311
5312 // TODO: introduce a tri-valued comparison for overload
5313 // candidates. Would be more worthwhile if we had a sort
5314 // that could exploit it.
John McCallbc077cf2010-02-08 23:07:23 +00005315 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5316 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00005317 } else if (R->Viable)
5318 return false;
John McCall12f97bc2010-01-08 04:41:39 +00005319
John McCall3712d9e2010-01-15 23:32:50 +00005320 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00005321
John McCall3712d9e2010-01-15 23:32:50 +00005322 // Criteria by which we can sort non-viable candidates:
5323 if (!L->Viable) {
5324 // 1. Arity mismatches come after other candidates.
5325 if (L->FailureKind == ovl_fail_too_many_arguments ||
5326 L->FailureKind == ovl_fail_too_few_arguments)
5327 return false;
5328 if (R->FailureKind == ovl_fail_too_many_arguments ||
5329 R->FailureKind == ovl_fail_too_few_arguments)
5330 return true;
John McCall12f97bc2010-01-08 04:41:39 +00005331
John McCallfe796dd2010-01-23 05:17:32 +00005332 // 2. Bad conversions come first and are ordered by the number
5333 // of bad conversions and quality of good conversions.
5334 if (L->FailureKind == ovl_fail_bad_conversion) {
5335 if (R->FailureKind != ovl_fail_bad_conversion)
5336 return true;
5337
5338 // If there's any ordering between the defined conversions...
5339 // FIXME: this might not be transitive.
5340 assert(L->Conversions.size() == R->Conversions.size());
5341
5342 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00005343 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5344 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCallfe796dd2010-01-23 05:17:32 +00005345 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5346 R->Conversions[I])) {
5347 case ImplicitConversionSequence::Better:
5348 leftBetter++;
5349 break;
5350
5351 case ImplicitConversionSequence::Worse:
5352 leftBetter--;
5353 break;
5354
5355 case ImplicitConversionSequence::Indistinguishable:
5356 break;
5357 }
5358 }
5359 if (leftBetter > 0) return true;
5360 if (leftBetter < 0) return false;
5361
5362 } else if (R->FailureKind == ovl_fail_bad_conversion)
5363 return false;
5364
John McCall3712d9e2010-01-15 23:32:50 +00005365 // TODO: others?
5366 }
5367
5368 // Sort everything else by location.
5369 SourceLocation LLoc = GetLocationForCandidate(L);
5370 SourceLocation RLoc = GetLocationForCandidate(R);
5371
5372 // Put candidates without locations (e.g. builtins) at the end.
5373 if (LLoc.isInvalid()) return false;
5374 if (RLoc.isInvalid()) return true;
5375
5376 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00005377 }
5378};
5379
John McCallfe796dd2010-01-23 05:17:32 +00005380/// CompleteNonViableCandidate - Normally, overload resolution only
5381/// computes up to the first
5382void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5383 Expr **Args, unsigned NumArgs) {
5384 assert(!Cand->Viable);
5385
5386 // Don't do anything on failures other than bad conversion.
5387 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5388
5389 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00005390 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00005391 unsigned ConvCount = Cand->Conversions.size();
5392 while (true) {
5393 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5394 ConvIdx++;
5395 if (Cand->Conversions[ConvIdx - 1].isBad())
5396 break;
5397 }
5398
5399 if (ConvIdx == ConvCount)
5400 return;
5401
John McCall65eb8792010-02-25 01:37:24 +00005402 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
5403 "remaining conversion is initialized?");
5404
Douglas Gregoradc7a702010-04-16 17:45:54 +00005405 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00005406 // operation somehow.
5407 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00005408
5409 const FunctionProtoType* Proto;
5410 unsigned ArgIdx = ConvIdx;
5411
5412 if (Cand->IsSurrogate) {
5413 QualType ConvType
5414 = Cand->Surrogate->getConversionType().getNonReferenceType();
5415 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
5416 ConvType = ConvPtrType->getPointeeType();
5417 Proto = ConvType->getAs<FunctionProtoType>();
5418 ArgIdx--;
5419 } else if (Cand->Function) {
5420 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
5421 if (isa<CXXMethodDecl>(Cand->Function) &&
5422 !isa<CXXConstructorDecl>(Cand->Function))
5423 ArgIdx--;
5424 } else {
5425 // Builtin binary operator with a bad first conversion.
5426 assert(ConvCount <= 3);
5427 for (; ConvIdx != ConvCount; ++ConvIdx)
5428 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005429 = TryCopyInitialization(S, Args[ConvIdx],
5430 Cand->BuiltinTypes.ParamTypes[ConvIdx],
5431 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005432 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00005433 return;
5434 }
5435
5436 // Fill in the rest of the conversions.
5437 unsigned NumArgsInProto = Proto->getNumArgs();
5438 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
5439 if (ArgIdx < NumArgsInProto)
5440 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005441 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
5442 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005443 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00005444 else
5445 Cand->Conversions[ConvIdx].setEllipsis();
5446 }
5447}
5448
John McCalld3224162010-01-08 00:58:21 +00005449} // end anonymous namespace
5450
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005451/// PrintOverloadCandidates - When overload resolution fails, prints
5452/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00005453/// set.
Mike Stump11289f42009-09-09 15:08:12 +00005454void
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005455Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall12f97bc2010-01-08 04:41:39 +00005456 OverloadCandidateDisplayKind OCD,
John McCallad907772010-01-12 07:18:19 +00005457 Expr **Args, unsigned NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00005458 const char *Opc,
Fariborz Jahanian29f9d392009-10-09 00:13:15 +00005459 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00005460 // Sort the candidates by viability and position. Sorting directly would
5461 // be prohibitive, so we make a set of pointers and sort those.
5462 llvm::SmallVector<OverloadCandidate*, 32> Cands;
5463 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
5464 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5465 LastCand = CandidateSet.end();
John McCallfe796dd2010-01-23 05:17:32 +00005466 Cand != LastCand; ++Cand) {
5467 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00005468 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00005469 else if (OCD == OCD_AllCandidates) {
5470 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
5471 Cands.push_back(Cand);
5472 }
5473 }
5474
John McCallad2587a2010-01-12 00:48:53 +00005475 std::sort(Cands.begin(), Cands.end(),
5476 CompareOverloadCandidatesForDisplay(*this));
John McCall12f97bc2010-01-08 04:41:39 +00005477
John McCall0d1da222010-01-12 00:44:57 +00005478 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00005479
John McCall12f97bc2010-01-08 04:41:39 +00005480 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
5481 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
5482 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00005483
John McCalld3224162010-01-08 00:58:21 +00005484 if (Cand->Function)
John McCalle1ac8d12010-01-13 00:25:19 +00005485 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00005486 else if (Cand->IsSurrogate)
5487 NoteSurrogateCandidate(*this, Cand);
5488
5489 // This a builtin candidate. We do not, in general, want to list
5490 // every possible builtin candidate.
John McCall0d1da222010-01-12 00:44:57 +00005491 else if (Cand->Viable) {
5492 // Generally we only see ambiguities including viable builtin
5493 // operators if overload resolution got screwed up by an
5494 // ambiguous user-defined conversion.
5495 //
5496 // FIXME: It's quite possible for different conversions to see
5497 // different ambiguities, though.
5498 if (!ReportedAmbiguousConversions) {
5499 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
5500 ReportedAmbiguousConversions = true;
5501 }
John McCalld3224162010-01-08 00:58:21 +00005502
John McCall0d1da222010-01-12 00:44:57 +00005503 // If this is a viable builtin, print it.
John McCalld3224162010-01-08 00:58:21 +00005504 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00005505 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005506 }
5507}
5508
John McCalla0296f72010-03-19 07:35:19 +00005509static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00005510 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00005511 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005512
John McCalla0296f72010-03-19 07:35:19 +00005513 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00005514}
5515
Douglas Gregorcd695e52008-11-10 20:40:00 +00005516/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
5517/// an overloaded function (C++ [over.over]), where @p From is an
5518/// expression with overloaded function type and @p ToType is the type
5519/// we're trying to resolve to. For example:
5520///
5521/// @code
5522/// int f(double);
5523/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00005524///
Douglas Gregorcd695e52008-11-10 20:40:00 +00005525/// int (*pfd)(double) = f; // selects f(double)
5526/// @endcode
5527///
5528/// This routine returns the resulting FunctionDecl if it could be
5529/// resolved, and NULL otherwise. When @p Complain is true, this
5530/// routine will emit diagnostics if there is an error.
5531FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005532Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00005533 bool Complain,
5534 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00005535 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005536 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005537 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00005538 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005539 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00005540 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005541 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005542 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005543 FunctionType = MemTypePtr->getPointeeType();
5544 IsMember = true;
5545 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005546
Douglas Gregorcd695e52008-11-10 20:40:00 +00005547 // C++ [over.over]p1:
5548 // [...] [Note: any redundant set of parentheses surrounding the
5549 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00005550 // C++ [over.over]p1:
5551 // [...] The overloaded function name can be preceded by the &
5552 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005553 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
5554 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
5555 if (OvlExpr->hasExplicitTemplateArgs()) {
5556 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
5557 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005558 }
Douglas Gregor064fdb22010-04-14 23:11:21 +00005559
5560 // We expect a pointer or reference to function, or a function pointer.
5561 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
5562 if (!FunctionType->isFunctionType()) {
5563 if (Complain)
5564 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
5565 << OvlExpr->getName() << ToType;
5566
5567 return 0;
5568 }
5569
5570 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005571
Douglas Gregorcd695e52008-11-10 20:40:00 +00005572 // Look through all of the overloaded functions, searching for one
5573 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00005574 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00005575 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
5576
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005577 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00005578 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5579 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005580 // Look through any using declarations to find the underlying function.
5581 NamedDecl *Fn = (*I)->getUnderlyingDecl();
5582
Douglas Gregorcd695e52008-11-10 20:40:00 +00005583 // C++ [over.over]p3:
5584 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00005585 // targets of type "pointer-to-function" or "reference-to-function."
5586 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005587 // type "pointer-to-member-function."
5588 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00005589
Mike Stump11289f42009-09-09 15:08:12 +00005590 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005591 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00005592 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005593 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00005594 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005595 // static when converting to member pointer.
5596 if (Method->isStatic() == IsMember)
5597 continue;
5598 } else if (IsMember)
5599 continue;
Mike Stump11289f42009-09-09 15:08:12 +00005600
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005601 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00005602 // If the name is a function template, template argument deduction is
5603 // done (14.8.2.2), and if the argument deduction succeeds, the
5604 // resulting template argument list is used to generate a single
5605 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005606 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005607 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00005608 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005609 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00005610 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00005611 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00005612 FunctionType, Specialization, Info)) {
5613 // FIXME: make a note of the failed deduction for diagnostics.
5614 (void)Result;
5615 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00005616 // FIXME: If the match isn't exact, shouldn't we just drop this as
5617 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00005618 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00005619 == Context.getCanonicalType(Specialization->getType()));
John McCalla0296f72010-03-19 07:35:19 +00005620 Matches.push_back(std::make_pair(I.getPair(),
5621 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor9b146582009-07-08 20:55:45 +00005622 }
John McCalld14a8642009-11-21 08:51:07 +00005623
5624 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00005625 }
Mike Stump11289f42009-09-09 15:08:12 +00005626
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005627 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005628 // Skip non-static functions when converting to pointer, and static
5629 // when converting to member pointer.
5630 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00005631 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00005632
5633 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00005634 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00005635 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005636 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00005637 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00005638
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00005639 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00005640 QualType ResultTy;
5641 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
5642 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
5643 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00005644 Matches.push_back(std::make_pair(I.getPair(),
5645 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005646 FoundNonTemplateFunction = true;
5647 }
Mike Stump11289f42009-09-09 15:08:12 +00005648 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00005649 }
5650
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005651 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00005652 if (Matches.empty()) {
5653 if (Complain) {
5654 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
5655 << OvlExpr->getName() << FunctionType;
5656 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5657 E = OvlExpr->decls_end();
5658 I != E; ++I)
5659 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
5660 NoteOverloadCandidate(F);
5661 }
5662
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005663 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00005664 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00005665 FunctionDecl *Result = Matches[0].second;
John McCall16df1e52010-03-30 21:47:33 +00005666 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005667 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCall58cc69d2010-01-27 01:50:18 +00005668 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00005669 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005670 return Result;
5671 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005672
5673 // C++ [over.over]p4:
5674 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00005675 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005676 // [...] and any given function template specialization F1 is
5677 // eliminated if the set contains a second function template
5678 // specialization whose function template is more specialized
5679 // than the function template of F1 according to the partial
5680 // ordering rules of 14.5.5.2.
5681
5682 // The algorithm specified above is quadratic. We instead use a
5683 // two-pass algorithm (similar to the one used to identify the
5684 // best viable function in an overload set) that identifies the
5685 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00005686
5687 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
5688 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5689 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00005690
5691 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00005692 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005693 TPOC_Other, From->getLocStart(),
5694 PDiag(),
5695 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00005696 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00005697 PDiag(diag::note_ovl_candidate)
5698 << (unsigned) oc_function_template);
John McCalla0296f72010-03-19 07:35:19 +00005699 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCall58cc69d2010-01-27 01:50:18 +00005700 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00005701 FoundResult = Matches[Result - MatchesCopy.begin()].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00005702 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00005703 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall4fa0d5f2010-05-06 18:15:07 +00005704 DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc());
5705 }
John McCall58cc69d2010-01-27 01:50:18 +00005706 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005707 }
Mike Stump11289f42009-09-09 15:08:12 +00005708
Douglas Gregorfae1d712009-09-26 03:56:17 +00005709 // [...] any function template specializations in the set are
5710 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00005711 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00005712 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00005713 ++I;
5714 else {
John McCalla0296f72010-03-19 07:35:19 +00005715 Matches[I] = Matches[--N];
5716 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00005717 }
5718 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00005719
Mike Stump11289f42009-09-09 15:08:12 +00005720 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005721 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00005722 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00005723 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00005724 FoundResult = Matches[0].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00005725 if (Complain) {
John McCalla0296f72010-03-19 07:35:19 +00005726 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
John McCall4fa0d5f2010-05-06 18:15:07 +00005727 DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc());
5728 }
John McCalla0296f72010-03-19 07:35:19 +00005729 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00005730 }
Mike Stump11289f42009-09-09 15:08:12 +00005731
Douglas Gregorb257e4f2009-07-08 23:33:52 +00005732 // FIXME: We should probably return the same thing that BestViableFunction
5733 // returns (even if we issue the diagnostics here).
5734 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00005735 << Matches[0].second->getDeclName();
5736 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
5737 NoteOverloadCandidate(Matches[I].second);
Douglas Gregorcd695e52008-11-10 20:40:00 +00005738 return 0;
5739}
5740
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005741/// \brief Given an expression that refers to an overloaded function, try to
5742/// resolve that overloaded function expression down to a single function.
5743///
5744/// This routine can only resolve template-ids that refer to a single function
5745/// template, where that template-id refers to a single template whose template
5746/// arguments are either provided by the template-id or have defaults,
5747/// as described in C++0x [temp.arg.explicit]p3.
5748FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
5749 // C++ [over.over]p1:
5750 // [...] [Note: any redundant set of parentheses surrounding the
5751 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005752 // C++ [over.over]p1:
5753 // [...] The overloaded function name can be preceded by the &
5754 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00005755
5756 if (From->getType() != Context.OverloadTy)
5757 return 0;
5758
5759 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005760
5761 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00005762 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005763 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00005764
5765 TemplateArgumentListInfo ExplicitTemplateArgs;
5766 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005767
5768 // Look through all of the overloaded functions, searching for one
5769 // whose type matches exactly.
5770 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00005771 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
5772 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005773 // C++0x [temp.arg.explicit]p3:
5774 // [...] In contexts where deduction is done and fails, or in contexts
5775 // where deduction is not done, if a template argument list is
5776 // specified and it, along with any default template arguments,
5777 // identifies a single function template specialization, then the
5778 // template-id is an lvalue for the function template specialization.
5779 FunctionTemplateDecl *FunctionTemplate = cast<FunctionTemplateDecl>(*I);
5780
5781 // C++ [over.over]p2:
5782 // If the name is a function template, template argument deduction is
5783 // done (14.8.2.2), and if the argument deduction succeeds, the
5784 // resulting template argument list is used to generate a single
5785 // function template specialization, which is added to the set of
5786 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005787 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00005788 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00005789 if (TemplateDeductionResult Result
5790 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
5791 Specialization, Info)) {
5792 // FIXME: make a note of the failed deduction for diagnostics.
5793 (void)Result;
5794 continue;
5795 }
5796
5797 // Multiple matches; we can't resolve to a single declaration.
5798 if (Matched)
5799 return 0;
5800
5801 Matched = Specialization;
5802 }
5803
5804 return Matched;
5805}
5806
Douglas Gregorcabea402009-09-22 15:41:20 +00005807/// \brief Add a single candidate to the overload set.
5808static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00005809 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00005810 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005811 Expr **Args, unsigned NumArgs,
5812 OverloadCandidateSet &CandidateSet,
5813 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00005814 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00005815 if (isa<UsingShadowDecl>(Callee))
5816 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
5817
Douglas Gregorcabea402009-09-22 15:41:20 +00005818 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00005819 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00005820 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005821 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005822 return;
John McCalld14a8642009-11-21 08:51:07 +00005823 }
5824
5825 if (FunctionTemplateDecl *FuncTemplate
5826 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00005827 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
5828 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005829 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00005830 return;
5831 }
5832
5833 assert(false && "unhandled case in overloaded call candidate");
5834
5835 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00005836}
5837
5838/// \brief Add the overload candidates named by callee and/or found by argument
5839/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00005840void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00005841 Expr **Args, unsigned NumArgs,
5842 OverloadCandidateSet &CandidateSet,
5843 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00005844
5845#ifndef NDEBUG
5846 // Verify that ArgumentDependentLookup is consistent with the rules
5847 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00005848 //
Douglas Gregorcabea402009-09-22 15:41:20 +00005849 // Let X be the lookup set produced by unqualified lookup (3.4.1)
5850 // and let Y be the lookup set produced by argument dependent
5851 // lookup (defined as follows). If X contains
5852 //
5853 // -- a declaration of a class member, or
5854 //
5855 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00005856 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00005857 //
5858 // -- a declaration that is neither a function or a function
5859 // template
5860 //
5861 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00005862
John McCall57500772009-12-16 12:17:52 +00005863 if (ULE->requiresADL()) {
5864 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5865 E = ULE->decls_end(); I != E; ++I) {
5866 assert(!(*I)->getDeclContext()->isRecord());
5867 assert(isa<UsingShadowDecl>(*I) ||
5868 !(*I)->getDeclContext()->isFunctionOrMethod());
5869 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00005870 }
5871 }
5872#endif
5873
John McCall57500772009-12-16 12:17:52 +00005874 // It would be nice to avoid this copy.
5875 TemplateArgumentListInfo TABuffer;
5876 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5877 if (ULE->hasExplicitTemplateArgs()) {
5878 ULE->copyTemplateArgumentsInto(TABuffer);
5879 ExplicitTemplateArgs = &TABuffer;
5880 }
5881
5882 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
5883 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00005884 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00005885 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00005886 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00005887
John McCall57500772009-12-16 12:17:52 +00005888 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00005889 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
5890 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005891 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005892 CandidateSet,
5893 PartialOverloading);
5894}
John McCalld681c392009-12-16 08:11:27 +00005895
John McCall57500772009-12-16 12:17:52 +00005896static Sema::OwningExprResult Destroy(Sema &SemaRef, Expr *Fn,
5897 Expr **Args, unsigned NumArgs) {
5898 Fn->Destroy(SemaRef.Context);
5899 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
5900 Args[Arg]->Destroy(SemaRef.Context);
5901 return SemaRef.ExprError();
5902}
5903
John McCalld681c392009-12-16 08:11:27 +00005904/// Attempts to recover from a call where no functions were found.
5905///
5906/// Returns true if new candidates were found.
John McCall57500772009-12-16 12:17:52 +00005907static Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005908BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00005909 UnresolvedLookupExpr *ULE,
5910 SourceLocation LParenLoc,
5911 Expr **Args, unsigned NumArgs,
5912 SourceLocation *CommaLocs,
5913 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00005914
5915 CXXScopeSpec SS;
5916 if (ULE->getQualifier()) {
5917 SS.setScopeRep(ULE->getQualifier());
5918 SS.setRange(ULE->getQualifierRange());
5919 }
5920
John McCall57500772009-12-16 12:17:52 +00005921 TemplateArgumentListInfo TABuffer;
5922 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
5923 if (ULE->hasExplicitTemplateArgs()) {
5924 ULE->copyTemplateArgumentsInto(TABuffer);
5925 ExplicitTemplateArgs = &TABuffer;
5926 }
5927
John McCalld681c392009-12-16 08:11:27 +00005928 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
5929 Sema::LookupOrdinaryName);
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005930 if (SemaRef.DiagnoseEmptyLookup(S, SS, R))
John McCall57500772009-12-16 12:17:52 +00005931 return Destroy(SemaRef, Fn, Args, NumArgs);
John McCalld681c392009-12-16 08:11:27 +00005932
John McCall57500772009-12-16 12:17:52 +00005933 assert(!R.empty() && "lookup results empty despite recovery");
5934
5935 // Build an implicit member call if appropriate. Just drop the
5936 // casts and such from the call, we don't really care.
5937 Sema::OwningExprResult NewFn = SemaRef.ExprError();
5938 if ((*R.begin())->isCXXClassMember())
5939 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
5940 else if (ExplicitTemplateArgs)
5941 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
5942 else
5943 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
5944
5945 if (NewFn.isInvalid())
5946 return Destroy(SemaRef, Fn, Args, NumArgs);
5947
5948 Fn->Destroy(SemaRef.Context);
5949
5950 // This shouldn't cause an infinite loop because we're giving it
5951 // an expression with non-empty lookup results, which should never
5952 // end up here.
5953 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
5954 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
5955 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00005956}
Douglas Gregorcabea402009-09-22 15:41:20 +00005957
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005958/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00005959/// (which eventually refers to the declaration Func) and the call
5960/// arguments Args/NumArgs, attempt to resolve the function call down
5961/// to a specific function. If overload resolution succeeds, returns
5962/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00005963/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00005964/// arguments and Fn, and returns NULL.
John McCall57500772009-12-16 12:17:52 +00005965Sema::OwningExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005966Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00005967 SourceLocation LParenLoc,
5968 Expr **Args, unsigned NumArgs,
5969 SourceLocation *CommaLocs,
5970 SourceLocation RParenLoc) {
5971#ifndef NDEBUG
5972 if (ULE->requiresADL()) {
5973 // To do ADL, we must have found an unqualified name.
5974 assert(!ULE->getQualifier() && "qualified name with ADL");
5975
5976 // We don't perform ADL for implicit declarations of builtins.
5977 // Verify that this was correctly set up.
5978 FunctionDecl *F;
5979 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
5980 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
5981 F->getBuiltinID() && F->isImplicit())
5982 assert(0 && "performing ADL for builtin");
5983
5984 // We don't perform ADL in C.
5985 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
5986 }
5987#endif
5988
John McCallbc077cf2010-02-08 23:07:23 +00005989 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00005990
John McCall57500772009-12-16 12:17:52 +00005991 // Add the functions denoted by the callee to the set of candidate
5992 // functions, including those from argument-dependent lookup.
5993 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00005994
5995 // If we found nothing, try to recover.
5996 // AddRecoveryCallCandidates diagnoses the error itself, so we just
5997 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00005998 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00005999 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall57500772009-12-16 12:17:52 +00006000 CommaLocs, RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006001
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006002 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006003 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00006004 case OR_Success: {
6005 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00006006 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006007 DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00006008 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00006009 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6010 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006011
6012 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00006013 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006014 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00006015 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006016 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006017 break;
6018
6019 case OR_Ambiguous:
6020 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00006021 << ULE->getName() << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006022 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006023 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006024
6025 case OR_Deleted:
6026 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6027 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00006028 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00006029 << Fn->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006030 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006031 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006032 }
6033
6034 // Overload resolution failed. Destroy all of the subexpressions and
6035 // return NULL.
6036 Fn->Destroy(Context);
6037 for (unsigned Arg = 0; Arg < NumArgs; ++Arg)
6038 Args[Arg]->Destroy(Context);
John McCall57500772009-12-16 12:17:52 +00006039 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006040}
6041
John McCall4c4c1df2010-01-26 03:27:55 +00006042static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00006043 return Functions.size() > 1 ||
6044 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6045}
6046
Douglas Gregor084d8552009-03-13 23:49:33 +00006047/// \brief Create a unary operation that may resolve to an overloaded
6048/// operator.
6049///
6050/// \param OpLoc The location of the operator itself (e.g., '*').
6051///
6052/// \param OpcIn The UnaryOperator::Opcode that describes this
6053/// operator.
6054///
6055/// \param Functions The set of non-member functions that will be
6056/// considered by overload resolution. The caller needs to build this
6057/// set based on the context using, e.g.,
6058/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6059/// set should not contain any member functions; those will be added
6060/// by CreateOverloadedUnaryOp().
6061///
6062/// \param input The input argument.
John McCall4c4c1df2010-01-26 03:27:55 +00006063Sema::OwningExprResult
6064Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6065 const UnresolvedSetImpl &Fns,
6066 ExprArg input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006067 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
6068 Expr *Input = (Expr *)input.get();
6069
6070 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6071 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6072 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6073
6074 Expr *Args[2] = { Input, 0 };
6075 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00006076
Douglas Gregor084d8552009-03-13 23:49:33 +00006077 // For post-increment and post-decrement, add the implicit '0' as
6078 // the second argument, so that we know this is a post-increment or
6079 // post-decrement.
6080 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
6081 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump11289f42009-09-09 15:08:12 +00006082 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregor084d8552009-03-13 23:49:33 +00006083 SourceLocation());
6084 NumArgs = 2;
6085 }
6086
6087 if (Input->isTypeDependent()) {
John McCall58cc69d2010-01-27 01:50:18 +00006088 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006089 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006090 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006091 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00006092 /*ADL*/ true, IsOverloaded(Fns));
6093 Fn->addDecls(Fns.begin(), Fns.end());
Mike Stump11289f42009-09-09 15:08:12 +00006094
Douglas Gregor084d8552009-03-13 23:49:33 +00006095 input.release();
6096 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6097 &Args[0], NumArgs,
6098 Context.DependentTy,
6099 OpLoc));
6100 }
6101
6102 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006103 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006104
6105 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006106 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00006107
6108 // Add operator candidates that are member functions.
6109 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6110
John McCall4c4c1df2010-01-26 03:27:55 +00006111 // Add candidates from ADL.
6112 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00006113 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00006114 /*ExplicitTemplateArgs*/ 0,
6115 CandidateSet);
6116
Douglas Gregor084d8552009-03-13 23:49:33 +00006117 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006118 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00006119
6120 // Perform overload resolution.
6121 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006122 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006123 case OR_Success: {
6124 // We found a built-in operator or an overloaded operator.
6125 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00006126
Douglas Gregor084d8552009-03-13 23:49:33 +00006127 if (FnDecl) {
6128 // We matched an overloaded operator. Build a call to that
6129 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00006130
Douglas Gregor084d8552009-03-13 23:49:33 +00006131 // Convert the arguments.
6132 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00006133 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006134
John McCall16df1e52010-03-30 21:47:33 +00006135 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6136 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00006137 return ExprError();
6138 } else {
6139 // Convert the arguments.
Douglas Gregore6600372009-12-23 17:40:29 +00006140 OwningExprResult InputInit
6141 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006142 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00006143 SourceLocation(),
6144 move(input));
6145 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00006146 return ExprError();
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006147
Douglas Gregore6600372009-12-23 17:40:29 +00006148 input = move(InputInit);
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006149 Input = (Expr *)input.get();
Douglas Gregor084d8552009-03-13 23:49:33 +00006150 }
6151
John McCall4fa0d5f2010-05-06 18:15:07 +00006152 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6153
Douglas Gregor084d8552009-03-13 23:49:33 +00006154 // Determine the result type
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006155 QualType ResultTy = FnDecl->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00006156
Douglas Gregor084d8552009-03-13 23:49:33 +00006157 // Build the actual expression node.
6158 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6159 SourceLocation());
6160 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00006161
Douglas Gregor084d8552009-03-13 23:49:33 +00006162 input.release();
Eli Friedman030eee42009-11-18 03:58:17 +00006163 Args[0] = Input;
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006164 ExprOwningPtr<CallExpr> TheCall(this,
6165 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman030eee42009-11-18 03:58:17 +00006166 Args, NumArgs, ResultTy, OpLoc));
John McCall4fa0d5f2010-05-06 18:15:07 +00006167
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006168 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6169 FnDecl))
6170 return ExprError();
6171
6172 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor084d8552009-03-13 23:49:33 +00006173 } else {
6174 // We matched a built-in operator. Convert the arguments, then
6175 // break out so that we will build the appropriate built-in
6176 // operator node.
6177 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006178 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00006179 return ExprError();
6180
6181 break;
6182 }
6183 }
6184
6185 case OR_No_Viable_Function:
6186 // No viable function; fall through to handling this as a
6187 // built-in operator, which will produce an error message for us.
6188 break;
6189
6190 case OR_Ambiguous:
6191 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6192 << UnaryOperator::getOpcodeStr(Opc)
6193 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006194 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006195 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006196 return ExprError();
6197
6198 case OR_Deleted:
6199 Diag(OpLoc, diag::err_ovl_deleted_oper)
6200 << Best->Function->isDeleted()
6201 << UnaryOperator::getOpcodeStr(Opc)
6202 << Input->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006203 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00006204 return ExprError();
6205 }
6206
6207 // Either we found no viable overloaded operator or we matched a
6208 // built-in operator. In either case, fall through to trying to
6209 // build a built-in operation.
6210 input.release();
6211 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
6212}
6213
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006214/// \brief Create a binary operation that may resolve to an overloaded
6215/// operator.
6216///
6217/// \param OpLoc The location of the operator itself (e.g., '+').
6218///
6219/// \param OpcIn The BinaryOperator::Opcode that describes this
6220/// operator.
6221///
6222/// \param Functions The set of non-member functions that will be
6223/// considered by overload resolution. The caller needs to build this
6224/// set based on the context using, e.g.,
6225/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6226/// set should not contain any member functions; those will be added
6227/// by CreateOverloadedBinOp().
6228///
6229/// \param LHS Left-hand argument.
6230/// \param RHS Right-hand argument.
Mike Stump11289f42009-09-09 15:08:12 +00006231Sema::OwningExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006232Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006233 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00006234 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006235 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006236 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00006237 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006238
6239 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6240 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6241 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6242
6243 // If either side is type-dependent, create an appropriate dependent
6244 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00006245 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00006246 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006247 // If there are no functions to store, just build a dependent
6248 // BinaryOperator or CompoundAssignment.
6249 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
6250 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6251 Context.DependentTy, OpLoc));
6252
6253 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6254 Context.DependentTy,
6255 Context.DependentTy,
6256 Context.DependentTy,
6257 OpLoc));
6258 }
John McCall4c4c1df2010-01-26 03:27:55 +00006259
6260 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00006261 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006262 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006263 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006264 0, SourceRange(), OpName, OpLoc,
John McCall4c4c1df2010-01-26 03:27:55 +00006265 /*ADL*/ true, IsOverloaded(Fns));
Mike Stump11289f42009-09-09 15:08:12 +00006266
John McCall4c4c1df2010-01-26 03:27:55 +00006267 Fn->addDecls(Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006268 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00006269 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006270 Context.DependentTy,
6271 OpLoc));
6272 }
6273
6274 // If this is the .* operator, which is not overloadable, just
6275 // create a built-in binary operator.
6276 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00006277 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006278
Sebastian Redl6a96bf72009-11-18 23:10:33 +00006279 // If this is the assignment operator, we only perform overload resolution
6280 // if the left-hand side is a class or enumeration type. This is actually
6281 // a hack. The standard requires that we do overload resolution between the
6282 // various built-in candidates, but as DR507 points out, this can lead to
6283 // problems. So we do it this way, which pretty much follows what GCC does.
6284 // Note that we go the traditional code path for compound assignment forms.
6285 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00006286 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006287
Douglas Gregor084d8552009-03-13 23:49:33 +00006288 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006289 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006290
6291 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006292 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006293
6294 // Add operator candidates that are member functions.
6295 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6296
John McCall4c4c1df2010-01-26 03:27:55 +00006297 // Add candidates from ADL.
6298 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6299 Args, 2,
6300 /*ExplicitTemplateArgs*/ 0,
6301 CandidateSet);
6302
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006303 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006304 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006305
6306 // Perform overload resolution.
6307 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006308 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00006309 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006310 // We found a built-in operator or an overloaded operator.
6311 FunctionDecl *FnDecl = Best->Function;
6312
6313 if (FnDecl) {
6314 // We matched an overloaded operator. Build a call to that
6315 // operator.
6316
6317 // Convert the arguments.
6318 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00006319 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00006320 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006321
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006322 OwningExprResult Arg1
6323 = PerformCopyInitialization(
6324 InitializedEntity::InitializeParameter(
6325 FnDecl->getParamDecl(0)),
6326 SourceLocation(),
6327 Owned(Args[1]));
6328 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006329 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006330
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006331 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006332 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006333 return ExprError();
6334
6335 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006336 } else {
6337 // Convert the arguments.
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006338 OwningExprResult Arg0
6339 = PerformCopyInitialization(
6340 InitializedEntity::InitializeParameter(
6341 FnDecl->getParamDecl(0)),
6342 SourceLocation(),
6343 Owned(Args[0]));
6344 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006345 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00006346
6347 OwningExprResult Arg1
6348 = PerformCopyInitialization(
6349 InitializedEntity::InitializeParameter(
6350 FnDecl->getParamDecl(1)),
6351 SourceLocation(),
6352 Owned(Args[1]));
6353 if (Arg1.isInvalid())
6354 return ExprError();
6355 Args[0] = LHS = Arg0.takeAs<Expr>();
6356 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006357 }
6358
John McCall4fa0d5f2010-05-06 18:15:07 +00006359 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6360
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006361 // Determine the result type
6362 QualType ResultTy
John McCall9dd450b2009-09-21 23:43:11 +00006363 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006364 ResultTy = ResultTy.getNonReferenceType();
6365
6366 // Build the actual expression node.
6367 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00006368 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006369 UsualUnaryConversions(FnExpr);
6370
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00006371 ExprOwningPtr<CXXOperatorCallExpr>
6372 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6373 Args, 2, ResultTy,
6374 OpLoc));
6375
6376 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6377 FnDecl))
6378 return ExprError();
6379
6380 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006381 } else {
6382 // We matched a built-in operator. Convert the arguments, then
6383 // break out so that we will build the appropriate built-in
6384 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00006385 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006386 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00006387 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006388 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006389 return ExprError();
6390
6391 break;
6392 }
6393 }
6394
Douglas Gregor66950a32009-09-30 21:46:01 +00006395 case OR_No_Viable_Function: {
6396 // C++ [over.match.oper]p9:
6397 // If the operator is the operator , [...] and there are no
6398 // viable functions, then the operator is assumed to be the
6399 // built-in operator and interpreted according to clause 5.
6400 if (Opc == BinaryOperator::Comma)
6401 break;
6402
Sebastian Redl027de2a2009-05-21 11:50:50 +00006403 // For class as left operand for assignment or compound assigment operator
6404 // do not fall through to handling in built-in, but report that no overloaded
6405 // assignment operator found
Douglas Gregor66950a32009-09-30 21:46:01 +00006406 OwningExprResult Result = ExprError();
6407 if (Args[0]->getType()->isRecordType() &&
6408 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00006409 Diag(OpLoc, diag::err_ovl_no_viable_oper)
6410 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006411 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00006412 } else {
6413 // No viable function; try to create a built-in operation, which will
6414 // produce an error. Then, show the non-viable candidates.
6415 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00006416 }
Douglas Gregor66950a32009-09-30 21:46:01 +00006417 assert(Result.isInvalid() &&
6418 "C++ binary operator overloading is missing candidates!");
6419 if (Result.isInvalid())
John McCallad907772010-01-12 07:18:19 +00006420 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006421 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00006422 return move(Result);
6423 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006424
6425 case OR_Ambiguous:
6426 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6427 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006428 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006429 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahaniane7196432009-10-12 20:11:40 +00006430 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006431 return ExprError();
6432
6433 case OR_Deleted:
6434 Diag(OpLoc, diag::err_ovl_deleted_oper)
6435 << Best->Function->isDeleted()
6436 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00006437 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006438 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006439 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00006440 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006441
Douglas Gregor66950a32009-09-30 21:46:01 +00006442 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00006443 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006444}
6445
Sebastian Redladba46e2009-10-29 20:17:01 +00006446Action::OwningExprResult
6447Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
6448 SourceLocation RLoc,
6449 ExprArg Base, ExprArg Idx) {
6450 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
6451 static_cast<Expr*>(Idx.get()) };
6452 DeclarationName OpName =
6453 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
6454
6455 // If either side is type-dependent, create an appropriate dependent
6456 // expression.
6457 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
6458
John McCall58cc69d2010-01-27 01:50:18 +00006459 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006460 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006461 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
John McCalle66edc12009-11-24 19:00:30 +00006462 0, SourceRange(), OpName, LLoc,
John McCall283b9012009-11-22 00:44:51 +00006463 /*ADL*/ true, /*Overloaded*/ false);
John McCalle66edc12009-11-24 19:00:30 +00006464 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00006465
6466 Base.release();
6467 Idx.release();
6468 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
6469 Args, 2,
6470 Context.DependentTy,
6471 RLoc));
6472 }
6473
6474 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006475 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006476
6477 // Subscript can only be overloaded as a member function.
6478
6479 // Add operator candidates that are member functions.
6480 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6481
6482 // Add builtin operator candidates.
6483 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
6484
6485 // Perform overload resolution.
6486 OverloadCandidateSet::iterator Best;
6487 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
6488 case OR_Success: {
6489 // We found a built-in operator or an overloaded operator.
6490 FunctionDecl *FnDecl = Best->Function;
6491
6492 if (FnDecl) {
6493 // We matched an overloaded operator. Build a call to that
6494 // operator.
6495
John McCalla0296f72010-03-19 07:35:19 +00006496 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006497 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00006498
Sebastian Redladba46e2009-10-29 20:17:01 +00006499 // Convert the arguments.
6500 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006501 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006502 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00006503 return ExprError();
6504
Anders Carlssona68e51e2010-01-29 18:37:50 +00006505 // Convert the arguments.
6506 OwningExprResult InputInit
6507 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6508 FnDecl->getParamDecl(0)),
6509 SourceLocation(),
6510 Owned(Args[1]));
6511 if (InputInit.isInvalid())
6512 return ExprError();
6513
6514 Args[1] = InputInit.takeAs<Expr>();
6515
Sebastian Redladba46e2009-10-29 20:17:01 +00006516 // Determine the result type
6517 QualType ResultTy
6518 = FnDecl->getType()->getAs<FunctionType>()->getResultType();
6519 ResultTy = ResultTy.getNonReferenceType();
6520
6521 // Build the actual expression node.
6522 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6523 LLoc);
6524 UsualUnaryConversions(FnExpr);
6525
6526 Base.release();
6527 Idx.release();
6528 ExprOwningPtr<CXXOperatorCallExpr>
6529 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
6530 FnExpr, Args, 2,
6531 ResultTy, RLoc));
6532
6533 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
6534 FnDecl))
6535 return ExprError();
6536
6537 return MaybeBindToTemporary(TheCall.release());
6538 } else {
6539 // We matched a built-in operator. Convert the arguments, then
6540 // break out so that we will build the appropriate built-in
6541 // operator node.
6542 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006543 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00006544 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006545 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00006546 return ExprError();
6547
6548 break;
6549 }
6550 }
6551
6552 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00006553 if (CandidateSet.empty())
6554 Diag(LLoc, diag::err_ovl_no_oper)
6555 << Args[0]->getType() << /*subscript*/ 0
6556 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
6557 else
6558 Diag(LLoc, diag::err_ovl_no_viable_subscript)
6559 << Args[0]->getType()
6560 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006561 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall02374852010-01-07 02:04:15 +00006562 "[]", LLoc);
6563 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00006564 }
6565
6566 case OR_Ambiguous:
6567 Diag(LLoc, diag::err_ovl_ambiguous_oper)
6568 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006569 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redladba46e2009-10-29 20:17:01 +00006570 "[]", LLoc);
6571 return ExprError();
6572
6573 case OR_Deleted:
6574 Diag(LLoc, diag::err_ovl_deleted_oper)
6575 << Best->Function->isDeleted() << "[]"
6576 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006577 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall12f97bc2010-01-08 04:41:39 +00006578 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00006579 return ExprError();
6580 }
6581
6582 // We matched a built-in operator; build it.
6583 Base.release();
6584 Idx.release();
6585 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
6586 Owned(Args[1]), RLoc);
6587}
6588
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006589/// BuildCallToMemberFunction - Build a call to a member
6590/// function. MemExpr is the expression that refers to the member
6591/// function (and includes the object parameter), Args/NumArgs are the
6592/// arguments to the function call (not including the object
6593/// parameter). The caller needs to validate that the member
6594/// expression refers to a member function or an overloaded member
6595/// function.
John McCall2d74de92009-12-01 22:10:20 +00006596Sema::OwningExprResult
Mike Stump11289f42009-09-09 15:08:12 +00006597Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
6598 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006599 unsigned NumArgs, SourceLocation *CommaLocs,
6600 SourceLocation RParenLoc) {
6601 // Dig out the member expression. This holds both the object
6602 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00006603 Expr *NakedMemExpr = MemExprE->IgnoreParens();
6604
John McCall10eae182009-11-30 22:42:35 +00006605 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006606 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00006607 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006608 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00006609 if (isa<MemberExpr>(NakedMemExpr)) {
6610 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00006611 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00006612 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006613 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00006614 } else {
6615 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006616 Qualifier = UnresExpr->getQualifier();
6617
John McCall6e9f8f62009-12-03 04:06:58 +00006618 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00006619
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006620 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00006621 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00006622
John McCall2d74de92009-12-01 22:10:20 +00006623 // FIXME: avoid copy.
6624 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
6625 if (UnresExpr->hasExplicitTemplateArgs()) {
6626 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
6627 TemplateArgs = &TemplateArgsBuffer;
6628 }
6629
John McCall10eae182009-11-30 22:42:35 +00006630 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
6631 E = UnresExpr->decls_end(); I != E; ++I) {
6632
John McCall6e9f8f62009-12-03 04:06:58 +00006633 NamedDecl *Func = *I;
6634 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
6635 if (isa<UsingShadowDecl>(Func))
6636 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
6637
John McCall10eae182009-11-30 22:42:35 +00006638 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00006639 // If explicit template arguments were provided, we can't call a
6640 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00006641 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00006642 continue;
6643
John McCalla0296f72010-03-19 07:35:19 +00006644 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00006645 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006646 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006647 } else {
John McCall10eae182009-11-30 22:42:35 +00006648 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00006649 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00006650 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006651 CandidateSet,
6652 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00006653 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00006654 }
Mike Stump11289f42009-09-09 15:08:12 +00006655
John McCall10eae182009-11-30 22:42:35 +00006656 DeclarationName DeclName = UnresExpr->getMemberName();
6657
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006658 OverloadCandidateSet::iterator Best;
John McCall10eae182009-11-30 22:42:35 +00006659 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006660 case OR_Success:
6661 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00006662 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00006663 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006664 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006665 break;
6666
6667 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00006668 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006669 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006670 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006671 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006672 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006673 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006674
6675 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00006676 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00006677 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006678 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006679 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006680 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00006681
6682 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00006683 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00006684 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00006685 << DeclName << MemExprE->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006686 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006687 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00006688 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006689 }
6690
John McCall16df1e52010-03-30 21:47:33 +00006691 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00006692
John McCall2d74de92009-12-01 22:10:20 +00006693 // If overload resolution picked a static member, build a
6694 // non-member call based on that function.
6695 if (Method->isStatic()) {
6696 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
6697 Args, NumArgs, RParenLoc);
6698 }
6699
John McCall10eae182009-11-30 22:42:35 +00006700 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006701 }
6702
6703 assert(Method && "Member call to something that isn't a method?");
Mike Stump11289f42009-09-09 15:08:12 +00006704 ExprOwningPtr<CXXMemberCallExpr>
John McCall2d74de92009-12-01 22:10:20 +00006705 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump11289f42009-09-09 15:08:12 +00006706 NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006707 Method->getResultType().getNonReferenceType(),
6708 RParenLoc));
6709
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006710 // Check for a valid return type.
6711 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
6712 TheCall.get(), Method))
John McCall2d74de92009-12-01 22:10:20 +00006713 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00006714
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006715 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00006716 // We only need to do this if there was actually an overload; otherwise
6717 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00006718 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00006719 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00006720 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
6721 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00006722 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006723 MemExpr->setBase(ObjectArg);
6724
6725 // Convert the rest of the arguments
Douglas Gregorc8be9522010-05-04 18:18:31 +00006726 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Mike Stump11289f42009-09-09 15:08:12 +00006727 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006728 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00006729 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006730
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006731 if (CheckFunctionCall(Method, TheCall.get()))
John McCall2d74de92009-12-01 22:10:20 +00006732 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00006733
John McCall2d74de92009-12-01 22:10:20 +00006734 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006735}
6736
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006737/// BuildCallToObjectOfClassType - Build a call to an object of class
6738/// type (C++ [over.call.object]), which can end up invoking an
6739/// overloaded function call operator (@c operator()) or performing a
6740/// user-defined conversion on the object argument.
Mike Stump11289f42009-09-09 15:08:12 +00006741Sema::ExprResult
6742Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00006743 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006744 Expr **Args, unsigned NumArgs,
Mike Stump11289f42009-09-09 15:08:12 +00006745 SourceLocation *CommaLocs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006746 SourceLocation RParenLoc) {
6747 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006748 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00006749
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006750 // C++ [over.call.object]p1:
6751 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00006752 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006753 // candidate functions includes at least the function call
6754 // operators of T. The function call operators of T are obtained by
6755 // ordinary lookup of the name operator() in the context of
6756 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00006757 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00006758 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006759
6760 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00006761 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006762 << Object->getSourceRange()))
6763 return true;
6764
John McCall27b18f82009-11-17 02:14:36 +00006765 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
6766 LookupQualifiedName(R, Record->getDecl());
6767 R.suppressDiagnostics();
6768
Douglas Gregorc473cbb2009-11-15 07:48:03 +00006769 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00006770 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00006771 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00006772 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00006773 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00006774 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006775
Douglas Gregorab7897a2008-11-19 22:57:39 +00006776 // C++ [over.call.object]p2:
6777 // In addition, for each conversion function declared in T of the
6778 // form
6779 //
6780 // operator conversion-type-id () cv-qualifier;
6781 //
6782 // where cv-qualifier is the same cv-qualification as, or a
6783 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00006784 // denotes the type "pointer to function of (P1,...,Pn) returning
6785 // R", or the type "reference to pointer to function of
6786 // (P1,...,Pn) returning R", or the type "reference to function
6787 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00006788 // is also considered as a candidate function. Similarly,
6789 // surrogate call functions are added to the set of candidate
6790 // functions for each conversion function declared in an
6791 // accessible base class provided the function is not hidden
6792 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00006793 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00006794 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00006795 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00006796 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00006797 NamedDecl *D = *I;
6798 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
6799 if (isa<UsingShadowDecl>(D))
6800 D = cast<UsingShadowDecl>(D)->getTargetDecl();
6801
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006802 // Skip over templated conversion functions; they aren't
6803 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00006804 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006805 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00006806
John McCall6e9f8f62009-12-03 04:06:58 +00006807 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00006808
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006809 // Strip the reference type (if any) and then the pointer type (if
6810 // any) to get down to what might be a function type.
6811 QualType ConvType = Conv->getConversionType().getNonReferenceType();
6812 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6813 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006814
Douglas Gregor74ba25c2009-10-21 06:18:39 +00006815 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00006816 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00006817 Object->getType(), Args, NumArgs,
6818 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00006819 }
Mike Stump11289f42009-09-09 15:08:12 +00006820
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006821 // Perform overload resolution.
6822 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006823 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006824 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00006825 // Overload resolution succeeded; we'll build the appropriate call
6826 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006827 break;
6828
6829 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00006830 if (CandidateSet.empty())
6831 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
6832 << Object->getType() << /*call*/ 1
6833 << Object->getSourceRange();
6834 else
6835 Diag(Object->getSourceRange().getBegin(),
6836 diag::err_ovl_no_viable_object_call)
6837 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006838 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006839 break;
6840
6841 case OR_Ambiguous:
6842 Diag(Object->getSourceRange().getBegin(),
6843 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00006844 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006845 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006846 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006847
6848 case OR_Deleted:
6849 Diag(Object->getSourceRange().getBegin(),
6850 diag::err_ovl_deleted_object_call)
6851 << Best->Function->isDeleted()
6852 << Object->getType() << Object->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00006853 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006854 break;
Mike Stump11289f42009-09-09 15:08:12 +00006855 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006856
Douglas Gregorab7897a2008-11-19 22:57:39 +00006857 if (Best == CandidateSet.end()) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006858 // We had an error; delete all of the subexpressions and return
6859 // the error.
Ted Kremenek5a201952009-02-07 01:47:29 +00006860 Object->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006861 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
Ted Kremenek5a201952009-02-07 01:47:29 +00006862 Args[ArgIdx]->Destroy(Context);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006863 return true;
6864 }
6865
Douglas Gregorab7897a2008-11-19 22:57:39 +00006866 if (Best->Function == 0) {
6867 // Since there is no function declaration, this is one of the
6868 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00006869 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00006870 = cast<CXXConversionDecl>(
6871 Best->Conversions[0].UserDefined.ConversionFunction);
6872
John McCalla0296f72010-03-19 07:35:19 +00006873 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006874 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00006875
Douglas Gregorab7897a2008-11-19 22:57:39 +00006876 // We selected one of the surrogate functions that converts the
6877 // object parameter to a function pointer. Perform the conversion
6878 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006879
6880 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006881 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00006882 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
6883 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00006884
Fariborz Jahanian774cf792009-09-28 18:35:46 +00006885 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redlc215cfc2009-01-19 00:08:26 +00006886 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
Douglas Gregore5e775b2010-04-13 15:50:39 +00006887 CommaLocs, RParenLoc).result();
Douglas Gregorab7897a2008-11-19 22:57:39 +00006888 }
6889
John McCalla0296f72010-03-19 07:35:19 +00006890 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006891 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00006892
Douglas Gregorab7897a2008-11-19 22:57:39 +00006893 // We found an overloaded operator(). Build a CXXOperatorCallExpr
6894 // that calls this method, using Object for the implicit object
6895 // parameter and passing along the remaining arguments.
6896 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00006897 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006898
6899 unsigned NumArgsInProto = Proto->getNumArgs();
6900 unsigned NumArgsToCheck = NumArgs;
6901
6902 // Build the full argument list for the method call (the
6903 // implicit object parameter is placed at the beginning of the
6904 // list).
6905 Expr **MethodArgs;
6906 if (NumArgs < NumArgsInProto) {
6907 NumArgsToCheck = NumArgsInProto;
6908 MethodArgs = new Expr*[NumArgsInProto + 1];
6909 } else {
6910 MethodArgs = new Expr*[NumArgs + 1];
6911 }
6912 MethodArgs[0] = Object;
6913 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6914 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00006915
6916 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00006917 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006918 UsualUnaryConversions(NewFn);
6919
6920 // Once we've built TheCall, all of the expressions are properly
6921 // owned.
6922 QualType ResultTy = Method->getResultType().getNonReferenceType();
Mike Stump11289f42009-09-09 15:08:12 +00006923 ExprOwningPtr<CXXOperatorCallExpr>
6924 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006925 MethodArgs, NumArgs + 1,
Ted Kremenek5a201952009-02-07 01:47:29 +00006926 ResultTy, RParenLoc));
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006927 delete [] MethodArgs;
6928
Anders Carlsson3d5829c2009-10-13 21:49:31 +00006929 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
6930 Method))
6931 return true;
6932
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006933 // We may have default arguments. If so, we need to allocate more
6934 // slots in the call for them.
6935 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00006936 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006937 else if (NumArgs > NumArgsInProto)
6938 NumArgsToCheck = NumArgsInProto;
6939
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006940 bool IsError = false;
6941
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006942 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00006943 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00006944 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006945 TheCall->setArg(0, Object);
6946
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006947
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006948 // Check the argument types.
6949 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006950 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006951 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006952 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00006953
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006954 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00006955
6956 OwningExprResult InputInit
6957 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
6958 Method->getParamDecl(i)),
6959 SourceLocation(), Owned(Arg));
6960
6961 IsError |= InputInit.isInvalid();
6962 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006963 } else {
Douglas Gregor1bc688d2009-11-09 19:27:57 +00006964 OwningExprResult DefArg
6965 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
6966 if (DefArg.isInvalid()) {
6967 IsError = true;
6968 break;
6969 }
6970
6971 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00006972 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006973
6974 TheCall->setArg(i + 1, Arg);
6975 }
6976
6977 // If this is a variadic call, handle args passed through "...".
6978 if (Proto->isVariadic()) {
6979 // Promote the arguments (C99 6.5.2.2p7).
6980 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
6981 Expr *Arg = Args[i];
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006982 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006983 TheCall->setArg(i + 1, Arg);
6984 }
6985 }
6986
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00006987 if (IsError) return true;
6988
Anders Carlssonbc4c1072009-08-16 01:56:34 +00006989 if (CheckFunctionCall(Method, TheCall.get()))
6990 return true;
6991
Douglas Gregore5e775b2010-04-13 15:50:39 +00006992 return MaybeBindToTemporary(TheCall.release()).result();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00006993}
6994
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006995/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00006996/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00006997/// @c Member is the name of the member we're trying to find.
Douglas Gregord8061562009-08-06 03:17:00 +00006998Sema::OwningExprResult
6999Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
7000 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007001 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00007002
John McCallbc077cf2010-02-08 23:07:23 +00007003 SourceLocation Loc = Base->getExprLoc();
7004
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007005 // C++ [over.ref]p1:
7006 //
7007 // [...] An expression x->m is interpreted as (x.operator->())->m
7008 // for a class object x of type T if T::operator->() exists and if
7009 // the operator is selected as the best match function by the
7010 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007011 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00007012 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007013 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00007014
John McCallbc077cf2010-02-08 23:07:23 +00007015 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00007016 PDiag(diag::err_typecheck_incomplete_tag)
7017 << Base->getSourceRange()))
7018 return ExprError();
7019
John McCall27b18f82009-11-17 02:14:36 +00007020 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7021 LookupQualifiedName(R, BaseRecord->getDecl());
7022 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00007023
7024 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00007025 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007026 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007027 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00007028 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007029
7030 // Perform overload resolution.
7031 OverloadCandidateSet::iterator Best;
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007032 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007033 case OR_Success:
7034 // Overload resolution succeeded; we'll build the call below.
7035 break;
7036
7037 case OR_No_Viable_Function:
7038 if (CandidateSet.empty())
7039 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00007040 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007041 else
7042 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00007043 << "operator->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007044 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007045 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007046
7047 case OR_Ambiguous:
7048 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00007049 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007050 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007051 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007052
7053 case OR_Deleted:
7054 Diag(OpLoc, diag::err_ovl_deleted_oper)
7055 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00007056 << "->" << Base->getSourceRange();
John McCallad907772010-01-12 07:18:19 +00007057 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007058 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007059 }
7060
John McCalla0296f72010-03-19 07:35:19 +00007061 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007062 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00007063
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007064 // Convert the object parameter.
7065 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007066 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7067 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00007068 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00007069
7070 // No concerns about early exits now.
Douglas Gregord8061562009-08-06 03:17:00 +00007071 BaseIn.release();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007072
7073 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00007074 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7075 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007076 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007077
7078 QualType ResultTy = Method->getResultType().getNonReferenceType();
7079 ExprOwningPtr<CXXOperatorCallExpr>
7080 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7081 &Base, 1, ResultTy, OpLoc));
7082
7083 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
7084 Method))
7085 return ExprError();
7086 return move(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007087}
7088
Douglas Gregorcd695e52008-11-10 20:40:00 +00007089/// FixOverloadedFunctionReference - E is an expression that refers to
7090/// a C++ overloaded function (possibly with some parentheses and
7091/// perhaps a '&' around it). We have resolved the overloaded function
7092/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007093/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00007094Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00007095 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00007096 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007097 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7098 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007099 if (SubExpr == PE->getSubExpr())
7100 return PE->Retain();
7101
7102 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7103 }
7104
7105 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007106 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7107 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00007108 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00007109 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00007110 "Implicit cast type cannot be determined from overload");
Douglas Gregor51c538b2009-11-20 19:42:02 +00007111 if (SubExpr == ICE->getSubExpr())
7112 return ICE->Retain();
7113
7114 return new (Context) ImplicitCastExpr(ICE->getType(),
7115 ICE->getCastKind(),
Anders Carlsson0c509ee2010-04-24 16:57:13 +00007116 SubExpr, CXXBaseSpecifierArray(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00007117 ICE->isLvalueCast());
7118 }
7119
7120 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump11289f42009-09-09 15:08:12 +00007121 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00007122 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007123 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7124 if (Method->isStatic()) {
7125 // Do nothing: static member functions aren't any different
7126 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00007127 } else {
John McCalle66edc12009-11-24 19:00:30 +00007128 // Fix the sub expression, which really has to be an
7129 // UnresolvedLookupExpr holding an overloaded member function
7130 // or template.
John McCall16df1e52010-03-30 21:47:33 +00007131 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7132 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00007133 if (SubExpr == UnOp->getSubExpr())
7134 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00007135
John McCalld14a8642009-11-21 08:51:07 +00007136 assert(isa<DeclRefExpr>(SubExpr)
7137 && "fixed to something other than a decl ref");
7138 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7139 && "fixed to a member ref with no nested name qualifier");
7140
7141 // We have taken the address of a pointer to member
7142 // function. Perform the computation here so that we get the
7143 // appropriate pointer to member type.
7144 QualType ClassType
7145 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7146 QualType MemPtrType
7147 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7148
7149 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7150 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007151 }
7152 }
John McCall16df1e52010-03-30 21:47:33 +00007153 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7154 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007155 if (SubExpr == UnOp->getSubExpr())
7156 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007157
Douglas Gregor51c538b2009-11-20 19:42:02 +00007158 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7159 Context.getPointerType(SubExpr->getType()),
7160 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00007161 }
John McCalld14a8642009-11-21 08:51:07 +00007162
7163 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00007164 // FIXME: avoid copy.
7165 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00007166 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00007167 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7168 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00007169 }
7170
John McCalld14a8642009-11-21 08:51:07 +00007171 return DeclRefExpr::Create(Context,
7172 ULE->getQualifier(),
7173 ULE->getQualifierRange(),
7174 Fn,
7175 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00007176 Fn->getType(),
7177 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00007178 }
7179
John McCall10eae182009-11-30 22:42:35 +00007180 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00007181 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00007182 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7183 if (MemExpr->hasExplicitTemplateArgs()) {
7184 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7185 TemplateArgs = &TemplateArgsBuffer;
7186 }
John McCall6b51f282009-11-23 01:53:49 +00007187
John McCall2d74de92009-12-01 22:10:20 +00007188 Expr *Base;
7189
7190 // If we're filling in
7191 if (MemExpr->isImplicitAccess()) {
7192 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7193 return DeclRefExpr::Create(Context,
7194 MemExpr->getQualifier(),
7195 MemExpr->getQualifierRange(),
7196 Fn,
7197 MemExpr->getMemberLoc(),
7198 Fn->getType(),
7199 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00007200 } else {
7201 SourceLocation Loc = MemExpr->getMemberLoc();
7202 if (MemExpr->getQualifier())
7203 Loc = MemExpr->getQualifierRange().getBegin();
7204 Base = new (Context) CXXThisExpr(Loc,
7205 MemExpr->getBaseType(),
7206 /*isImplicit=*/true);
7207 }
John McCall2d74de92009-12-01 22:10:20 +00007208 } else
7209 Base = MemExpr->getBase()->Retain();
7210
7211 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007212 MemExpr->isArrow(),
7213 MemExpr->getQualifier(),
7214 MemExpr->getQualifierRange(),
7215 Fn,
John McCall16df1e52010-03-30 21:47:33 +00007216 Found,
John McCall6b51f282009-11-23 01:53:49 +00007217 MemExpr->getMemberLoc(),
John McCall2d74de92009-12-01 22:10:20 +00007218 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007219 Fn->getType());
7220 }
7221
Douglas Gregor51c538b2009-11-20 19:42:02 +00007222 assert(false && "Invalid reference to overloaded function");
7223 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00007224}
7225
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007226Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCalla8ae2222010-04-06 21:38:20 +00007227 DeclAccessPair Found,
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007228 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00007229 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007230}
7231
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007232} // end namespace clang