blob: 919aea8d024abab2b88822d30c3ef2ae1641ed25 [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
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000024#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000025#include "clang/AST/ExprCXX.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000026#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000027#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000028#include "llvm/ADT/DenseSet.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000029#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000030#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000031#include <algorithm>
32
33namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000034using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000035
John McCall5c32be02010-08-24 20:38:10 +000036static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
37 bool InOverloadResolution,
38 StandardConversionSequence &SCS);
39static OverloadingResult
40IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
41 UserDefinedConversionSequence& User,
42 OverloadCandidateSet& Conversions,
43 bool AllowExplicit);
44
45
46static ImplicitConversionSequence::CompareKind
47CompareStandardConversionSequences(Sema &S,
48 const StandardConversionSequence& SCS1,
49 const StandardConversionSequence& SCS2);
50
51static ImplicitConversionSequence::CompareKind
52CompareQualificationConversions(Sema &S,
53 const StandardConversionSequence& SCS1,
54 const StandardConversionSequence& SCS2);
55
56static ImplicitConversionSequence::CompareKind
57CompareDerivedToBaseConversions(Sema &S,
58 const StandardConversionSequence& SCS1,
59 const StandardConversionSequence& SCS2);
60
61
62
Douglas Gregor5251f1b2008-10-21 16:13:35 +000063/// GetConversionCategory - Retrieve the implicit conversion
64/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000065ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000066GetConversionCategory(ImplicitConversionKind Kind) {
67 static const ImplicitConversionCategory
68 Category[(int)ICK_Num_Conversion_Kinds] = {
69 ICC_Identity,
70 ICC_Lvalue_Transformation,
71 ICC_Lvalue_Transformation,
72 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000073 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000074 ICC_Qualification_Adjustment,
75 ICC_Promotion,
76 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000077 ICC_Promotion,
78 ICC_Conversion,
79 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000080 ICC_Conversion,
81 ICC_Conversion,
82 ICC_Conversion,
83 ICC_Conversion,
84 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000085 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000086 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +000087 ICC_Conversion,
88 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000089 ICC_Conversion
90 };
91 return Category[(int)Kind];
92}
93
94/// GetConversionRank - Retrieve the implicit conversion rank
95/// corresponding to the given implicit conversion kind.
96ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
97 static const ImplicitConversionRank
98 Rank[(int)ICK_Num_Conversion_Kinds] = {
99 ICR_Exact_Match,
100 ICR_Exact_Match,
101 ICR_Exact_Match,
102 ICR_Exact_Match,
103 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000104 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000105 ICR_Promotion,
106 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000107 ICR_Promotion,
108 ICR_Conversion,
109 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000110 ICR_Conversion,
111 ICR_Conversion,
112 ICR_Conversion,
113 ICR_Conversion,
114 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000115 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000116 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000117 ICR_Conversion,
118 ICR_Conversion,
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +0000119 ICR_Complex_Real_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000120 };
121 return Rank[(int)Kind];
122}
123
124/// GetImplicitConversionName - Return the name of this kind of
125/// implicit conversion.
126const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000127 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000128 "No conversion",
129 "Lvalue-to-rvalue",
130 "Array-to-pointer",
131 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000132 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000133 "Qualification",
134 "Integral promotion",
135 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000136 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000137 "Integral conversion",
138 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000139 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000140 "Floating-integral conversion",
141 "Pointer conversion",
142 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000143 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000144 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000145 "Derived-to-base conversion",
146 "Vector conversion",
147 "Vector splat",
148 "Complex-real conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000149 };
150 return Name[Kind];
151}
152
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000153/// StandardConversionSequence - Set the standard conversion
154/// sequence to the identity conversion.
155void StandardConversionSequence::setAsIdentityConversion() {
156 First = ICK_Identity;
157 Second = ICK_Identity;
158 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000159 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000160 ReferenceBinding = false;
161 DirectBinding = false;
Sebastian Redlf69a94a2009-03-29 22:46:24 +0000162 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000163 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000164}
165
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000166/// getRank - Retrieve the rank of this standard conversion sequence
167/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
168/// implicit conversions.
169ImplicitConversionRank StandardConversionSequence::getRank() const {
170 ImplicitConversionRank Rank = ICR_Exact_Match;
171 if (GetConversionRank(First) > Rank)
172 Rank = GetConversionRank(First);
173 if (GetConversionRank(Second) > Rank)
174 Rank = GetConversionRank(Second);
175 if (GetConversionRank(Third) > Rank)
176 Rank = GetConversionRank(Third);
177 return Rank;
178}
179
180/// isPointerConversionToBool - Determines whether this conversion is
181/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000182/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000183/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000184bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000185 // Note that FromType has not necessarily been transformed by the
186 // array-to-pointer or function-to-pointer implicit conversions, so
187 // check for their presence as well as checking whether FromType is
188 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000189 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000190 (getFromType()->isPointerType() ||
191 getFromType()->isObjCObjectPointerType() ||
192 getFromType()->isBlockPointerType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000193 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
194 return true;
195
196 return false;
197}
198
Douglas Gregor5c407d92008-10-23 00:40:37 +0000199/// isPointerConversionToVoidPointer - Determines whether this
200/// conversion is a conversion of a pointer to a void pointer. This is
201/// used as part of the ranking of standard conversion sequences (C++
202/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000203bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000204StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000205isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000206 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000207 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000208
209 // Note that FromType has not necessarily been transformed by the
210 // array-to-pointer implicit conversion, so check for its presence
211 // and redo the conversion to get a pointer.
212 if (First == ICK_Array_To_Pointer)
213 FromType = Context.getArrayDecayedType(FromType);
214
Douglas Gregor1aa450a2009-12-13 21:37:05 +0000215 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000216 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000217 return ToPtrType->getPointeeType()->isVoidType();
218
219 return false;
220}
221
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000222/// DebugPrint - Print this standard conversion sequence to standard
223/// error. Useful for debugging overloading issues.
224void StandardConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000225 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000226 bool PrintedSomething = false;
227 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000228 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000229 PrintedSomething = true;
230 }
231
232 if (Second != ICK_Identity) {
233 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000234 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000235 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000236 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000237
238 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000239 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000240 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000241 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000242 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000243 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000244 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000245 PrintedSomething = true;
246 }
247
248 if (Third != ICK_Identity) {
249 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000250 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000251 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000252 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000253 PrintedSomething = true;
254 }
255
256 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000257 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000258 }
259}
260
261/// DebugPrint - Print this user-defined conversion sequence to standard
262/// error. Useful for debugging overloading issues.
263void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000264 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000265 if (Before.First || Before.Second || Before.Third) {
266 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000267 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000268 }
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000269 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000270 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000271 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000272 After.DebugPrint();
273 }
274}
275
276/// DebugPrint - Print this implicit conversion sequence to standard
277/// error. Useful for debugging overloading issues.
278void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000279 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000280 switch (ConversionKind) {
281 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000282 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000283 Standard.DebugPrint();
284 break;
285 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000286 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000287 UserDefined.DebugPrint();
288 break;
289 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000290 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000291 break;
John McCall0d1da222010-01-12 00:44:57 +0000292 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000293 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000294 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000295 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000296 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000297 break;
298 }
299
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000300 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000301}
302
John McCall0d1da222010-01-12 00:44:57 +0000303void AmbiguousConversionSequence::construct() {
304 new (&conversions()) ConversionSet();
305}
306
307void AmbiguousConversionSequence::destruct() {
308 conversions().~ConversionSet();
309}
310
311void
312AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
313 FromTypePtr = O.FromTypePtr;
314 ToTypePtr = O.ToTypePtr;
315 new (&conversions()) ConversionSet(O.conversions());
316}
317
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000318namespace {
319 // Structure used by OverloadCandidate::DeductionFailureInfo to store
320 // template parameter and template argument information.
321 struct DFIParamWithArguments {
322 TemplateParameter Param;
323 TemplateArgument FirstArg;
324 TemplateArgument SecondArg;
325 };
326}
327
328/// \brief Convert from Sema's representation of template deduction information
329/// to the form used in overload-candidate information.
330OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000331static MakeDeductionFailureInfo(ASTContext &Context,
332 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000333 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000334 OverloadCandidate::DeductionFailureInfo Result;
335 Result.Result = static_cast<unsigned>(TDK);
336 Result.Data = 0;
337 switch (TDK) {
338 case Sema::TDK_Success:
339 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000340 case Sema::TDK_TooManyArguments:
341 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000342 break;
343
344 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000345 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000346 Result.Data = Info.Param.getOpaqueValue();
347 break;
348
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000349 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000350 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000351 // FIXME: Should allocate from normal heap so that we can free this later.
352 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000353 Saved->Param = Info.Param;
354 Saved->FirstArg = Info.FirstArg;
355 Saved->SecondArg = Info.SecondArg;
356 Result.Data = Saved;
357 break;
358 }
359
360 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000361 Result.Data = Info.take();
362 break;
363
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000364 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000365 case Sema::TDK_FailedOverloadResolution:
366 break;
367 }
368
369 return Result;
370}
John McCall0d1da222010-01-12 00:44:57 +0000371
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000372void OverloadCandidate::DeductionFailureInfo::Destroy() {
373 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
374 case Sema::TDK_Success:
375 case Sema::TDK_InstantiationDepth:
376 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000377 case Sema::TDK_TooManyArguments:
378 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000379 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000380 break;
381
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000382 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000383 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000384 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000385 Data = 0;
386 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000387
388 case Sema::TDK_SubstitutionFailure:
389 // FIXME: Destroy the template arugment list?
390 Data = 0;
391 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000392
Douglas Gregor461761d2010-05-08 18:20:53 +0000393 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000394 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000395 case Sema::TDK_FailedOverloadResolution:
396 break;
397 }
398}
399
400TemplateParameter
401OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
402 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
403 case Sema::TDK_Success:
404 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000405 case Sema::TDK_TooManyArguments:
406 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000407 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000408 return TemplateParameter();
409
410 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000411 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000412 return TemplateParameter::getFromOpaqueValue(Data);
413
414 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000415 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000416 return static_cast<DFIParamWithArguments*>(Data)->Param;
417
418 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000419 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000420 case Sema::TDK_FailedOverloadResolution:
421 break;
422 }
423
424 return TemplateParameter();
425}
Douglas Gregord09efd42010-05-08 20:07:26 +0000426
427TemplateArgumentList *
428OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
429 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
430 case Sema::TDK_Success:
431 case Sema::TDK_InstantiationDepth:
432 case Sema::TDK_TooManyArguments:
433 case Sema::TDK_TooFewArguments:
434 case Sema::TDK_Incomplete:
435 case Sema::TDK_InvalidExplicitArguments:
436 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000437 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000438 return 0;
439
440 case Sema::TDK_SubstitutionFailure:
441 return static_cast<TemplateArgumentList*>(Data);
442
443 // Unhandled
444 case Sema::TDK_NonDeducedMismatch:
445 case Sema::TDK_FailedOverloadResolution:
446 break;
447 }
448
449 return 0;
450}
451
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000452const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
453 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
454 case Sema::TDK_Success:
455 case Sema::TDK_InstantiationDepth:
456 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000457 case Sema::TDK_TooManyArguments:
458 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000459 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000460 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000461 return 0;
462
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000463 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000464 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000465 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
466
Douglas Gregor461761d2010-05-08 18:20:53 +0000467 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000468 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000469 case Sema::TDK_FailedOverloadResolution:
470 break;
471 }
472
473 return 0;
474}
475
476const TemplateArgument *
477OverloadCandidate::DeductionFailureInfo::getSecondArg() {
478 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
479 case Sema::TDK_Success:
480 case Sema::TDK_InstantiationDepth:
481 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000482 case Sema::TDK_TooManyArguments:
483 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000484 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000485 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000486 return 0;
487
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000488 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000489 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000490 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
491
Douglas Gregor461761d2010-05-08 18:20:53 +0000492 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000493 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000494 case Sema::TDK_FailedOverloadResolution:
495 break;
496 }
497
498 return 0;
499}
500
501void OverloadCandidateSet::clear() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000502 inherited::clear();
503 Functions.clear();
504}
505
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000506// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000507// overload of the declarations in Old. This routine returns false if
508// New and Old cannot be overloaded, e.g., if New has the same
509// signature as some function in Old (C++ 1.3.10) or if the Old
510// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000511// it does return false, MatchedDecl will point to the decl that New
512// cannot be overloaded with. This decl may be a UsingShadowDecl on
513// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000514//
515// Example: Given the following input:
516//
517// void f(int, float); // #1
518// void f(int, int); // #2
519// int f(int, int); // #3
520//
521// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000522// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000523//
John McCall3d988d92009-12-02 08:47:38 +0000524// When we process #2, Old contains only the FunctionDecl for #1. By
525// comparing the parameter types, we see that #1 and #2 are overloaded
526// (since they have different signatures), so this routine returns
527// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000528//
John McCall3d988d92009-12-02 08:47:38 +0000529// When we process #3, Old is an overload set containing #1 and #2. We
530// compare the signatures of #3 to #1 (they're overloaded, so we do
531// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
532// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000533// signature), IsOverload returns false and MatchedDecl will be set to
534// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000535//
536// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
537// into a class by a using declaration. The rules for whether to hide
538// shadow declarations ignore some properties which otherwise figure
539// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000540Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000541Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
542 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000543 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000544 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000545 NamedDecl *OldD = *I;
546
547 bool OldIsUsingDecl = false;
548 if (isa<UsingShadowDecl>(OldD)) {
549 OldIsUsingDecl = true;
550
551 // We can always introduce two using declarations into the same
552 // context, even if they have identical signatures.
553 if (NewIsUsingDecl) continue;
554
555 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
556 }
557
558 // If either declaration was introduced by a using declaration,
559 // we'll need to use slightly different rules for matching.
560 // Essentially, these rules are the normal rules, except that
561 // function templates hide function templates with different
562 // return types or template parameter lists.
563 bool UseMemberUsingDeclRules =
564 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
565
John McCall3d988d92009-12-02 08:47:38 +0000566 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000567 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
568 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
569 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
570 continue;
571 }
572
John McCalldaa3d6b2009-12-09 03:35:25 +0000573 Match = *I;
574 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000575 }
John McCall3d988d92009-12-02 08:47:38 +0000576 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000577 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
578 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
579 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
580 continue;
581 }
582
John McCalldaa3d6b2009-12-09 03:35:25 +0000583 Match = *I;
584 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000585 }
John McCall84d87672009-12-10 09:41:52 +0000586 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
587 // We can overload with these, which can show up when doing
588 // redeclaration checks for UsingDecls.
589 assert(Old.getLookupKind() == LookupUsingDeclName);
590 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
591 // Optimistically assume that an unresolved using decl will
592 // overload; if it doesn't, we'll have to diagnose during
593 // template instantiation.
594 } else {
John McCall1f82f242009-11-18 22:49:29 +0000595 // (C++ 13p1):
596 // Only function declarations can be overloaded; object and type
597 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000598 Match = *I;
599 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000600 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000601 }
John McCall1f82f242009-11-18 22:49:29 +0000602
John McCalldaa3d6b2009-12-09 03:35:25 +0000603 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000604}
605
John McCalle9cccd82010-06-16 08:42:20 +0000606bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
607 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000608 // If both of the functions are extern "C", then they are not
609 // overloads.
610 if (Old->isExternC() && New->isExternC())
611 return false;
612
John McCall1f82f242009-11-18 22:49:29 +0000613 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
614 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
615
616 // C++ [temp.fct]p2:
617 // A function template can be overloaded with other function templates
618 // and with normal (non-template) functions.
619 if ((OldTemplate == 0) != (NewTemplate == 0))
620 return true;
621
622 // Is the function New an overload of the function Old?
623 QualType OldQType = Context.getCanonicalType(Old->getType());
624 QualType NewQType = Context.getCanonicalType(New->getType());
625
626 // Compare the signatures (C++ 1.3.10) of the two functions to
627 // determine whether they are overloads. If we find any mismatch
628 // in the signature, they are overloads.
629
630 // If either of these functions is a K&R-style function (no
631 // prototype), then we consider them to have matching signatures.
632 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
633 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
634 return false;
635
636 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
637 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
638
639 // The signature of a function includes the types of its
640 // parameters (C++ 1.3.10), which includes the presence or absence
641 // of the ellipsis; see C++ DR 357).
642 if (OldQType != NewQType &&
643 (OldType->getNumArgs() != NewType->getNumArgs() ||
644 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000645 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000646 return true;
647
648 // C++ [temp.over.link]p4:
649 // The signature of a function template consists of its function
650 // signature, its return type and its template parameter list. The names
651 // of the template parameters are significant only for establishing the
652 // relationship between the template parameters and the rest of the
653 // signature.
654 //
655 // We check the return type and template parameter lists for function
656 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000657 //
658 // However, we don't consider either of these when deciding whether
659 // a member introduced by a shadow declaration is hidden.
660 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000661 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
662 OldTemplate->getTemplateParameters(),
663 false, TPL_TemplateMatch) ||
664 OldType->getResultType() != NewType->getResultType()))
665 return true;
666
667 // If the function is a class member, its signature includes the
668 // cv-qualifiers (if any) on the function itself.
669 //
670 // As part of this, also check whether one of the member functions
671 // is static, in which case they are not overloads (C++
672 // 13.1p2). While not part of the definition of the signature,
673 // this check is important to determine whether these functions
674 // can be overloaded.
675 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
676 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
677 if (OldMethod && NewMethod &&
678 !OldMethod->isStatic() && !NewMethod->isStatic() &&
679 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
680 return true;
681
682 // The signatures match; this is not an overload.
683 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000684}
685
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000686/// TryImplicitConversion - Attempt to perform an implicit conversion
687/// from the given expression (Expr) to the given type (ToType). This
688/// function returns an implicit conversion sequence that can be used
689/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000690///
691/// void f(float f);
692/// void g(int i) { f(i); }
693///
694/// this routine would produce an implicit conversion sequence to
695/// describe the initialization of f from i, which will be a standard
696/// conversion sequence containing an lvalue-to-rvalue conversion (C++
697/// 4.1) followed by a floating-integral conversion (C++ 4.9).
698//
699/// Note that this routine only determines how the conversion can be
700/// performed; it does not actually perform the conversion. As such,
701/// it will not produce any diagnostics if no conversion is available,
702/// but will instead return an implicit conversion sequence of kind
703/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000704///
705/// If @p SuppressUserConversions, then user-defined conversions are
706/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000707/// If @p AllowExplicit, then explicit user-defined conversions are
708/// permitted.
John McCall5c32be02010-08-24 20:38:10 +0000709static ImplicitConversionSequence
710TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
711 bool SuppressUserConversions,
712 bool AllowExplicit,
713 bool InOverloadResolution) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000714 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +0000715 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
716 ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000717 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000718 return ICS;
719 }
720
John McCall5c32be02010-08-24 20:38:10 +0000721 if (!S.getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000722 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000723 return ICS;
724 }
725
Douglas Gregor836a7e82010-08-11 02:15:33 +0000726 // C++ [over.ics.user]p4:
727 // A conversion of an expression of class type to the same class
728 // type is given Exact Match rank, and a conversion of an
729 // expression of class type to a base class of that type is
730 // given Conversion rank, in spite of the fact that a copy/move
731 // constructor (i.e., a user-defined conversion function) is
732 // called for those cases.
733 QualType FromType = From->getType();
734 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +0000735 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
736 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000737 ICS.setStandard();
738 ICS.Standard.setAsIdentityConversion();
739 ICS.Standard.setFromType(FromType);
740 ICS.Standard.setAllToTypes(ToType);
741
742 // We don't actually check at this point whether there is a valid
743 // copy/move constructor, since overloading just assumes that it
744 // exists. When we actually perform initialization, we'll find the
745 // appropriate constructor to copy the returned object, if needed.
746 ICS.Standard.CopyConstructor = 0;
Douglas Gregor836a7e82010-08-11 02:15:33 +0000747
Douglas Gregor5ab11652010-04-17 22:01:05 +0000748 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +0000749 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +0000750 ICS.Standard.Second = ICK_Derived_To_Base;
Douglas Gregor836a7e82010-08-11 02:15:33 +0000751
752 return ICS;
753 }
754
755 if (SuppressUserConversions) {
756 // We're not in the case above, so there is no conversion that
757 // we can perform.
758 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor5ab11652010-04-17 22:01:05 +0000759 return ICS;
760 }
761
762 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000763 OverloadCandidateSet Conversions(From->getExprLoc());
764 OverloadingResult UserDefResult
John McCall5c32be02010-08-24 20:38:10 +0000765 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000766 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000767
768 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000769 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000770 // C++ [over.ics.user]p4:
771 // A conversion of an expression of class type to the same class
772 // type is given Exact Match rank, and a conversion of an
773 // expression of class type to a base class of that type is
774 // given Conversion rank, in spite of the fact that a copy
775 // constructor (i.e., a user-defined conversion function) is
776 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000777 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000778 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000779 QualType FromCanon
John McCall5c32be02010-08-24 20:38:10 +0000780 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
781 QualType ToCanon
782 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000783 if (Constructor->isCopyConstructor() &&
John McCall5c32be02010-08-24 20:38:10 +0000784 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000785 // Turn this into a "standard" conversion sequence, so that it
786 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000787 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000788 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000789 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000790 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000791 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000792 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000793 ICS.Standard.Second = ICK_Derived_To_Base;
794 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000795 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000796
797 // C++ [over.best.ics]p4:
798 // However, when considering the argument of a user-defined
799 // conversion function that is a candidate by 13.3.1.3 when
800 // invoked for the copying of the temporary in the second step
801 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
802 // 13.3.1.6 in all cases, only standard conversion sequences and
803 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000804 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000805 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000806 }
John McCalle8c8cd22010-01-13 22:30:33 +0000807 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000808 ICS.setAmbiguous();
809 ICS.Ambiguous.setFromType(From->getType());
810 ICS.Ambiguous.setToType(ToType);
811 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
812 Cand != Conversions.end(); ++Cand)
813 if (Cand->Viable)
814 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000815 } else {
John McCall65eb8792010-02-25 01:37:24 +0000816 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000817 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000818
819 return ICS;
820}
821
John McCall5c32be02010-08-24 20:38:10 +0000822bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
823 const InitializedEntity &Entity,
824 Expr *Initializer,
825 bool SuppressUserConversions,
826 bool AllowExplicitConversions,
827 bool InOverloadResolution) {
828 ImplicitConversionSequence ICS
829 = clang::TryImplicitConversion(*this, Initializer, Entity.getType(),
830 SuppressUserConversions,
831 AllowExplicitConversions,
832 InOverloadResolution);
833 if (ICS.isBad()) return true;
834
835 // Perform the actual conversion.
836 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
837 return false;
838}
839
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000840/// PerformImplicitConversion - Perform an implicit conversion of the
841/// expression From to the type ToType. Returns true if there was an
842/// error, false otherwise. The expression From is replaced with the
843/// converted expression. Flavor is the kind of conversion we're
844/// performing, used in the error message. If @p AllowExplicit,
845/// explicit user-defined conversions are permitted.
846bool
847Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
848 AssignmentAction Action, bool AllowExplicit) {
849 ImplicitConversionSequence ICS;
850 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
851}
852
853bool
854Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
855 AssignmentAction Action, bool AllowExplicit,
856 ImplicitConversionSequence& ICS) {
John McCall5c32be02010-08-24 20:38:10 +0000857 ICS = clang::TryImplicitConversion(*this, From, ToType,
858 /*SuppressUserConversions=*/false,
859 AllowExplicit,
860 /*InOverloadResolution=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000861 return PerformImplicitConversion(From, ToType, ICS, Action);
862}
863
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000864/// \brief Determine whether the conversion from FromType to ToType is a valid
865/// conversion that strips "noreturn" off the nested function type.
866static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
867 QualType ToType, QualType &ResultTy) {
868 if (Context.hasSameUnqualifiedType(FromType, ToType))
869 return false;
870
871 // Strip the noreturn off the type we're converting from; noreturn can
872 // safely be removed.
873 FromType = Context.getNoReturnType(FromType, false);
874 if (!Context.hasSameUnqualifiedType(FromType, ToType))
875 return false;
876
877 ResultTy = FromType;
878 return true;
879}
Douglas Gregor46188682010-05-18 22:42:18 +0000880
881/// \brief Determine whether the conversion from FromType to ToType is a valid
882/// vector conversion.
883///
884/// \param ICK Will be set to the vector conversion kind, if this is a vector
885/// conversion.
886static bool IsVectorConversion(ASTContext &Context, QualType FromType,
887 QualType ToType, ImplicitConversionKind &ICK) {
888 // We need at least one of these types to be a vector type to have a vector
889 // conversion.
890 if (!ToType->isVectorType() && !FromType->isVectorType())
891 return false;
892
893 // Identical types require no conversions.
894 if (Context.hasSameUnqualifiedType(FromType, ToType))
895 return false;
896
897 // There are no conversions between extended vector types, only identity.
898 if (ToType->isExtVectorType()) {
899 // There are no conversions between extended vector types other than the
900 // identity conversion.
901 if (FromType->isExtVectorType())
902 return false;
903
904 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +0000905 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +0000906 ICK = ICK_Vector_Splat;
907 return true;
908 }
909 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000910
911 // We can perform the conversion between vector types in the following cases:
912 // 1)vector types are equivalent AltiVec and GCC vector types
913 // 2)lax vector conversions are permitted and the vector types are of the
914 // same size
915 if (ToType->isVectorType() && FromType->isVectorType()) {
916 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +0000917 (Context.getLangOptions().LaxVectorConversions &&
918 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000919 ICK = ICK_Vector_Conversion;
920 return true;
921 }
Douglas Gregor46188682010-05-18 22:42:18 +0000922 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000923
Douglas Gregor46188682010-05-18 22:42:18 +0000924 return false;
925}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000926
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000927/// IsStandardConversion - Determines whether there is a standard
928/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
929/// expression From to the type ToType. Standard conversion sequences
930/// only consider non-class types; for conversions that involve class
931/// types, use TryImplicitConversion. If a conversion exists, SCS will
932/// contain the standard conversion sequence required to perform this
933/// conversion and this routine will return true. Otherwise, this
934/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +0000935static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
936 bool InOverloadResolution,
937 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000938 QualType FromType = From->getType();
John McCall5c32be02010-08-24 20:38:10 +0000939
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000940 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000941 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000942 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000943 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000944 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000945 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000946
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000947 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000948 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000949 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +0000950 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000951 return false;
952
Mike Stump11289f42009-09-09 15:08:12 +0000953 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000954 }
955
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000956 // The first conversion can be an lvalue-to-rvalue conversion,
957 // array-to-pointer conversion, or function-to-pointer conversion
958 // (C++ 4p1).
959
John McCall5c32be02010-08-24 20:38:10 +0000960 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +0000961 DeclAccessPair AccessPair;
962 if (FunctionDecl *Fn
John McCall5c32be02010-08-24 20:38:10 +0000963 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
964 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +0000965 // We were able to resolve the address of the overloaded function,
966 // so we can convert to the type of that function.
967 FromType = Fn->getType();
968 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
969 if (!Method->isStatic()) {
970 Type *ClassType
John McCall5c32be02010-08-24 20:38:10 +0000971 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
972 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Douglas Gregor980fb162010-04-29 18:24:40 +0000973 }
974 }
975
976 // If the "from" expression takes the address of the overloaded
977 // function, update the type of the resulting expression accordingly.
978 if (FromType->getAs<FunctionType>())
979 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
John McCalle3027922010-08-25 11:45:40 +0000980 if (UnOp->getOpcode() == UO_AddrOf)
John McCall5c32be02010-08-24 20:38:10 +0000981 FromType = S.Context.getPointerType(FromType);
Douglas Gregor980fb162010-04-29 18:24:40 +0000982
983 // Check that we've computed the proper type after overload resolution.
John McCall5c32be02010-08-24 20:38:10 +0000984 assert(S.Context.hasSameType(FromType,
985 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +0000986 } else {
987 return false;
988 }
989 }
Mike Stump11289f42009-09-09 15:08:12 +0000990 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000991 // An lvalue (3.10) of a non-function, non-array type T can be
992 // converted to an rvalue.
John McCall5c32be02010-08-24 20:38:10 +0000993 Expr::isLvalueResult argIsLvalue = From->isLvalue(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +0000994 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregorcd695e52008-11-10 20:40:00 +0000995 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +0000996 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000997 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000998
999 // If T is a non-class type, the type of the rvalue is the
1000 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001001 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1002 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001003 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001004 } else if (FromType->isArrayType()) {
1005 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001006 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001007
1008 // An lvalue or rvalue of type "array of N T" or "array of unknown
1009 // bound of T" can be converted to an rvalue of type "pointer to
1010 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001011 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001012
John McCall5c32be02010-08-24 20:38:10 +00001013 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001014 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001015 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001016
1017 // For the purpose of ranking in overload resolution
1018 // (13.3.3.1.1), this conversion is considered an
1019 // array-to-pointer conversion followed by a qualification
1020 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001021 SCS.Second = ICK_Identity;
1022 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001023 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001024 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001025 }
Mike Stump12b8ce12009-08-04 21:02:39 +00001026 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
1027 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001028 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001029
1030 // An lvalue of function type T can be converted to an rvalue of
1031 // type "pointer to T." The result is a pointer to the
1032 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001033 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001034 } else {
1035 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001036 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001037 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001038 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001039
1040 // The second conversion can be an integral promotion, floating
1041 // point promotion, integral conversion, floating point conversion,
1042 // floating-integral conversion, pointer conversion,
1043 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001044 // For overloading in C, this can also be a "compatible-type"
1045 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001046 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001047 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001048 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001049 // The unqualified versions of the types are the same: there's no
1050 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001051 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001052 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001053 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001054 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001055 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001056 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001057 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001058 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001059 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001060 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001061 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001062 SCS.Second = ICK_Complex_Promotion;
1063 FromType = ToType.getUnqualifiedType();
Douglas Gregorb90df602010-06-16 00:17:44 +00001064 } else if (FromType->isIntegralOrEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001065 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001066 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001067 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001068 FromType = ToType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001069 } else if (FromType->isComplexType() && ToType->isComplexType()) {
1070 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001071 SCS.Second = ICK_Complex_Conversion;
1072 FromType = ToType.getUnqualifiedType();
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001073 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
1074 (ToType->isComplexType() && FromType->isArithmeticType())) {
1075 // Complex-real conversions (C99 6.3.1.7)
1076 SCS.Second = ICK_Complex_Real;
1077 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001078 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001079 // Floating point conversions (C++ 4.8).
1080 SCS.Second = ICK_Floating_Conversion;
1081 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001082 } else if ((FromType->isRealFloatingType() &&
John McCall5c32be02010-08-24 20:38:10 +00001083 ToType->isIntegralType(S.Context) && !ToType->isBooleanType()) ||
Douglas Gregorb90df602010-06-16 00:17:44 +00001084 (FromType->isIntegralOrEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001085 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001086 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001087 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001088 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001089 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1090 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001091 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001092 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001093 SCS.IncompatibleObjC = IncompatibleObjC;
John McCall5c32be02010-08-24 20:38:10 +00001094 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1095 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001096 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001097 SCS.Second = ICK_Pointer_Member;
Mike Stump12b8ce12009-08-04 21:02:39 +00001098 } else if (ToType->isBooleanType() &&
1099 (FromType->isArithmeticType() ||
1100 FromType->isEnumeralType() ||
Fariborz Jahanian88118852009-12-11 21:23:13 +00001101 FromType->isAnyPointerType() ||
Mike Stump12b8ce12009-08-04 21:02:39 +00001102 FromType->isBlockPointerType() ||
1103 FromType->isMemberPointerType() ||
Douglas Gregora3208f92010-06-22 23:41:02 +00001104 FromType->isNullPtrType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001105 // Boolean conversions (C++ 4.12).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001106 SCS.Second = ICK_Boolean_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001107 FromType = S.Context.BoolTy;
1108 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001109 SCS.Second = SecondICK;
1110 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001111 } else if (!S.getLangOptions().CPlusPlus &&
1112 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001113 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001114 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001115 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001116 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001117 // Treat a conversion that strips "noreturn" as an identity conversion.
1118 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001119 } else {
1120 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001121 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001122 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001123 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001124
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001125 QualType CanonFrom;
1126 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001127 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall5c32be02010-08-24 20:38:10 +00001128 if (S.IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001129 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001130 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001131 CanonFrom = S.Context.getCanonicalType(FromType);
1132 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001133 } else {
1134 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001135 SCS.Third = ICK_Identity;
1136
Mike Stump11289f42009-09-09 15:08:12 +00001137 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001138 // [...] Any difference in top-level cv-qualification is
1139 // subsumed by the initialization itself and does not constitute
1140 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001141 CanonFrom = S.Context.getCanonicalType(FromType);
1142 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001143 if (CanonFrom.getLocalUnqualifiedType()
1144 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001145 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1146 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001147 FromType = ToType;
1148 CanonFrom = CanonTo;
1149 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001150 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001151 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001152
1153 // If we have not converted the argument type to the parameter type,
1154 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001155 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001156 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001157
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001158 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001159}
1160
1161/// IsIntegralPromotion - Determines whether the conversion from the
1162/// expression From (whose potentially-adjusted type is FromType) to
1163/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1164/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001165bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001166 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001167 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001168 if (!To) {
1169 return false;
1170 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001171
1172 // An rvalue of type char, signed char, unsigned char, short int, or
1173 // unsigned short int can be converted to an rvalue of type int if
1174 // int can represent all the values of the source type; otherwise,
1175 // the source rvalue can be converted to an rvalue of type unsigned
1176 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001177 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1178 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001179 if (// We can promote any signed, promotable integer type to an int
1180 (FromType->isSignedIntegerType() ||
1181 // We can promote any unsigned integer type whose size is
1182 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001183 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001184 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001185 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001186 }
1187
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001188 return To->getKind() == BuiltinType::UInt;
1189 }
1190
1191 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
1192 // can be converted to an rvalue of the first of the following types
1193 // that can represent all the values of its underlying type: int,
1194 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall56774992009-12-09 09:09:27 +00001195
1196 // We pre-calculate the promotion type for enum types.
1197 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001198 if (ToType->isIntegerType() &&
1199 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001200 return Context.hasSameUnqualifiedType(ToType,
1201 FromEnumType->getDecl()->getPromotionType());
1202
1203 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001204 // Determine whether the type we're converting from is signed or
1205 // unsigned.
1206 bool FromIsSigned;
1207 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +00001208
1209 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1210 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001211
1212 // The types we'll try to promote to, in the appropriate
1213 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001214 QualType PromoteTypes[6] = {
1215 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001216 Context.LongTy, Context.UnsignedLongTy ,
1217 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001218 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001219 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001220 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1221 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001222 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001223 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1224 // We found the type that we can promote to. If this is the
1225 // type we wanted, we have a promotion. Otherwise, no
1226 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001227 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001228 }
1229 }
1230 }
1231
1232 // An rvalue for an integral bit-field (9.6) can be converted to an
1233 // rvalue of type int if int can represent all the values of the
1234 // bit-field; otherwise, it can be converted to unsigned int if
1235 // unsigned int can represent all the values of the bit-field. If
1236 // the bit-field is larger yet, no integral promotion applies to
1237 // it. If the bit-field has an enumerated type, it is treated as any
1238 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001239 // FIXME: We should delay checking of bit-fields until we actually perform the
1240 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001241 using llvm::APSInt;
1242 if (From)
1243 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001244 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001245 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001246 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1247 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1248 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001249
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001250 // Are we promoting to an int from a bitfield that fits in an int?
1251 if (BitWidth < ToSize ||
1252 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1253 return To->getKind() == BuiltinType::Int;
1254 }
Mike Stump11289f42009-09-09 15:08:12 +00001255
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001256 // Are we promoting to an unsigned int from an unsigned bitfield
1257 // that fits into an unsigned int?
1258 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1259 return To->getKind() == BuiltinType::UInt;
1260 }
Mike Stump11289f42009-09-09 15:08:12 +00001261
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001262 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001263 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001264 }
Mike Stump11289f42009-09-09 15:08:12 +00001265
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001266 // An rvalue of type bool can be converted to an rvalue of type int,
1267 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001268 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001269 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001270 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001271
1272 return false;
1273}
1274
1275/// IsFloatingPointPromotion - Determines whether the conversion from
1276/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1277/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001278bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001279 /// An rvalue of type float can be converted to an rvalue of type
1280 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001281 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1282 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001283 if (FromBuiltin->getKind() == BuiltinType::Float &&
1284 ToBuiltin->getKind() == BuiltinType::Double)
1285 return true;
1286
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001287 // C99 6.3.1.5p1:
1288 // When a float is promoted to double or long double, or a
1289 // double is promoted to long double [...].
1290 if (!getLangOptions().CPlusPlus &&
1291 (FromBuiltin->getKind() == BuiltinType::Float ||
1292 FromBuiltin->getKind() == BuiltinType::Double) &&
1293 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1294 return true;
1295 }
1296
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001297 return false;
1298}
1299
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001300/// \brief Determine if a conversion is a complex promotion.
1301///
1302/// A complex promotion is defined as a complex -> complex conversion
1303/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001304/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001305bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001306 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001307 if (!FromComplex)
1308 return false;
1309
John McCall9dd450b2009-09-21 23:43:11 +00001310 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001311 if (!ToComplex)
1312 return false;
1313
1314 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001315 ToComplex->getElementType()) ||
1316 IsIntegralPromotion(0, FromComplex->getElementType(),
1317 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001318}
1319
Douglas Gregor237f96c2008-11-26 23:31:11 +00001320/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1321/// the pointer type FromPtr to a pointer to type ToPointee, with the
1322/// same type qualifiers as FromPtr has on its pointee type. ToType,
1323/// if non-empty, will be a pointer to ToType that may or may not have
1324/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001325static QualType
1326BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001327 QualType ToPointee, QualType ToType,
1328 ASTContext &Context) {
1329 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1330 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001331 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001332
1333 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001334 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001335 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001336 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001337 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001338
1339 // Build a pointer to ToPointee. It has the right qualifiers
1340 // already.
1341 return Context.getPointerType(ToPointee);
1342 }
1343
1344 // Just build a canonical type that has the right qualifiers.
John McCall8ccfcb52009-09-24 19:53:00 +00001345 return Context.getPointerType(
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001346 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1347 Quals));
Douglas Gregor237f96c2008-11-26 23:31:11 +00001348}
1349
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001350/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1351/// the FromType, which is an objective-c pointer, to ToType, which may or may
1352/// not have the right set of qualifiers.
1353static QualType
1354BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1355 QualType ToType,
1356 ASTContext &Context) {
1357 QualType CanonFromType = Context.getCanonicalType(FromType);
1358 QualType CanonToType = Context.getCanonicalType(ToType);
1359 Qualifiers Quals = CanonFromType.getQualifiers();
1360
1361 // Exact qualifier match -> return the pointer type we're converting to.
1362 if (CanonToType.getLocalQualifiers() == Quals)
1363 return ToType;
1364
1365 // Just build a canonical type that has the right qualifiers.
1366 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1367}
1368
Mike Stump11289f42009-09-09 15:08:12 +00001369static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001370 bool InOverloadResolution,
1371 ASTContext &Context) {
1372 // Handle value-dependent integral null pointer constants correctly.
1373 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1374 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001375 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001376 return !InOverloadResolution;
1377
Douglas Gregor56751b52009-09-25 04:25:58 +00001378 return Expr->isNullPointerConstant(Context,
1379 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1380 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001381}
Mike Stump11289f42009-09-09 15:08:12 +00001382
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001383/// IsPointerConversion - Determines whether the conversion of the
1384/// expression From, which has the (possibly adjusted) type FromType,
1385/// can be converted to the type ToType via a pointer conversion (C++
1386/// 4.10). If so, returns true and places the converted type (that
1387/// might differ from ToType in its cv-qualifiers at some level) into
1388/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001389///
Douglas Gregora29dc052008-11-27 01:19:21 +00001390/// This routine also supports conversions to and from block pointers
1391/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1392/// pointers to interfaces. FIXME: Once we've determined the
1393/// appropriate overloading rules for Objective-C, we may want to
1394/// split the Objective-C checks into a different routine; however,
1395/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001396/// conversions, so for now they live here. IncompatibleObjC will be
1397/// set if the conversion is an allowed Objective-C conversion that
1398/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001399bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001400 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001401 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001402 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001403 IncompatibleObjC = false;
Douglas Gregora119f102008-12-19 19:13:09 +00001404 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1405 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001406
Mike Stump11289f42009-09-09 15:08:12 +00001407 // Conversion from a null pointer constant to any Objective-C pointer type.
1408 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001409 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001410 ConvertedType = ToType;
1411 return true;
1412 }
1413
Douglas Gregor231d1c62008-11-27 00:15:41 +00001414 // Blocks: Block pointers can be converted to void*.
1415 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001416 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001417 ConvertedType = ToType;
1418 return true;
1419 }
1420 // Blocks: A null pointer constant can be converted to a block
1421 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001422 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001423 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001424 ConvertedType = ToType;
1425 return true;
1426 }
1427
Sebastian Redl576fd422009-05-10 18:38:11 +00001428 // If the left-hand-side is nullptr_t, the right side can be a null
1429 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001430 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001431 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001432 ConvertedType = ToType;
1433 return true;
1434 }
1435
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001436 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001437 if (!ToTypePtr)
1438 return false;
1439
1440 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001441 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001442 ConvertedType = ToType;
1443 return true;
1444 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001445
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001446 // Beyond this point, both types need to be pointers
1447 // , including objective-c pointers.
1448 QualType ToPointeeType = ToTypePtr->getPointeeType();
1449 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1450 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1451 ToType, Context);
1452 return true;
1453
1454 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001455 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001456 if (!FromTypePtr)
1457 return false;
1458
1459 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001460
Douglas Gregorfb640862010-08-18 21:25:30 +00001461 // If the unqualified pointee types are the same, this can't be a
1462 // pointer conversion, so don't do all of the work below.
1463 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1464 return false;
1465
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001466 // An rvalue of type "pointer to cv T," where T is an object type,
1467 // can be converted to an rvalue of type "pointer to cv void" (C++
1468 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001469 if (FromPointeeType->isIncompleteOrObjectType() &&
1470 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001471 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001472 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001473 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001474 return true;
1475 }
1476
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001477 // When we're overloading in C, we allow a special kind of pointer
1478 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001479 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001480 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001481 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001482 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001483 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001484 return true;
1485 }
1486
Douglas Gregor5c407d92008-10-23 00:40:37 +00001487 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001488 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001489 // An rvalue of type "pointer to cv D," where D is a class type,
1490 // can be converted to an rvalue of type "pointer to cv B," where
1491 // B is a base class (clause 10) of D. If B is an inaccessible
1492 // (clause 11) or ambiguous (10.2) base class of D, a program that
1493 // necessitates this conversion is ill-formed. The result of the
1494 // conversion is a pointer to the base class sub-object of the
1495 // derived class object. The null pointer value is converted to
1496 // the null pointer value of the destination type.
1497 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001498 // Note that we do not check for ambiguity or inaccessibility
1499 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001500 if (getLangOptions().CPlusPlus &&
1501 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001502 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001503 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001504 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001505 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001506 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001507 ToType, Context);
1508 return true;
1509 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001510
Douglas Gregora119f102008-12-19 19:13:09 +00001511 return false;
1512}
1513
1514/// isObjCPointerConversion - Determines whether this is an
1515/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1516/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001517bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001518 QualType& ConvertedType,
1519 bool &IncompatibleObjC) {
1520 if (!getLangOptions().ObjC1)
1521 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001522
Steve Naroff7cae42b2009-07-10 23:34:53 +00001523 // First, we handle all conversions on ObjC object pointer types.
John McCall9dd450b2009-09-21 23:43:11 +00001524 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001525 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001526 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001527
Steve Naroff7cae42b2009-07-10 23:34:53 +00001528 if (ToObjCPtr && FromObjCPtr) {
Steve Naroff1329fa02009-07-15 18:40:39 +00001529 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001530 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001531 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001532 ConvertedType = ToType;
1533 return true;
1534 }
1535 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001536 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001537 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001538 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001539 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001540 ConvertedType = ToType;
1541 return true;
1542 }
1543 // Objective C++: We're able to convert from a pointer to an
1544 // interface to a pointer to a different interface.
1545 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001546 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1547 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1548 if (getLangOptions().CPlusPlus && LHS && RHS &&
1549 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1550 FromObjCPtr->getPointeeType()))
1551 return false;
Steve Naroff7cae42b2009-07-10 23:34:53 +00001552 ConvertedType = ToType;
1553 return true;
1554 }
1555
1556 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1557 // Okay: this is some kind of implicit downcast of Objective-C
1558 // interfaces, which is permitted. However, we're going to
1559 // complain about it.
1560 IncompatibleObjC = true;
1561 ConvertedType = FromType;
1562 return true;
1563 }
Mike Stump11289f42009-09-09 15:08:12 +00001564 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001565 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001566 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001567 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001568 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001569 else if (const BlockPointerType *ToBlockPtr =
1570 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001571 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001572 // to a block pointer type.
1573 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1574 ConvertedType = ToType;
1575 return true;
1576 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001577 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001578 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001579 else if (FromType->getAs<BlockPointerType>() &&
1580 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1581 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001582 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001583 ConvertedType = ToType;
1584 return true;
1585 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001586 else
Douglas Gregora119f102008-12-19 19:13:09 +00001587 return false;
1588
Douglas Gregor033f56d2008-12-23 00:53:59 +00001589 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001590 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001591 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001592 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001593 FromPointeeType = FromBlockPtr->getPointeeType();
1594 else
Douglas Gregora119f102008-12-19 19:13:09 +00001595 return false;
1596
Douglas Gregora119f102008-12-19 19:13:09 +00001597 // If we have pointers to pointers, recursively check whether this
1598 // is an Objective-C conversion.
1599 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1600 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1601 IncompatibleObjC)) {
1602 // We always complain about this conversion.
1603 IncompatibleObjC = true;
1604 ConvertedType = ToType;
1605 return true;
1606 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001607 // Allow conversion of pointee being objective-c pointer to another one;
1608 // as in I* to id.
1609 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1610 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1611 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1612 IncompatibleObjC)) {
1613 ConvertedType = ToType;
1614 return true;
1615 }
1616
Douglas Gregor033f56d2008-12-23 00:53:59 +00001617 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001618 // differences in the argument and result types are in Objective-C
1619 // pointer conversions. If so, we permit the conversion (but
1620 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001621 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001622 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001623 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001624 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001625 if (FromFunctionType && ToFunctionType) {
1626 // If the function types are exactly the same, this isn't an
1627 // Objective-C pointer conversion.
1628 if (Context.getCanonicalType(FromPointeeType)
1629 == Context.getCanonicalType(ToPointeeType))
1630 return false;
1631
1632 // Perform the quick checks that will tell us whether these
1633 // function types are obviously different.
1634 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1635 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1636 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1637 return false;
1638
1639 bool HasObjCConversion = false;
1640 if (Context.getCanonicalType(FromFunctionType->getResultType())
1641 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1642 // Okay, the types match exactly. Nothing to do.
1643 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1644 ToFunctionType->getResultType(),
1645 ConvertedType, IncompatibleObjC)) {
1646 // Okay, we have an Objective-C pointer conversion.
1647 HasObjCConversion = true;
1648 } else {
1649 // Function types are too different. Abort.
1650 return false;
1651 }
Mike Stump11289f42009-09-09 15:08:12 +00001652
Douglas Gregora119f102008-12-19 19:13:09 +00001653 // Check argument types.
1654 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1655 ArgIdx != NumArgs; ++ArgIdx) {
1656 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1657 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1658 if (Context.getCanonicalType(FromArgType)
1659 == Context.getCanonicalType(ToArgType)) {
1660 // Okay, the types match exactly. Nothing to do.
1661 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1662 ConvertedType, IncompatibleObjC)) {
1663 // Okay, we have an Objective-C pointer conversion.
1664 HasObjCConversion = true;
1665 } else {
1666 // Argument types are too different. Abort.
1667 return false;
1668 }
1669 }
1670
1671 if (HasObjCConversion) {
1672 // We had an Objective-C conversion. Allow this pointer
1673 // conversion, but complain about it.
1674 ConvertedType = ToType;
1675 IncompatibleObjC = true;
1676 return true;
1677 }
1678 }
1679
Sebastian Redl72b597d2009-01-25 19:43:20 +00001680 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001681}
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001682
1683/// FunctionArgTypesAreEqual - This routine checks two function proto types
1684/// for equlity of their argument types. Caller has already checked that
1685/// they have same number of arguments. This routine assumes that Objective-C
1686/// pointer types which only differ in their protocol qualifiers are equal.
1687bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1688 FunctionProtoType* NewType){
1689 if (!getLangOptions().ObjC1)
1690 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1691 NewType->arg_type_begin());
1692
1693 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1694 N = NewType->arg_type_begin(),
1695 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1696 QualType ToType = (*O);
1697 QualType FromType = (*N);
1698 if (ToType != FromType) {
1699 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1700 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001701 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1702 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1703 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1704 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001705 continue;
1706 }
John McCall8b07ec22010-05-15 11:32:37 +00001707 else if (const ObjCObjectPointerType *PTTo =
1708 ToType->getAs<ObjCObjectPointerType>()) {
1709 if (const ObjCObjectPointerType *PTFr =
1710 FromType->getAs<ObjCObjectPointerType>())
1711 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1712 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001713 }
1714 return false;
1715 }
1716 }
1717 return true;
1718}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001719
Douglas Gregor39c16d42008-10-24 04:54:22 +00001720/// CheckPointerConversion - Check the pointer conversion from the
1721/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001722/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001723/// conversions for which IsPointerConversion has already returned
1724/// true. It returns true and produces a diagnostic if there was an
1725/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001726bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00001727 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001728 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001729 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001730 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001731 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001732
Douglas Gregor4038cf42010-06-08 17:35:15 +00001733 if (CXXBoolLiteralExpr* LitBool
1734 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001735 if (!IsCStyleOrFunctionalCast && LitBool->getValue() == false)
Douglas Gregor4038cf42010-06-08 17:35:15 +00001736 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1737 << ToType;
1738
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001739 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1740 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001741 QualType FromPointeeType = FromPtrType->getPointeeType(),
1742 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001743
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001744 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1745 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001746 // We must have a derived-to-base conversion. Check an
1747 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001748 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1749 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001750 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001751 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001752 return true;
1753
1754 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00001755 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001756 }
1757 }
Mike Stump11289f42009-09-09 15:08:12 +00001758 if (const ObjCObjectPointerType *FromPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001759 FromType->getAs<ObjCObjectPointerType>())
Mike Stump11289f42009-09-09 15:08:12 +00001760 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001761 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001762 // Objective-C++ conversions are always okay.
1763 // FIXME: We should have a different class of conversions for the
1764 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001765 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001766 return false;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001767
Steve Naroff7cae42b2009-07-10 23:34:53 +00001768 }
Douglas Gregor39c16d42008-10-24 04:54:22 +00001769 return false;
1770}
1771
Sebastian Redl72b597d2009-01-25 19:43:20 +00001772/// IsMemberPointerConversion - Determines whether the conversion of the
1773/// expression From, which has the (possibly adjusted) type FromType, can be
1774/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1775/// If so, returns true and places the converted type (that might differ from
1776/// ToType in its cv-qualifiers at some level) into ConvertedType.
1777bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001778 QualType ToType,
1779 bool InOverloadResolution,
1780 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001781 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001782 if (!ToTypePtr)
1783 return false;
1784
1785 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001786 if (From->isNullPointerConstant(Context,
1787 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1788 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001789 ConvertedType = ToType;
1790 return true;
1791 }
1792
1793 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001794 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001795 if (!FromTypePtr)
1796 return false;
1797
1798 // A pointer to member of B can be converted to a pointer to member of D,
1799 // where D is derived from B (C++ 4.11p2).
1800 QualType FromClass(FromTypePtr->getClass(), 0);
1801 QualType ToClass(ToTypePtr->getClass(), 0);
1802 // FIXME: What happens when these are dependent? Is this function even called?
1803
1804 if (IsDerivedFrom(ToClass, FromClass)) {
1805 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1806 ToClass.getTypePtr());
1807 return true;
1808 }
1809
1810 return false;
1811}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001812
Sebastian Redl72b597d2009-01-25 19:43:20 +00001813/// CheckMemberPointerConversion - Check the member pointer conversion from the
1814/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001815/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001816/// for which IsMemberPointerConversion has already returned true. It returns
1817/// true and produces a diagnostic if there was an error, or returns false
1818/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001819bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00001820 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001821 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001822 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001823 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001824 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001825 if (!FromPtrType) {
1826 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001827 assert(From->isNullPointerConstant(Context,
1828 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001829 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00001830 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001831 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001832 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001833
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001834 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001835 assert(ToPtrType && "No member pointer cast has a target type "
1836 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001837
Sebastian Redled8f2002009-01-28 18:33:18 +00001838 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1839 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001840
Sebastian Redled8f2002009-01-28 18:33:18 +00001841 // FIXME: What about dependent types?
1842 assert(FromClass->isRecordType() && "Pointer into non-class.");
1843 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001844
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001845 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001846 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001847 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1848 assert(DerivationOkay &&
1849 "Should not have been called if derivation isn't OK.");
1850 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001851
Sebastian Redled8f2002009-01-28 18:33:18 +00001852 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1853 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001854 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1855 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1856 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1857 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001858 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001859
Douglas Gregor89ee6822009-02-28 01:32:25 +00001860 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001861 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1862 << FromClass << ToClass << QualType(VBase, 0)
1863 << From->getSourceRange();
1864 return true;
1865 }
1866
John McCall5b0829a2010-02-10 09:31:12 +00001867 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001868 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1869 Paths.front(),
1870 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001871
Anders Carlssond7923c62009-08-22 23:33:40 +00001872 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001873 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001874 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001875 return false;
1876}
1877
Douglas Gregor9a657932008-10-21 23:43:52 +00001878/// IsQualificationConversion - Determines whether the conversion from
1879/// an rvalue of type FromType to ToType is a qualification conversion
1880/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001881bool
1882Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001883 FromType = Context.getCanonicalType(FromType);
1884 ToType = Context.getCanonicalType(ToType);
1885
1886 // If FromType and ToType are the same type, this is not a
1887 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001888 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001889 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001890
Douglas Gregor9a657932008-10-21 23:43:52 +00001891 // (C++ 4.4p4):
1892 // A conversion can add cv-qualifiers at levels other than the first
1893 // in multi-level pointers, subject to the following rules: [...]
1894 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001895 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001896 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001897 // Within each iteration of the loop, we check the qualifiers to
1898 // determine if this still looks like a qualification
1899 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001900 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001901 // until there are no more pointers or pointers-to-members left to
1902 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001903 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001904
1905 // -- for every j > 0, if const is in cv 1,j then const is in cv
1906 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001907 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001908 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001909
Douglas Gregor9a657932008-10-21 23:43:52 +00001910 // -- if the cv 1,j and cv 2,j are different, then const is in
1911 // every cv for 0 < k < j.
1912 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001913 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001914 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001915
Douglas Gregor9a657932008-10-21 23:43:52 +00001916 // Keep track of whether all prior cv-qualifiers in the "to" type
1917 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00001918 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00001919 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001920 }
Douglas Gregor9a657932008-10-21 23:43:52 +00001921
1922 // We are left with FromType and ToType being the pointee types
1923 // after unwrapping the original FromType and ToType the same number
1924 // of types. If we unwrapped any pointers, and if FromType and
1925 // ToType have the same unqualified type (since we checked
1926 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001927 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00001928}
1929
Douglas Gregor576e98c2009-01-30 23:27:23 +00001930/// Determines whether there is a user-defined conversion sequence
1931/// (C++ [over.ics.user]) that converts expression From to the type
1932/// ToType. If such a conversion exists, User will contain the
1933/// user-defined conversion sequence that performs such a conversion
1934/// and this routine will return true. Otherwise, this routine returns
1935/// false and User is unspecified.
1936///
Douglas Gregor576e98c2009-01-30 23:27:23 +00001937/// \param AllowExplicit true if the conversion should consider C++0x
1938/// "explicit" conversion functions as well as non-explicit conversion
1939/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00001940static OverloadingResult
1941IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
1942 UserDefinedConversionSequence& User,
1943 OverloadCandidateSet& CandidateSet,
1944 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001945 // Whether we will only visit constructors.
1946 bool ConstructorsOnly = false;
1947
1948 // If the type we are conversion to is a class type, enumerate its
1949 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001950 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00001951 // C++ [over.match.ctor]p1:
1952 // When objects of class type are direct-initialized (8.5), or
1953 // copy-initialized from an expression of the same or a
1954 // derived class type (8.5), overload resolution selects the
1955 // constructor. [...] For copy-initialization, the candidate
1956 // functions are all the converting constructors (12.3.1) of
1957 // that class. The argument list is the expression-list within
1958 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00001959 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00001960 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00001961 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00001962 ConstructorsOnly = true;
1963
John McCall5c32be02010-08-24 20:38:10 +00001964 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag())) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00001965 // We're not going to find any constructors.
1966 } else if (CXXRecordDecl *ToRecordDecl
1967 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00001968 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00001969 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00001970 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00001971 NamedDecl *D = *Con;
1972 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1973
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001974 // Find the constructor (which may be a template).
1975 CXXConstructorDecl *Constructor = 0;
1976 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00001977 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001978 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00001979 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001980 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1981 else
John McCalla0296f72010-03-19 07:35:19 +00001982 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00001983
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00001984 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00001985 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001986 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00001987 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
1988 /*ExplicitArgs*/ 0,
1989 &From, 1, CandidateSet,
1990 /*SuppressUserConversions=*/
1991 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001992 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00001993 // Allow one user-defined conversion when user specifies a
1994 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00001995 S.AddOverloadCandidate(Constructor, FoundDecl,
1996 &From, 1, CandidateSet,
1997 /*SuppressUserConversions=*/
1998 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00001999 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002000 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002001 }
2002 }
2003
Douglas Gregor5ab11652010-04-17 22:01:05 +00002004 // Enumerate conversion functions, if we're allowed to.
2005 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002006 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2007 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002008 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002009 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002010 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002011 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002012 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2013 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002014 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002015 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002016 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002017 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002018 DeclAccessPair FoundDecl = I.getPair();
2019 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002020 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2021 if (isa<UsingShadowDecl>(D))
2022 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2023
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002024 CXXConversionDecl *Conv;
2025 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002026 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2027 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002028 else
John McCallda4458e2010-03-31 01:36:47 +00002029 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002030
2031 if (AllowExplicit || !Conv->isExplicit()) {
2032 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002033 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2034 ActingContext, From, ToType,
2035 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002036 else
John McCall5c32be02010-08-24 20:38:10 +00002037 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2038 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002039 }
2040 }
2041 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002042 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002043
2044 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002045 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002046 case OR_Success:
2047 // Record the standard conversion we used and the conversion function.
2048 if (CXXConstructorDecl *Constructor
2049 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
2050 // C++ [over.ics.user]p1:
2051 // If the user-defined conversion is specified by a
2052 // constructor (12.3.1), the initial standard conversion
2053 // sequence converts the source type to the type required by
2054 // the argument of the constructor.
2055 //
2056 QualType ThisType = Constructor->getThisType(S.Context);
2057 if (Best->Conversions[0].isEllipsis())
2058 User.EllipsisConversion = true;
2059 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002060 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002061 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002062 }
John McCall5c32be02010-08-24 20:38:10 +00002063 User.ConversionFunction = Constructor;
2064 User.After.setAsIdentityConversion();
2065 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2066 User.After.setAllToTypes(ToType);
2067 return OR_Success;
2068 } else if (CXXConversionDecl *Conversion
2069 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2070 // C++ [over.ics.user]p1:
2071 //
2072 // [...] If the user-defined conversion is specified by a
2073 // conversion function (12.3.2), the initial standard
2074 // conversion sequence converts the source type to the
2075 // implicit object parameter of the conversion function.
2076 User.Before = Best->Conversions[0].Standard;
2077 User.ConversionFunction = Conversion;
2078 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002079
John McCall5c32be02010-08-24 20:38:10 +00002080 // C++ [over.ics.user]p2:
2081 // The second standard conversion sequence converts the
2082 // result of the user-defined conversion to the target type
2083 // for the sequence. Since an implicit conversion sequence
2084 // is an initialization, the special rules for
2085 // initialization by user-defined conversion apply when
2086 // selecting the best user-defined conversion for a
2087 // user-defined conversion sequence (see 13.3.3 and
2088 // 13.3.3.1).
2089 User.After = Best->FinalConversion;
2090 return OR_Success;
2091 } else {
2092 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002093 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002094 }
2095
John McCall5c32be02010-08-24 20:38:10 +00002096 case OR_No_Viable_Function:
2097 return OR_No_Viable_Function;
2098 case OR_Deleted:
2099 // No conversion here! We're done.
2100 return OR_Deleted;
2101
2102 case OR_Ambiguous:
2103 return OR_Ambiguous;
2104 }
2105
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002106 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002107}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002108
2109bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002110Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002111 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002112 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002113 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002114 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002115 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002116 if (OvResult == OR_Ambiguous)
2117 Diag(From->getSourceRange().getBegin(),
2118 diag::err_typecheck_ambiguous_condition)
2119 << From->getType() << ToType << From->getSourceRange();
2120 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2121 Diag(From->getSourceRange().getBegin(),
2122 diag::err_typecheck_nonviable_condition)
2123 << From->getType() << ToType << From->getSourceRange();
2124 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002125 return false;
John McCall5c32be02010-08-24 20:38:10 +00002126 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002127 return true;
2128}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002129
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002130/// CompareImplicitConversionSequences - Compare two implicit
2131/// conversion sequences to determine whether one is better than the
2132/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002133static ImplicitConversionSequence::CompareKind
2134CompareImplicitConversionSequences(Sema &S,
2135 const ImplicitConversionSequence& ICS1,
2136 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002137{
2138 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2139 // conversion sequences (as defined in 13.3.3.1)
2140 // -- a standard conversion sequence (13.3.3.1.1) is a better
2141 // conversion sequence than a user-defined conversion sequence or
2142 // an ellipsis conversion sequence, and
2143 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2144 // conversion sequence than an ellipsis conversion sequence
2145 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002146 //
John McCall0d1da222010-01-12 00:44:57 +00002147 // C++0x [over.best.ics]p10:
2148 // For the purpose of ranking implicit conversion sequences as
2149 // described in 13.3.3.2, the ambiguous conversion sequence is
2150 // treated as a user-defined sequence that is indistinguishable
2151 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002152 if (ICS1.getKindRank() < ICS2.getKindRank())
2153 return ImplicitConversionSequence::Better;
2154 else if (ICS2.getKindRank() < ICS1.getKindRank())
2155 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002156
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002157 // The following checks require both conversion sequences to be of
2158 // the same kind.
2159 if (ICS1.getKind() != ICS2.getKind())
2160 return ImplicitConversionSequence::Indistinguishable;
2161
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002162 // Two implicit conversion sequences of the same form are
2163 // indistinguishable conversion sequences unless one of the
2164 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002165 if (ICS1.isStandard())
John McCall5c32be02010-08-24 20:38:10 +00002166 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002167 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002168 // User-defined conversion sequence U1 is a better conversion
2169 // sequence than another user-defined conversion sequence U2 if
2170 // they contain the same user-defined conversion function or
2171 // constructor and if the second standard conversion sequence of
2172 // U1 is better than the second standard conversion sequence of
2173 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002174 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002175 ICS2.UserDefined.ConversionFunction)
John McCall5c32be02010-08-24 20:38:10 +00002176 return CompareStandardConversionSequences(S,
2177 ICS1.UserDefined.After,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002178 ICS2.UserDefined.After);
2179 }
2180
2181 return ImplicitConversionSequence::Indistinguishable;
2182}
2183
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002184static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2185 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2186 Qualifiers Quals;
2187 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2188 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2189 }
2190
2191 return Context.hasSameUnqualifiedType(T1, T2);
2192}
2193
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002194// Per 13.3.3.2p3, compare the given standard conversion sequences to
2195// determine if one is a proper subset of the other.
2196static ImplicitConversionSequence::CompareKind
2197compareStandardConversionSubsets(ASTContext &Context,
2198 const StandardConversionSequence& SCS1,
2199 const StandardConversionSequence& SCS2) {
2200 ImplicitConversionSequence::CompareKind Result
2201 = ImplicitConversionSequence::Indistinguishable;
2202
Douglas Gregore87561a2010-05-23 22:10:15 +00002203 // the identity conversion sequence is considered to be a subsequence of
2204 // any non-identity conversion sequence
2205 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2206 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2207 return ImplicitConversionSequence::Better;
2208 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2209 return ImplicitConversionSequence::Worse;
2210 }
2211
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002212 if (SCS1.Second != SCS2.Second) {
2213 if (SCS1.Second == ICK_Identity)
2214 Result = ImplicitConversionSequence::Better;
2215 else if (SCS2.Second == ICK_Identity)
2216 Result = ImplicitConversionSequence::Worse;
2217 else
2218 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002219 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002220 return ImplicitConversionSequence::Indistinguishable;
2221
2222 if (SCS1.Third == SCS2.Third) {
2223 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2224 : ImplicitConversionSequence::Indistinguishable;
2225 }
2226
2227 if (SCS1.Third == ICK_Identity)
2228 return Result == ImplicitConversionSequence::Worse
2229 ? ImplicitConversionSequence::Indistinguishable
2230 : ImplicitConversionSequence::Better;
2231
2232 if (SCS2.Third == ICK_Identity)
2233 return Result == ImplicitConversionSequence::Better
2234 ? ImplicitConversionSequence::Indistinguishable
2235 : ImplicitConversionSequence::Worse;
2236
2237 return ImplicitConversionSequence::Indistinguishable;
2238}
2239
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002240/// CompareStandardConversionSequences - Compare two standard
2241/// conversion sequences to determine whether one is better than the
2242/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002243static ImplicitConversionSequence::CompareKind
2244CompareStandardConversionSequences(Sema &S,
2245 const StandardConversionSequence& SCS1,
2246 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002247{
2248 // Standard conversion sequence S1 is a better conversion sequence
2249 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2250
2251 // -- S1 is a proper subsequence of S2 (comparing the conversion
2252 // sequences in the canonical form defined by 13.3.3.1.1,
2253 // excluding any Lvalue Transformation; the identity conversion
2254 // sequence is considered to be a subsequence of any
2255 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002256 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002257 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002258 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002259
2260 // -- the rank of S1 is better than the rank of S2 (by the rules
2261 // defined below), or, if not that,
2262 ImplicitConversionRank Rank1 = SCS1.getRank();
2263 ImplicitConversionRank Rank2 = SCS2.getRank();
2264 if (Rank1 < Rank2)
2265 return ImplicitConversionSequence::Better;
2266 else if (Rank2 < Rank1)
2267 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002268
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002269 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2270 // are indistinguishable unless one of the following rules
2271 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002272
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002273 // A conversion that is not a conversion of a pointer, or
2274 // pointer to member, to bool is better than another conversion
2275 // that is such a conversion.
2276 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2277 return SCS2.isPointerConversionToBool()
2278 ? ImplicitConversionSequence::Better
2279 : ImplicitConversionSequence::Worse;
2280
Douglas Gregor5c407d92008-10-23 00:40:37 +00002281 // C++ [over.ics.rank]p4b2:
2282 //
2283 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002284 // conversion of B* to A* is better than conversion of B* to
2285 // void*, and conversion of A* to void* is better than conversion
2286 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002287 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002288 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002289 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002290 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002291 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2292 // Exactly one of the conversion sequences is a conversion to
2293 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002294 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2295 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002296 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2297 // Neither conversion sequence converts to a void pointer; compare
2298 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002299 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002300 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002301 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002302 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2303 // Both conversion sequences are conversions to void
2304 // pointers. Compare the source types to determine if there's an
2305 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002306 QualType FromType1 = SCS1.getFromType();
2307 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002308
2309 // Adjust the types we're converting from via the array-to-pointer
2310 // conversion, if we need to.
2311 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002312 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002313 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002314 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002315
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002316 QualType FromPointee1
2317 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2318 QualType FromPointee2
2319 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002320
John McCall5c32be02010-08-24 20:38:10 +00002321 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002322 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002323 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002324 return ImplicitConversionSequence::Worse;
2325
2326 // Objective-C++: If one interface is more specific than the
2327 // other, it is the better one.
John McCall8b07ec22010-05-15 11:32:37 +00002328 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2329 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002330 if (FromIface1 && FromIface1) {
John McCall5c32be02010-08-24 20:38:10 +00002331 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002332 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002333 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002334 return ImplicitConversionSequence::Worse;
2335 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002336 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002337
2338 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2339 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002340 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00002341 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002342 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002343
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002344 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00002345 // C++0x [over.ics.rank]p3b4:
2346 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2347 // implicit object parameter of a non-static member function declared
2348 // without a ref-qualifier, and S1 binds an rvalue reference to an
2349 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00002350 // FIXME: We don't know if we're dealing with the implicit object parameter,
2351 // or if the member function in this case has a ref qualifier.
2352 // (Of course, we don't have ref qualifiers yet.)
2353 if (SCS1.RRefBinding != SCS2.RRefBinding)
2354 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2355 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00002356
2357 // C++ [over.ics.rank]p3b4:
2358 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2359 // which the references refer are the same type except for
2360 // top-level cv-qualifiers, and the type to which the reference
2361 // initialized by S2 refers is more cv-qualified than the type
2362 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002363 QualType T1 = SCS1.getToType(2);
2364 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002365 T1 = S.Context.getCanonicalType(T1);
2366 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002367 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002368 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2369 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002370 if (UnqualT1 == UnqualT2) {
2371 // If the type is an array type, promote the element qualifiers to the type
2372 // for comparison.
2373 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002374 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002375 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002376 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002377 if (T2.isMoreQualifiedThan(T1))
2378 return ImplicitConversionSequence::Better;
2379 else if (T1.isMoreQualifiedThan(T2))
2380 return ImplicitConversionSequence::Worse;
2381 }
2382 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002383
2384 return ImplicitConversionSequence::Indistinguishable;
2385}
2386
2387/// CompareQualificationConversions - Compares two standard conversion
2388/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002389/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2390ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002391CompareQualificationConversions(Sema &S,
2392 const StandardConversionSequence& SCS1,
2393 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002394 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002395 // -- S1 and S2 differ only in their qualification conversion and
2396 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2397 // cv-qualification signature of type T1 is a proper subset of
2398 // the cv-qualification signature of type T2, and S1 is not the
2399 // deprecated string literal array-to-pointer conversion (4.2).
2400 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2401 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2402 return ImplicitConversionSequence::Indistinguishable;
2403
2404 // FIXME: the example in the standard doesn't use a qualification
2405 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002406 QualType T1 = SCS1.getToType(2);
2407 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002408 T1 = S.Context.getCanonicalType(T1);
2409 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002410 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002411 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2412 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002413
2414 // If the types are the same, we won't learn anything by unwrapped
2415 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002416 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002417 return ImplicitConversionSequence::Indistinguishable;
2418
Chandler Carruth607f38e2009-12-29 07:16:59 +00002419 // If the type is an array type, promote the element qualifiers to the type
2420 // for comparison.
2421 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002422 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002423 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002424 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002425
Mike Stump11289f42009-09-09 15:08:12 +00002426 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002427 = ImplicitConversionSequence::Indistinguishable;
John McCall5c32be02010-08-24 20:38:10 +00002428 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002429 // Within each iteration of the loop, we check the qualifiers to
2430 // determine if this still looks like a qualification
2431 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002432 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002433 // until there are no more pointers or pointers-to-members left
2434 // to unwrap. This essentially mimics what
2435 // IsQualificationConversion does, but here we're checking for a
2436 // strict subset of qualifiers.
2437 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2438 // The qualifiers are the same, so this doesn't tell us anything
2439 // about how the sequences rank.
2440 ;
2441 else if (T2.isMoreQualifiedThan(T1)) {
2442 // T1 has fewer qualifiers, so it could be the better sequence.
2443 if (Result == ImplicitConversionSequence::Worse)
2444 // Neither has qualifiers that are a subset of the other's
2445 // qualifiers.
2446 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002447
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002448 Result = ImplicitConversionSequence::Better;
2449 } else if (T1.isMoreQualifiedThan(T2)) {
2450 // T2 has fewer qualifiers, so it could be the better sequence.
2451 if (Result == ImplicitConversionSequence::Better)
2452 // Neither has qualifiers that are a subset of the other's
2453 // qualifiers.
2454 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002455
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002456 Result = ImplicitConversionSequence::Worse;
2457 } else {
2458 // Qualifiers are disjoint.
2459 return ImplicitConversionSequence::Indistinguishable;
2460 }
2461
2462 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00002463 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002464 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002465 }
2466
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002467 // Check that the winning standard conversion sequence isn't using
2468 // the deprecated string literal array to pointer conversion.
2469 switch (Result) {
2470 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002471 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002472 Result = ImplicitConversionSequence::Indistinguishable;
2473 break;
2474
2475 case ImplicitConversionSequence::Indistinguishable:
2476 break;
2477
2478 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002479 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002480 Result = ImplicitConversionSequence::Indistinguishable;
2481 break;
2482 }
2483
2484 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002485}
2486
Douglas Gregor5c407d92008-10-23 00:40:37 +00002487/// CompareDerivedToBaseConversions - Compares two standard conversion
2488/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002489/// various kinds of derived-to-base conversions (C++
2490/// [over.ics.rank]p4b3). As part of these checks, we also look at
2491/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002492ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002493CompareDerivedToBaseConversions(Sema &S,
2494 const StandardConversionSequence& SCS1,
2495 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002496 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002497 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002498 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002499 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002500
2501 // Adjust the types we're converting from via the array-to-pointer
2502 // conversion, if we need to.
2503 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002504 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002505 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002506 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002507
2508 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00002509 FromType1 = S.Context.getCanonicalType(FromType1);
2510 ToType1 = S.Context.getCanonicalType(ToType1);
2511 FromType2 = S.Context.getCanonicalType(FromType2);
2512 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002513
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002514 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002515 //
2516 // If class B is derived directly or indirectly from class A and
2517 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002518 //
2519 // For Objective-C, we let A, B, and C also be Objective-C
2520 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002521
2522 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002523 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002524 SCS2.Second == ICK_Pointer_Conversion &&
2525 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2526 FromType1->isPointerType() && FromType2->isPointerType() &&
2527 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002528 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002529 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002530 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002531 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002532 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002533 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002534 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002535 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002536
John McCall8b07ec22010-05-15 11:32:37 +00002537 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2538 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2539 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2540 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002541
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002542 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002543 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002544 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002545 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002546 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002547 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002548
2549 if (ToIface1 && ToIface2) {
John McCall5c32be02010-08-24 20:38:10 +00002550 if (S.Context.canAssignObjCInterfaces(ToIface2, ToIface1))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002551 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002552 else if (S.Context.canAssignObjCInterfaces(ToIface1, ToIface2))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002553 return ImplicitConversionSequence::Worse;
2554 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002555 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002556
2557 // -- conversion of B* to A* is better than conversion of C* to A*,
2558 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002559 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002560 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002561 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002562 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002563
Douglas Gregor237f96c2008-11-26 23:31:11 +00002564 if (FromIface1 && FromIface2) {
John McCall5c32be02010-08-24 20:38:10 +00002565 if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002566 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002567 else if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002568 return ImplicitConversionSequence::Worse;
2569 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002570 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002571 }
2572
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002573 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002574 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2575 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2576 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2577 const MemberPointerType * FromMemPointer1 =
2578 FromType1->getAs<MemberPointerType>();
2579 const MemberPointerType * ToMemPointer1 =
2580 ToType1->getAs<MemberPointerType>();
2581 const MemberPointerType * FromMemPointer2 =
2582 FromType2->getAs<MemberPointerType>();
2583 const MemberPointerType * ToMemPointer2 =
2584 ToType2->getAs<MemberPointerType>();
2585 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2586 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2587 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2588 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2589 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2590 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2591 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2592 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002593 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002594 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002595 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002596 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00002597 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002598 return ImplicitConversionSequence::Better;
2599 }
2600 // conversion of B::* to C::* is better than conversion of A::* to C::*
2601 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002602 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002603 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002604 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002605 return ImplicitConversionSequence::Worse;
2606 }
2607 }
2608
Douglas Gregor5ab11652010-04-17 22:01:05 +00002609 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002610 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002611 // -- binding of an expression of type C to a reference of type
2612 // B& is better than binding an expression of type C to a
2613 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002614 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2615 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2616 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002617 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002618 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002619 return ImplicitConversionSequence::Worse;
2620 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002621
Douglas Gregor2fe98832008-11-03 19:09:14 +00002622 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002623 // -- binding of an expression of type B to a reference of type
2624 // A& is better than binding an expression of type C to a
2625 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002626 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2627 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2628 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002629 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002630 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002631 return ImplicitConversionSequence::Worse;
2632 }
2633 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002634
Douglas Gregor5c407d92008-10-23 00:40:37 +00002635 return ImplicitConversionSequence::Indistinguishable;
2636}
2637
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002638/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2639/// determine whether they are reference-related,
2640/// reference-compatible, reference-compatible with added
2641/// qualification, or incompatible, for use in C++ initialization by
2642/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2643/// type, and the first type (T1) is the pointee type of the reference
2644/// type being initialized.
2645Sema::ReferenceCompareResult
2646Sema::CompareReferenceRelationship(SourceLocation Loc,
2647 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002648 bool &DerivedToBase,
2649 bool &ObjCConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002650 assert(!OrigT1->isReferenceType() &&
2651 "T1 must be the pointee type of the reference type");
2652 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2653
2654 QualType T1 = Context.getCanonicalType(OrigT1);
2655 QualType T2 = Context.getCanonicalType(OrigT2);
2656 Qualifiers T1Quals, T2Quals;
2657 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2658 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2659
2660 // C++ [dcl.init.ref]p4:
2661 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2662 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2663 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002664 DerivedToBase = false;
2665 ObjCConversion = false;
2666 if (UnqualT1 == UnqualT2) {
2667 // Nothing to do.
2668 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002669 IsDerivedFrom(UnqualT2, UnqualT1))
2670 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002671 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2672 UnqualT2->isObjCObjectOrInterfaceType() &&
2673 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2674 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002675 else
2676 return Ref_Incompatible;
2677
2678 // At this point, we know that T1 and T2 are reference-related (at
2679 // least).
2680
2681 // If the type is an array type, promote the element qualifiers to the type
2682 // for comparison.
2683 if (isa<ArrayType>(T1) && T1Quals)
2684 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2685 if (isa<ArrayType>(T2) && T2Quals)
2686 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2687
2688 // C++ [dcl.init.ref]p4:
2689 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2690 // reference-related to T2 and cv1 is the same cv-qualification
2691 // as, or greater cv-qualification than, cv2. For purposes of
2692 // overload resolution, cases for which cv1 is greater
2693 // cv-qualification than cv2 are identified as
2694 // reference-compatible with added qualification (see 13.3.3.2).
2695 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2696 return Ref_Compatible;
2697 else if (T1.isMoreQualifiedThan(T2))
2698 return Ref_Compatible_With_Added_Qualification;
2699 else
2700 return Ref_Related;
2701}
2702
Douglas Gregor836a7e82010-08-11 02:15:33 +00002703/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00002704/// with DeclType. Return true if something definite is found.
2705static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00002706FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2707 QualType DeclType, SourceLocation DeclLoc,
2708 Expr *Init, QualType T2, bool AllowRvalues,
2709 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002710 assert(T2->isRecordType() && "Can only find conversions of record types.");
2711 CXXRecordDecl *T2RecordDecl
2712 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2713
Douglas Gregor836a7e82010-08-11 02:15:33 +00002714 QualType ToType
2715 = AllowRvalues? DeclType->getAs<ReferenceType>()->getPointeeType()
2716 : DeclType;
2717
Sebastian Redld92badf2010-06-30 18:13:39 +00002718 OverloadCandidateSet CandidateSet(DeclLoc);
2719 const UnresolvedSetImpl *Conversions
2720 = T2RecordDecl->getVisibleConversionFunctions();
2721 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2722 E = Conversions->end(); I != E; ++I) {
2723 NamedDecl *D = *I;
2724 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2725 if (isa<UsingShadowDecl>(D))
2726 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2727
2728 FunctionTemplateDecl *ConvTemplate
2729 = dyn_cast<FunctionTemplateDecl>(D);
2730 CXXConversionDecl *Conv;
2731 if (ConvTemplate)
2732 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2733 else
2734 Conv = cast<CXXConversionDecl>(D);
2735
Douglas Gregor836a7e82010-08-11 02:15:33 +00002736 // If this is an explicit conversion, and we're not allowed to consider
2737 // explicit conversions, skip it.
2738 if (!AllowExplicit && Conv->isExplicit())
2739 continue;
2740
2741 if (AllowRvalues) {
2742 bool DerivedToBase = false;
2743 bool ObjCConversion = false;
2744 if (!ConvTemplate &&
2745 S.CompareReferenceRelationship(DeclLoc,
2746 Conv->getConversionType().getNonReferenceType().getUnqualifiedType(),
2747 DeclType.getNonReferenceType().getUnqualifiedType(),
2748 DerivedToBase, ObjCConversion)
2749 == Sema::Ref_Incompatible)
2750 continue;
2751 } else {
2752 // If the conversion function doesn't return a reference type,
2753 // it can't be considered for this conversion. An rvalue reference
2754 // is only acceptable if its referencee is a function type.
2755
2756 const ReferenceType *RefType =
2757 Conv->getConversionType()->getAs<ReferenceType>();
2758 if (!RefType ||
2759 (!RefType->isLValueReferenceType() &&
2760 !RefType->getPointeeType()->isFunctionType()))
2761 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00002762 }
Douglas Gregor836a7e82010-08-11 02:15:33 +00002763
2764 if (ConvTemplate)
2765 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2766 Init, ToType, CandidateSet);
2767 else
2768 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2769 ToType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00002770 }
2771
2772 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002773 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002774 case OR_Success:
2775 // C++ [over.ics.ref]p1:
2776 //
2777 // [...] If the parameter binds directly to the result of
2778 // applying a conversion function to the argument
2779 // expression, the implicit conversion sequence is a
2780 // user-defined conversion sequence (13.3.3.1.2), with the
2781 // second standard conversion sequence either an identity
2782 // conversion or, if the conversion function returns an
2783 // entity of a type that is a derived class of the parameter
2784 // type, a derived-to-base Conversion.
2785 if (!Best->FinalConversion.DirectBinding)
2786 return false;
2787
2788 ICS.setUserDefined();
2789 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2790 ICS.UserDefined.After = Best->FinalConversion;
2791 ICS.UserDefined.ConversionFunction = Best->Function;
2792 ICS.UserDefined.EllipsisConversion = false;
2793 assert(ICS.UserDefined.After.ReferenceBinding &&
2794 ICS.UserDefined.After.DirectBinding &&
2795 "Expected a direct reference binding!");
2796 return true;
2797
2798 case OR_Ambiguous:
2799 ICS.setAmbiguous();
2800 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2801 Cand != CandidateSet.end(); ++Cand)
2802 if (Cand->Viable)
2803 ICS.Ambiguous.addConversion(Cand->Function);
2804 return true;
2805
2806 case OR_No_Viable_Function:
2807 case OR_Deleted:
2808 // There was no suitable conversion, or we found a deleted
2809 // conversion; continue with other checks.
2810 return false;
2811 }
Eric Christopheraba9fb22010-06-30 18:36:32 +00002812
2813 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002814}
2815
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002816/// \brief Compute an implicit conversion sequence for reference
2817/// initialization.
2818static ImplicitConversionSequence
2819TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2820 SourceLocation DeclLoc,
2821 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002822 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002823 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2824
2825 // Most paths end in a failed conversion.
2826 ImplicitConversionSequence ICS;
2827 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2828
2829 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2830 QualType T2 = Init->getType();
2831
2832 // If the initializer is the address of an overloaded function, try
2833 // to resolve the overloaded function. If all goes well, T2 is the
2834 // type of the resulting function.
2835 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2836 DeclAccessPair Found;
2837 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2838 false, Found))
2839 T2 = Fn->getType();
2840 }
2841
2842 // Compute some basic properties of the types and the initializer.
2843 bool isRValRef = DeclType->isRValueReferenceType();
2844 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002845 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002846 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002847 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002848 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
2849 ObjCConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002850
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002851
Sebastian Redld92badf2010-06-30 18:13:39 +00002852 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00002853 // A reference to type "cv1 T1" is initialized by an expression
2854 // of type "cv2 T2" as follows:
2855
Sebastian Redld92badf2010-06-30 18:13:39 +00002856 // -- If reference is an lvalue reference and the initializer expression
2857 // The next bullet point (T1 is a function) is pretty much equivalent to this
2858 // one, so it's handled here.
2859 if (!isRValRef || T1->isFunctionType()) {
2860 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2861 // reference-compatible with "cv2 T2," or
2862 //
2863 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2864 if (InitCategory.isLValue() &&
2865 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002866 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00002867 // When a parameter of reference type binds directly (8.5.3)
2868 // to an argument expression, the implicit conversion sequence
2869 // is the identity conversion, unless the argument expression
2870 // has a type that is a derived class of the parameter type,
2871 // in which case the implicit conversion sequence is a
2872 // derived-to-base Conversion (13.3.3.1).
2873 ICS.setStandard();
2874 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002875 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2876 : ObjCConversion? ICK_Compatible_Conversion
2877 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00002878 ICS.Standard.Third = ICK_Identity;
2879 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2880 ICS.Standard.setToType(0, T2);
2881 ICS.Standard.setToType(1, T1);
2882 ICS.Standard.setToType(2, T1);
2883 ICS.Standard.ReferenceBinding = true;
2884 ICS.Standard.DirectBinding = true;
2885 ICS.Standard.RRefBinding = isRValRef;
2886 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002887
Sebastian Redld92badf2010-06-30 18:13:39 +00002888 // Nothing more to do: the inaccessibility/ambiguity check for
2889 // derived-to-base conversions is suppressed when we're
2890 // computing the implicit conversion sequence (C++
2891 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002892 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00002893 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002894
Sebastian Redld92badf2010-06-30 18:13:39 +00002895 // -- has a class type (i.e., T2 is a class type), where T1 is
2896 // not reference-related to T2, and can be implicitly
2897 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2898 // is reference-compatible with "cv3 T3" 92) (this
2899 // conversion is selected by enumerating the applicable
2900 // conversion functions (13.3.1.6) and choosing the best
2901 // one through overload resolution (13.3)),
2902 if (!SuppressUserConversions && T2->isRecordType() &&
2903 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2904 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00002905 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2906 Init, T2, /*AllowRvalues=*/false,
2907 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00002908 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002909 }
2910 }
2911
Sebastian Redld92badf2010-06-30 18:13:39 +00002912 // -- Otherwise, the reference shall be an lvalue reference to a
2913 // non-volatile const type (i.e., cv1 shall be const), or the reference
2914 // shall be an rvalue reference and the initializer expression shall be
2915 // an rvalue or have a function type.
Douglas Gregor870f3742010-04-18 09:22:00 +00002916 //
2917 // We actually handle one oddity of C++ [over.ics.ref] at this
2918 // point, which is that, due to p2 (which short-circuits reference
2919 // binding by only attempting a simple conversion for non-direct
2920 // bindings) and p3's strange wording, we allow a const volatile
2921 // reference to bind to an rvalue. Hence the check for the presence
2922 // of "const" rather than checking for "const" being the only
2923 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00002924 // This is also the point where rvalue references and lvalue inits no longer
2925 // go together.
2926 if ((!isRValRef && !T1.isConstQualified()) ||
2927 (isRValRef && InitCategory.isLValue()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002928 return ICS;
2929
Sebastian Redld92badf2010-06-30 18:13:39 +00002930 // -- If T1 is a function type, then
2931 // -- if T2 is the same type as T1, the reference is bound to the
2932 // initializer expression lvalue;
2933 // -- if T2 is a class type and the initializer expression can be
2934 // implicitly converted to an lvalue of type T1 [...], the
2935 // reference is bound to the function lvalue that is the result
2936 // of the conversion;
2937 // This is the same as for the lvalue case above, so it was handled there.
2938 // -- otherwise, the program is ill-formed.
2939 // This is the one difference to the lvalue case.
2940 if (T1->isFunctionType())
2941 return ICS;
2942
2943 // -- Otherwise, if T2 is a class type and
Douglas Gregorf93df192010-04-18 08:46:23 +00002944 // -- the initializer expression is an rvalue and "cv1 T1"
2945 // is reference-compatible with "cv2 T2," or
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002946 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002947 // -- T1 is not reference-related to T2 and the initializer
2948 // expression can be implicitly converted to an rvalue
2949 // of type "cv3 T3" (this conversion is selected by
2950 // enumerating the applicable conversion functions
2951 // (13.3.1.6) and choosing the best one through overload
2952 // resolution (13.3)),
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002953 //
Douglas Gregorf93df192010-04-18 08:46:23 +00002954 // then the reference is bound to the initializer
2955 // expression rvalue in the first case and to the object
2956 // that is the result of the conversion in the second case
2957 // (or, in either case, to the appropriate base class
2958 // subobject of the object).
Douglas Gregor836a7e82010-08-11 02:15:33 +00002959 if (T2->isRecordType()) {
2960 // First case: "cv1 T1" is reference-compatible with "cv2 T2". This is a
2961 // direct binding in C++0x but not in C++03.
2962 if (InitCategory.isRValue() &&
2963 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2964 ICS.setStandard();
2965 ICS.Standard.First = ICK_Identity;
2966 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2967 : ObjCConversion? ICK_Compatible_Conversion
2968 : ICK_Identity;
2969 ICS.Standard.Third = ICK_Identity;
2970 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2971 ICS.Standard.setToType(0, T2);
2972 ICS.Standard.setToType(1, T1);
2973 ICS.Standard.setToType(2, T1);
2974 ICS.Standard.ReferenceBinding = true;
2975 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
2976 ICS.Standard.RRefBinding = isRValRef;
2977 ICS.Standard.CopyConstructor = 0;
2978 return ICS;
2979 }
2980
2981 // Second case: not reference-related.
2982 if (RefRelationship == Sema::Ref_Incompatible &&
2983 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2984 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2985 Init, T2, /*AllowRvalues=*/true,
2986 AllowExplicit))
2987 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002988 }
Douglas Gregor836a7e82010-08-11 02:15:33 +00002989
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002990 // -- Otherwise, a temporary of type "cv1 T1" is created and
2991 // initialized from the initializer expression using the
2992 // rules for a non-reference copy initialization (8.5). The
2993 // reference is then bound to the temporary. If T1 is
2994 // reference-related to T2, cv1 must be the same
2995 // cv-qualification as, or greater cv-qualification than,
2996 // cv2; otherwise, the program is ill-formed.
2997 if (RefRelationship == Sema::Ref_Related) {
2998 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2999 // we would be reference-compatible or reference-compatible with
3000 // added qualification. But that wasn't the case, so the reference
3001 // initialization fails.
3002 return ICS;
3003 }
3004
3005 // If at least one of the types is a class type, the types are not
3006 // related, and we aren't allowed any user conversions, the
3007 // reference binding fails. This case is important for breaking
3008 // recursion, since TryImplicitConversion below will attempt to
3009 // create a temporary through the use of a copy constructor.
3010 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3011 (T1->isRecordType() || T2->isRecordType()))
3012 return ICS;
3013
3014 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003015 // When a parameter of reference type is not bound directly to
3016 // an argument expression, the conversion sequence is the one
3017 // required to convert the argument expression to the
3018 // underlying type of the reference according to
3019 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3020 // to copy-initializing a temporary of the underlying type with
3021 // the argument expression. Any difference in top-level
3022 // cv-qualification is subsumed by the initialization itself
3023 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003024 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3025 /*AllowExplicit=*/false,
3026 /*InOverloadResolution=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003027
3028 // Of course, that's still a reference binding.
3029 if (ICS.isStandard()) {
3030 ICS.Standard.ReferenceBinding = true;
3031 ICS.Standard.RRefBinding = isRValRef;
3032 } else if (ICS.isUserDefined()) {
3033 ICS.UserDefined.After.ReferenceBinding = true;
3034 ICS.UserDefined.After.RRefBinding = isRValRef;
3035 }
3036 return ICS;
3037}
3038
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003039/// TryCopyInitialization - Try to copy-initialize a value of type
3040/// ToType from the expression From. Return the implicit conversion
3041/// sequence required to pass this argument, which may be a bad
3042/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003043/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003044/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003045static ImplicitConversionSequence
3046TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00003047 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003048 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003049 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003050 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003051 /*FIXME:*/From->getLocStart(),
3052 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003053 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003054
John McCall5c32be02010-08-24 20:38:10 +00003055 return TryImplicitConversion(S, From, ToType,
3056 SuppressUserConversions,
3057 /*AllowExplicit=*/false,
3058 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003059}
3060
Douglas Gregor436424c2008-11-18 23:14:02 +00003061/// TryObjectArgumentInitialization - Try to initialize the object
3062/// parameter of the given member function (@c Method) from the
3063/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00003064static ImplicitConversionSequence
3065TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
3066 CXXMethodDecl *Method,
3067 CXXRecordDecl *ActingContext) {
3068 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003069 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3070 // const volatile object.
3071 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3072 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00003073 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003074
3075 // Set up the conversion sequence as a "bad" conversion, to allow us
3076 // to exit early.
3077 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003078
3079 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003080 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003081 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003082 FromType = PT->getPointeeType();
3083
3084 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003085
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003086 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00003087 // where X is the class of which the function is a member
3088 // (C++ [over.match.funcs]p4). However, when finding an implicit
3089 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00003090 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003091 // (C++ [over.match.funcs]p5). We perform a simplified version of
3092 // reference binding here, that allows class rvalues to bind to
3093 // non-constant references.
3094
3095 // First check the qualifiers. We don't care about lvalue-vs-rvalue
3096 // with the implicit object parameter (C++ [over.match.funcs]p5).
John McCall5c32be02010-08-24 20:38:10 +00003097 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003098 if (ImplicitParamType.getCVRQualifiers()
3099 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003100 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003101 ICS.setBad(BadConversionSequence::bad_qualifiers,
3102 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003103 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003104 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003105
3106 // Check that we have either the same type or a derived type. It
3107 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00003108 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003109 ImplicitConversionKind SecondKind;
3110 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3111 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00003112 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00003113 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003114 else {
John McCall65eb8792010-02-25 01:37:24 +00003115 ICS.setBad(BadConversionSequence::unrelated_class,
3116 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003117 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003118 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003119
3120 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003121 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003122 ICS.Standard.setAsIdentityConversion();
3123 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003124 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003125 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003126 ICS.Standard.ReferenceBinding = true;
3127 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00003128 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003129 return ICS;
3130}
3131
3132/// PerformObjectArgumentInitialization - Perform initialization of
3133/// the implicit object parameter for the given Method with the given
3134/// expression.
3135bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003136Sema::PerformObjectArgumentInitialization(Expr *&From,
3137 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003138 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003139 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003140 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003141 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003142 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003143
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003144 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003145 FromRecordType = PT->getPointeeType();
3146 DestType = Method->getThisType(Context);
3147 } else {
3148 FromRecordType = From->getType();
3149 DestType = ImplicitParamRecordType;
3150 }
3151
John McCall6e9f8f62009-12-03 04:06:58 +00003152 // Note that we always use the true parent context when performing
3153 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003154 ImplicitConversionSequence ICS
John McCall5c32be02010-08-24 20:38:10 +00003155 = TryObjectArgumentInitialization(*this, From->getType(), Method,
John McCall6e9f8f62009-12-03 04:06:58 +00003156 Method->getParent());
John McCall0d1da222010-01-12 00:44:57 +00003157 if (ICS.isBad())
Douglas Gregor436424c2008-11-18 23:14:02 +00003158 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003159 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003160 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00003161
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003162 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00003163 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00003164
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003165 if (!Context.hasSameType(From->getType(), DestType))
John McCalle3027922010-08-25 11:45:40 +00003166 ImpCastExprToType(From, DestType, CK_NoOp,
John McCall2536c6d2010-08-25 10:28:54 +00003167 From->getType()->isPointerType() ? VK_RValue : VK_LValue);
Douglas Gregor436424c2008-11-18 23:14:02 +00003168 return false;
3169}
3170
Douglas Gregor5fb53972009-01-14 15:45:31 +00003171/// TryContextuallyConvertToBool - Attempt to contextually convert the
3172/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00003173static ImplicitConversionSequence
3174TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003175 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00003176 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003177 // FIXME: Are these flags correct?
3178 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003179 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00003180 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003181}
3182
3183/// PerformContextuallyConvertToBool - Perform a contextual conversion
3184/// of the expression From to bool (C++0x [conv]p3).
3185bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
John McCall5c32be02010-08-24 20:38:10 +00003186 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00003187 if (!ICS.isBad())
3188 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003189
Fariborz Jahanian76197412009-11-18 18:26:29 +00003190 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003191 return Diag(From->getSourceRange().getBegin(),
3192 diag::err_typecheck_bool_condition)
3193 << From->getType() << From->getSourceRange();
3194 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003195}
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003196
3197/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3198/// expression From to 'id'.
John McCall5c32be02010-08-24 20:38:10 +00003199static ImplicitConversionSequence
3200TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3201 QualType Ty = S.Context.getObjCIdType();
3202 return TryImplicitConversion(S, From, Ty,
3203 // FIXME: Are these flags correct?
3204 /*SuppressUserConversions=*/false,
3205 /*AllowExplicit=*/true,
3206 /*InOverloadResolution=*/false);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003207}
John McCall5c32be02010-08-24 20:38:10 +00003208
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003209/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3210/// of the expression From to 'id'.
3211bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCall8b07ec22010-05-15 11:32:37 +00003212 QualType Ty = Context.getObjCIdType();
John McCall5c32be02010-08-24 20:38:10 +00003213 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003214 if (!ICS.isBad())
3215 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3216 return true;
3217}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003218
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003219/// \brief Attempt to convert the given expression to an integral or
3220/// enumeration type.
3221///
3222/// This routine will attempt to convert an expression of class type to an
3223/// integral or enumeration type, if that class type only has a single
3224/// conversion to an integral or enumeration type.
3225///
Douglas Gregor4799d032010-06-30 00:20:43 +00003226/// \param Loc The source location of the construct that requires the
3227/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003228///
Douglas Gregor4799d032010-06-30 00:20:43 +00003229/// \param FromE The expression we're converting from.
3230///
3231/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3232/// have integral or enumeration type.
3233///
3234/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3235/// incomplete class type.
3236///
3237/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3238/// explicit conversion function (because no implicit conversion functions
3239/// were available). This is a recovery mode.
3240///
3241/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3242/// showing which conversion was picked.
3243///
3244/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3245/// conversion function that could convert to integral or enumeration type.
3246///
3247/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3248/// usable conversion function.
3249///
3250/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3251/// function, which may be an extension in this case.
3252///
3253/// \returns The expression, converted to an integral or enumeration type if
3254/// successful.
John McCalldadc5752010-08-24 06:29:42 +00003255ExprResult
John McCallb268a282010-08-23 23:25:46 +00003256Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003257 const PartialDiagnostic &NotIntDiag,
3258 const PartialDiagnostic &IncompleteDiag,
3259 const PartialDiagnostic &ExplicitConvDiag,
3260 const PartialDiagnostic &ExplicitConvNote,
3261 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003262 const PartialDiagnostic &AmbigNote,
3263 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003264 // We can't perform any more checking for type-dependent expressions.
3265 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00003266 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003267
3268 // If the expression already has integral or enumeration type, we're golden.
3269 QualType T = From->getType();
3270 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00003271 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003272
3273 // FIXME: Check for missing '()' if T is a function type?
3274
3275 // If we don't have a class type in C++, there's no way we can get an
3276 // expression of integral or enumeration type.
3277 const RecordType *RecordTy = T->getAs<RecordType>();
3278 if (!RecordTy || !getLangOptions().CPlusPlus) {
3279 Diag(Loc, NotIntDiag)
3280 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00003281 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003282 }
3283
3284 // We must have a complete class type.
3285 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00003286 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003287
3288 // Look for a conversion to an integral or enumeration type.
3289 UnresolvedSet<4> ViableConversions;
3290 UnresolvedSet<4> ExplicitConversions;
3291 const UnresolvedSetImpl *Conversions
3292 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3293
3294 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3295 E = Conversions->end();
3296 I != E;
3297 ++I) {
3298 if (CXXConversionDecl *Conversion
3299 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3300 if (Conversion->getConversionType().getNonReferenceType()
3301 ->isIntegralOrEnumerationType()) {
3302 if (Conversion->isExplicit())
3303 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3304 else
3305 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3306 }
3307 }
3308
3309 switch (ViableConversions.size()) {
3310 case 0:
3311 if (ExplicitConversions.size() == 1) {
3312 DeclAccessPair Found = ExplicitConversions[0];
3313 CXXConversionDecl *Conversion
3314 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3315
3316 // The user probably meant to invoke the given explicit
3317 // conversion; use it.
3318 QualType ConvTy
3319 = Conversion->getConversionType().getNonReferenceType();
3320 std::string TypeStr;
3321 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3322
3323 Diag(Loc, ExplicitConvDiag)
3324 << T << ConvTy
3325 << FixItHint::CreateInsertion(From->getLocStart(),
3326 "static_cast<" + TypeStr + ">(")
3327 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3328 ")");
3329 Diag(Conversion->getLocation(), ExplicitConvNote)
3330 << ConvTy->isEnumeralType() << ConvTy;
3331
3332 // If we aren't in a SFINAE context, build a call to the
3333 // explicit conversion function.
3334 if (isSFINAEContext())
3335 return ExprError();
3336
3337 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
John McCallb268a282010-08-23 23:25:46 +00003338 From = BuildCXXMemberCallExpr(From, Found, Conversion);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003339 }
3340
3341 // We'll complain below about a non-integral condition type.
3342 break;
3343
3344 case 1: {
3345 // Apply this conversion.
3346 DeclAccessPair Found = ViableConversions[0];
3347 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor4799d032010-06-30 00:20:43 +00003348
3349 CXXConversionDecl *Conversion
3350 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3351 QualType ConvTy
3352 = Conversion->getConversionType().getNonReferenceType();
3353 if (ConvDiag.getDiagID()) {
3354 if (isSFINAEContext())
3355 return ExprError();
3356
3357 Diag(Loc, ConvDiag)
3358 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3359 }
3360
John McCallb268a282010-08-23 23:25:46 +00003361 From = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003362 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003363 break;
3364 }
3365
3366 default:
3367 Diag(Loc, AmbigDiag)
3368 << T << From->getSourceRange();
3369 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3370 CXXConversionDecl *Conv
3371 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3372 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3373 Diag(Conv->getLocation(), AmbigNote)
3374 << ConvTy->isEnumeralType() << ConvTy;
3375 }
John McCallb268a282010-08-23 23:25:46 +00003376 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003377 }
3378
Douglas Gregor5823da32010-06-29 23:25:20 +00003379 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003380 Diag(Loc, NotIntDiag)
3381 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003382
John McCallb268a282010-08-23 23:25:46 +00003383 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003384}
3385
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003386/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003387/// candidate functions, using the given function call arguments. If
3388/// @p SuppressUserConversions, then don't allow user-defined
3389/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003390///
3391/// \para PartialOverloading true if we are performing "partial" overloading
3392/// based on an incomplete set of function arguments. This feature is used by
3393/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003394void
3395Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003396 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003397 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003398 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003399 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003400 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003401 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003402 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003403 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003404 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003405 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003406
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003407 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003408 if (!isa<CXXConstructorDecl>(Method)) {
3409 // If we get here, it's because we're calling a member function
3410 // that is named without a member access expression (e.g.,
3411 // "this->f") that was either written explicitly or created
3412 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003413 // function, e.g., X::f(). We use an empty type for the implied
3414 // object argument (C++ [over.call.func]p3), and the acting context
3415 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003416 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00003417 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003418 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003419 return;
3420 }
3421 // We treat a constructor like a non-member function, since its object
3422 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003423 }
3424
Douglas Gregorff7028a2009-11-13 23:59:09 +00003425 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003426 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003427
Douglas Gregor27381f32009-11-23 12:27:39 +00003428 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003429 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003430
Douglas Gregorffe14e32009-11-14 01:20:54 +00003431 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3432 // C++ [class.copy]p3:
3433 // A member function template is never instantiated to perform the copy
3434 // of a class object to an object of its class type.
3435 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3436 if (NumArgs == 1 &&
3437 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003438 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3439 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003440 return;
3441 }
3442
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003443 // Add this candidate
3444 CandidateSet.push_back(OverloadCandidate());
3445 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003446 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003447 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003448 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003449 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003450 Candidate.IgnoreObjectArgument = false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003451
3452 unsigned NumArgsInProto = Proto->getNumArgs();
3453
3454 // (C++ 13.3.2p2): A candidate function having fewer than m
3455 // parameters is viable only if it has an ellipsis in its parameter
3456 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00003457 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3458 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003459 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003460 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003461 return;
3462 }
3463
3464 // (C++ 13.3.2p2): A candidate function having more than m parameters
3465 // is viable only if the (m+1)st parameter has a default argument
3466 // (8.3.6). For the purposes of overload resolution, the
3467 // parameter list is truncated on the right, so that there are
3468 // exactly m parameters.
3469 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003470 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003471 // Not enough arguments.
3472 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003473 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003474 return;
3475 }
3476
3477 // Determine the implicit conversion sequences for each of the
3478 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003479 Candidate.Conversions.resize(NumArgs);
3480 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3481 if (ArgIdx < NumArgsInProto) {
3482 // (C++ 13.3.2p3): for F to be a viable function, there shall
3483 // exist for each argument an implicit conversion sequence
3484 // (13.3.3.1) that converts that argument to the corresponding
3485 // parameter of F.
3486 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003487 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003488 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00003489 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003490 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003491 if (Candidate.Conversions[ArgIdx].isBad()) {
3492 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003493 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003494 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003495 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003496 } else {
3497 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3498 // argument for which there is no corresponding parameter is
3499 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003500 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003501 }
3502 }
3503}
3504
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003505/// \brief Add all of the function declarations in the given function set to
3506/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003507void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003508 Expr **Args, unsigned NumArgs,
3509 OverloadCandidateSet& CandidateSet,
3510 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003511 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003512 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3513 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003514 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003515 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003516 cast<CXXMethodDecl>(FD)->getParent(),
3517 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003518 CandidateSet, SuppressUserConversions);
3519 else
John McCalla0296f72010-03-19 07:35:19 +00003520 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003521 SuppressUserConversions);
3522 } else {
John McCalla0296f72010-03-19 07:35:19 +00003523 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003524 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3525 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003526 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003527 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003528 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003529 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003530 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003531 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003532 else
John McCalla0296f72010-03-19 07:35:19 +00003533 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003534 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003535 Args, NumArgs, CandidateSet,
3536 SuppressUserConversions);
3537 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003538 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003539}
3540
John McCallf0f1cf02009-11-17 07:50:12 +00003541/// AddMethodCandidate - Adds a named decl (which is some kind of
3542/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003543void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003544 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00003545 Expr **Args, unsigned NumArgs,
3546 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003547 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003548 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003549 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003550
3551 if (isa<UsingShadowDecl>(Decl))
3552 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3553
3554 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3555 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3556 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003557 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3558 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003559 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003560 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003561 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003562 } else {
John McCalla0296f72010-03-19 07:35:19 +00003563 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00003564 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003565 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003566 }
3567}
3568
Douglas Gregor436424c2008-11-18 23:14:02 +00003569/// AddMethodCandidate - Adds the given C++ member function to the set
3570/// of candidate functions, using the given function call arguments
3571/// and the object argument (@c Object). For example, in a call
3572/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3573/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3574/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003575/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003576void
John McCalla0296f72010-03-19 07:35:19 +00003577Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003578 CXXRecordDecl *ActingContext, QualType ObjectType,
3579 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003580 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003581 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003582 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003583 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003584 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003585 assert(!isa<CXXConstructorDecl>(Method) &&
3586 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003587
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003588 if (!CandidateSet.isNewCandidate(Method))
3589 return;
3590
Douglas Gregor27381f32009-11-23 12:27:39 +00003591 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003592 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003593
Douglas Gregor436424c2008-11-18 23:14:02 +00003594 // Add this candidate
3595 CandidateSet.push_back(OverloadCandidate());
3596 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003597 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003598 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003599 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003600 Candidate.IgnoreObjectArgument = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003601
3602 unsigned NumArgsInProto = Proto->getNumArgs();
3603
3604 // (C++ 13.3.2p2): A candidate function having fewer than m
3605 // parameters is viable only if it has an ellipsis in its parameter
3606 // list (8.3.5).
3607 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3608 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003609 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003610 return;
3611 }
3612
3613 // (C++ 13.3.2p2): A candidate function having more than m parameters
3614 // is viable only if the (m+1)st parameter has a default argument
3615 // (8.3.6). For the purposes of overload resolution, the
3616 // parameter list is truncated on the right, so that there are
3617 // exactly m parameters.
3618 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3619 if (NumArgs < MinRequiredArgs) {
3620 // Not enough arguments.
3621 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003622 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003623 return;
3624 }
3625
3626 Candidate.Viable = true;
3627 Candidate.Conversions.resize(NumArgs + 1);
3628
John McCall6e9f8f62009-12-03 04:06:58 +00003629 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003630 // The implicit object argument is ignored.
3631 Candidate.IgnoreObjectArgument = true;
3632 else {
3633 // Determine the implicit conversion sequence for the object
3634 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00003635 Candidate.Conversions[0]
John McCall5c32be02010-08-24 20:38:10 +00003636 = TryObjectArgumentInitialization(*this, ObjectType, Method,
3637 ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003638 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003639 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003640 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003641 return;
3642 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003643 }
3644
3645 // Determine the implicit conversion sequences for each of the
3646 // arguments.
3647 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3648 if (ArgIdx < NumArgsInProto) {
3649 // (C++ 13.3.2p3): for F to be a viable function, there shall
3650 // exist for each argument an implicit conversion sequence
3651 // (13.3.3.1) that converts that argument to the corresponding
3652 // parameter of F.
3653 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003654 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003655 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003656 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003657 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003658 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003659 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003660 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003661 break;
3662 }
3663 } else {
3664 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3665 // argument for which there is no corresponding parameter is
3666 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003667 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003668 }
3669 }
3670}
Douglas Gregor3626a5c2010-05-08 17:41:32 +00003671
Douglas Gregor97628d62009-08-21 00:16:32 +00003672/// \brief Add a C++ member function template as a candidate to the candidate
3673/// set, using template argument deduction to produce an appropriate member
3674/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003675void
Douglas Gregor97628d62009-08-21 00:16:32 +00003676Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003677 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003678 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003679 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003680 QualType ObjectType,
3681 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003682 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003683 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003684 if (!CandidateSet.isNewCandidate(MethodTmpl))
3685 return;
3686
Douglas Gregor97628d62009-08-21 00:16:32 +00003687 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003688 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003689 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003690 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003691 // candidate functions in the usual way.113) A given name can refer to one
3692 // or more function templates and also to a set of overloaded non-template
3693 // functions. In such a case, the candidate functions generated from each
3694 // function template are combined with the set of non-template candidate
3695 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003696 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003697 FunctionDecl *Specialization = 0;
3698 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003699 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003700 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003701 CandidateSet.push_back(OverloadCandidate());
3702 OverloadCandidate &Candidate = CandidateSet.back();
3703 Candidate.FoundDecl = FoundDecl;
3704 Candidate.Function = MethodTmpl->getTemplatedDecl();
3705 Candidate.Viable = false;
3706 Candidate.FailureKind = ovl_fail_bad_deduction;
3707 Candidate.IsSurrogate = false;
3708 Candidate.IgnoreObjectArgument = false;
3709 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3710 Info);
3711 return;
3712 }
Mike Stump11289f42009-09-09 15:08:12 +00003713
Douglas Gregor97628d62009-08-21 00:16:32 +00003714 // Add the function template specialization produced by template argument
3715 // deduction as a candidate.
3716 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003717 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003718 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003719 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003720 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003721 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003722}
3723
Douglas Gregor05155d82009-08-21 23:19:43 +00003724/// \brief Add a C++ function template specialization as a candidate
3725/// in the candidate set, using template argument deduction to produce
3726/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003727void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003728Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003729 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003730 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003731 Expr **Args, unsigned NumArgs,
3732 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003733 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003734 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3735 return;
3736
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003737 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003738 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003739 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003740 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003741 // candidate functions in the usual way.113) A given name can refer to one
3742 // or more function templates and also to a set of overloaded non-template
3743 // functions. In such a case, the candidate functions generated from each
3744 // function template are combined with the set of non-template candidate
3745 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003746 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003747 FunctionDecl *Specialization = 0;
3748 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003749 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003750 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003751 CandidateSet.push_back(OverloadCandidate());
3752 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003753 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003754 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3755 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003756 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003757 Candidate.IsSurrogate = false;
3758 Candidate.IgnoreObjectArgument = false;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003759 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3760 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003761 return;
3762 }
Mike Stump11289f42009-09-09 15:08:12 +00003763
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003764 // Add the function template specialization produced by template argument
3765 // deduction as a candidate.
3766 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003767 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003768 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003769}
Mike Stump11289f42009-09-09 15:08:12 +00003770
Douglas Gregora1f013e2008-11-07 22:36:19 +00003771/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003772/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003773/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003774/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003775/// (which may or may not be the same type as the type that the
3776/// conversion function produces).
3777void
3778Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003779 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003780 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003781 Expr *From, QualType ToType,
3782 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003783 assert(!Conversion->getDescribedFunctionTemplate() &&
3784 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003785 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003786 if (!CandidateSet.isNewCandidate(Conversion))
3787 return;
3788
Douglas Gregor27381f32009-11-23 12:27:39 +00003789 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003790 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003791
Douglas Gregora1f013e2008-11-07 22:36:19 +00003792 // Add this candidate
3793 CandidateSet.push_back(OverloadCandidate());
3794 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003795 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003796 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003797 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003798 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003799 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003800 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003801 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003802 Candidate.Viable = true;
3803 Candidate.Conversions.resize(1);
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003804
Douglas Gregor6affc782010-08-19 15:37:02 +00003805 // C++ [over.match.funcs]p4:
3806 // For conversion functions, the function is considered to be a member of
3807 // the class of the implicit implied object argument for the purpose of
3808 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003809 //
3810 // Determine the implicit conversion sequence for the implicit
3811 // object parameter.
3812 QualType ImplicitParamType = From->getType();
3813 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
3814 ImplicitParamType = FromPtrType->getPointeeType();
3815 CXXRecordDecl *ConversionContext
3816 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
3817
3818 Candidate.Conversions[0]
John McCall5c32be02010-08-24 20:38:10 +00003819 = TryObjectArgumentInitialization(*this, From->getType(), Conversion,
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003820 ConversionContext);
3821
John McCall0d1da222010-01-12 00:44:57 +00003822 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003823 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003824 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003825 return;
3826 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003827
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003828 // We won't go through a user-define type conversion function to convert a
3829 // derived to base as such conversions are given Conversion Rank. They only
3830 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3831 QualType FromCanon
3832 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3833 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3834 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3835 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003836 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003837 return;
3838 }
3839
Douglas Gregora1f013e2008-11-07 22:36:19 +00003840 // To determine what the conversion from the result of calling the
3841 // conversion function to the type we're eventually trying to
3842 // convert to (ToType), we need to synthesize a call to the
3843 // conversion function and attempt copy initialization from it. This
3844 // makes sure that we get the right semantics with respect to
3845 // lvalues/rvalues and the type. Fortunately, we can allocate this
3846 // call on the stack and we don't need its arguments to be
3847 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003848 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregore8f080122009-11-17 21:16:22 +00003849 From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00003850 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
3851 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00003852 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00003853 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00003854
3855 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003856 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3857 // allocator).
Mike Stump11289f42009-09-09 15:08:12 +00003858 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregora8a089b2010-07-13 18:40:04 +00003859 Conversion->getConversionType().getNonLValueExprType(Context),
Douglas Gregore8f080122009-11-17 21:16:22 +00003860 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003861 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003862 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003863 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003864 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003865
John McCall0d1da222010-01-12 00:44:57 +00003866 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003867 case ImplicitConversionSequence::StandardConversion:
3868 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003869
3870 // C++ [over.ics.user]p3:
3871 // If the user-defined conversion is specified by a specialization of a
3872 // conversion function template, the second standard conversion sequence
3873 // shall have exact match rank.
3874 if (Conversion->getPrimaryTemplate() &&
3875 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3876 Candidate.Viable = false;
3877 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3878 }
3879
Douglas Gregora1f013e2008-11-07 22:36:19 +00003880 break;
3881
3882 case ImplicitConversionSequence::BadConversion:
3883 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003884 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003885 break;
3886
3887 default:
Mike Stump11289f42009-09-09 15:08:12 +00003888 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00003889 "Can only end up with a standard conversion sequence or failure");
3890 }
3891}
3892
Douglas Gregor05155d82009-08-21 23:19:43 +00003893/// \brief Adds a conversion function template specialization
3894/// candidate to the overload set, using template argument deduction
3895/// to deduce the template arguments of the conversion function
3896/// template from the type that we are converting to (C++
3897/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00003898void
Douglas Gregor05155d82009-08-21 23:19:43 +00003899Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003900 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003901 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00003902 Expr *From, QualType ToType,
3903 OverloadCandidateSet &CandidateSet) {
3904 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3905 "Only conversion function templates permitted here");
3906
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003907 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3908 return;
3909
John McCallbc077cf2010-02-08 23:07:23 +00003910 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00003911 CXXConversionDecl *Specialization = 0;
3912 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00003913 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00003914 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003915 CandidateSet.push_back(OverloadCandidate());
3916 OverloadCandidate &Candidate = CandidateSet.back();
3917 Candidate.FoundDecl = FoundDecl;
3918 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3919 Candidate.Viable = false;
3920 Candidate.FailureKind = ovl_fail_bad_deduction;
3921 Candidate.IsSurrogate = false;
3922 Candidate.IgnoreObjectArgument = false;
3923 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3924 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00003925 return;
3926 }
Mike Stump11289f42009-09-09 15:08:12 +00003927
Douglas Gregor05155d82009-08-21 23:19:43 +00003928 // Add the conversion function template specialization produced by
3929 // template argument deduction as a candidate.
3930 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003931 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00003932 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00003933}
3934
Douglas Gregorab7897a2008-11-19 22:57:39 +00003935/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3936/// converts the given @c Object to a function pointer via the
3937/// conversion function @c Conversion, and then attempts to call it
3938/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3939/// the type of function that we'll eventually be calling.
3940void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003941 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003942 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003943 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00003944 QualType ObjectType,
3945 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00003946 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003947 if (!CandidateSet.isNewCandidate(Conversion))
3948 return;
3949
Douglas Gregor27381f32009-11-23 12:27:39 +00003950 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003951 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003952
Douglas Gregorab7897a2008-11-19 22:57:39 +00003953 CandidateSet.push_back(OverloadCandidate());
3954 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003955 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003956 Candidate.Function = 0;
3957 Candidate.Surrogate = Conversion;
3958 Candidate.Viable = true;
3959 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003960 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003961 Candidate.Conversions.resize(NumArgs + 1);
3962
3963 // Determine the implicit conversion sequence for the implicit
3964 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00003965 ImplicitConversionSequence ObjectInit
John McCall5c32be02010-08-24 20:38:10 +00003966 = TryObjectArgumentInitialization(*this, ObjectType, Conversion,
3967 ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003968 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00003969 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003970 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00003971 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003972 return;
3973 }
3974
3975 // The first conversion is actually a user-defined conversion whose
3976 // first conversion is ObjectInit's standard conversion (which is
3977 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00003978 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00003979 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00003980 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003981 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump11289f42009-09-09 15:08:12 +00003982 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00003983 = Candidate.Conversions[0].UserDefined.Before;
3984 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3985
Mike Stump11289f42009-09-09 15:08:12 +00003986 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00003987 unsigned NumArgsInProto = Proto->getNumArgs();
3988
3989 // (C++ 13.3.2p2): A candidate function having fewer than m
3990 // parameters is viable only if it has an ellipsis in its parameter
3991 // list (8.3.5).
3992 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3993 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003994 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003995 return;
3996 }
3997
3998 // Function types don't have any default arguments, so just check if
3999 // we have enough arguments.
4000 if (NumArgs < NumArgsInProto) {
4001 // Not enough arguments.
4002 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004003 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004004 return;
4005 }
4006
4007 // Determine the implicit conversion sequences for each of the
4008 // arguments.
4009 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4010 if (ArgIdx < NumArgsInProto) {
4011 // (C++ 13.3.2p3): for F to be a viable function, there shall
4012 // exist for each argument an implicit conversion sequence
4013 // (13.3.3.1) that converts that argument to the corresponding
4014 // parameter of F.
4015 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004016 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004017 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004018 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00004019 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00004020 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004021 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004022 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004023 break;
4024 }
4025 } else {
4026 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4027 // argument for which there is no corresponding parameter is
4028 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004029 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004030 }
4031 }
4032}
4033
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004034/// \brief Add overload candidates for overloaded operators that are
4035/// member functions.
4036///
4037/// Add the overloaded operator candidates that are member functions
4038/// for the operator Op that was used in an operator expression such
4039/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4040/// CandidateSet will store the added overload candidates. (C++
4041/// [over.match.oper]).
4042void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4043 SourceLocation OpLoc,
4044 Expr **Args, unsigned NumArgs,
4045 OverloadCandidateSet& CandidateSet,
4046 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004047 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4048
4049 // C++ [over.match.oper]p3:
4050 // For a unary operator @ with an operand of a type whose
4051 // cv-unqualified version is T1, and for a binary operator @ with
4052 // a left operand of a type whose cv-unqualified version is T1 and
4053 // a right operand of a type whose cv-unqualified version is T2,
4054 // three sets of candidate functions, designated member
4055 // candidates, non-member candidates and built-in candidates, are
4056 // constructed as follows:
4057 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00004058
4059 // -- If T1 is a class type, the set of member candidates is the
4060 // result of the qualified lookup of T1::operator@
4061 // (13.3.1.1.1); otherwise, the set of member candidates is
4062 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004063 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004064 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004065 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004066 return;
Mike Stump11289f42009-09-09 15:08:12 +00004067
John McCall27b18f82009-11-17 02:14:36 +00004068 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4069 LookupQualifiedName(Operators, T1Rec->getDecl());
4070 Operators.suppressDiagnostics();
4071
Mike Stump11289f42009-09-09 15:08:12 +00004072 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004073 OperEnd = Operators.end();
4074 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004075 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004076 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00004077 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004078 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004079 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004080}
4081
Douglas Gregora11693b2008-11-12 17:17:38 +00004082/// AddBuiltinCandidate - Add a candidate for a built-in
4083/// operator. ResultTy and ParamTys are the result and parameter types
4084/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004085/// arguments being passed to the candidate. IsAssignmentOperator
4086/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004087/// operator. NumContextualBoolArguments is the number of arguments
4088/// (at the beginning of the argument list) that will be contextually
4089/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004090void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004091 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004092 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004093 bool IsAssignmentOperator,
4094 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004095 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004096 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004097
Douglas Gregora11693b2008-11-12 17:17:38 +00004098 // Add this candidate
4099 CandidateSet.push_back(OverloadCandidate());
4100 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004101 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004102 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004103 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004104 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004105 Candidate.BuiltinTypes.ResultTy = ResultTy;
4106 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4107 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4108
4109 // Determine the implicit conversion sequences for each of the
4110 // arguments.
4111 Candidate.Viable = true;
4112 Candidate.Conversions.resize(NumArgs);
4113 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004114 // C++ [over.match.oper]p4:
4115 // For the built-in assignment operators, conversions of the
4116 // left operand are restricted as follows:
4117 // -- no temporaries are introduced to hold the left operand, and
4118 // -- no user-defined conversions are applied to the left
4119 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004120 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004121 //
4122 // We block these conversions by turning off user-defined
4123 // conversions, since that is the only way that initialization of
4124 // a reference to a non-class type can occur from something that
4125 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004126 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004127 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004128 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00004129 Candidate.Conversions[ArgIdx]
4130 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004131 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004132 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004133 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004134 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00004135 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004136 }
John McCall0d1da222010-01-12 00:44:57 +00004137 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004138 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004139 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004140 break;
4141 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004142 }
4143}
4144
4145/// BuiltinCandidateTypeSet - A set of types that will be used for the
4146/// candidate operator functions for built-in operators (C++
4147/// [over.built]). The types are separated into pointer types and
4148/// enumeration types.
4149class BuiltinCandidateTypeSet {
4150 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004151 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004152
4153 /// PointerTypes - The set of pointer types that will be used in the
4154 /// built-in candidates.
4155 TypeSet PointerTypes;
4156
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004157 /// MemberPointerTypes - The set of member pointer types that will be
4158 /// used in the built-in candidates.
4159 TypeSet MemberPointerTypes;
4160
Douglas Gregora11693b2008-11-12 17:17:38 +00004161 /// EnumerationTypes - The set of enumeration types that will be
4162 /// used in the built-in candidates.
4163 TypeSet EnumerationTypes;
4164
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004165 /// \brief The set of vector types that will be used in the built-in
4166 /// candidates.
4167 TypeSet VectorTypes;
4168
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004169 /// Sema - The semantic analysis instance where we are building the
4170 /// candidate type set.
4171 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004172
Douglas Gregora11693b2008-11-12 17:17:38 +00004173 /// Context - The AST context in which we will build the type sets.
4174 ASTContext &Context;
4175
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004176 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4177 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004178 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004179
4180public:
4181 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004182 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004183
Mike Stump11289f42009-09-09 15:08:12 +00004184 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004185 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004186
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004187 void AddTypesConvertedFrom(QualType Ty,
4188 SourceLocation Loc,
4189 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004190 bool AllowExplicitConversions,
4191 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004192
4193 /// pointer_begin - First pointer type found;
4194 iterator pointer_begin() { return PointerTypes.begin(); }
4195
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004196 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004197 iterator pointer_end() { return PointerTypes.end(); }
4198
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004199 /// member_pointer_begin - First member pointer type found;
4200 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4201
4202 /// member_pointer_end - Past the last member pointer type found;
4203 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4204
Douglas Gregora11693b2008-11-12 17:17:38 +00004205 /// enumeration_begin - First enumeration type found;
4206 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4207
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004208 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004209 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004210
4211 iterator vector_begin() { return VectorTypes.begin(); }
4212 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregora11693b2008-11-12 17:17:38 +00004213};
4214
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004215/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004216/// the set of pointer types along with any more-qualified variants of
4217/// that type. For example, if @p Ty is "int const *", this routine
4218/// will add "int const *", "int const volatile *", "int const
4219/// restrict *", and "int const volatile restrict *" to the set of
4220/// pointer types. Returns true if the add of @p Ty itself succeeded,
4221/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004222///
4223/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004224bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004225BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4226 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004227
Douglas Gregora11693b2008-11-12 17:17:38 +00004228 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004229 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004230 return false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004231
4232 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00004233 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004234 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004235 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004236 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004237 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004238 buildObjCPtr = true;
4239 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004240 else
4241 assert(false && "type was not a pointer type!");
4242 }
4243 else
4244 PointeeTy = PointerTy->getPointeeType();
4245
Sebastian Redl4990a632009-11-18 20:39:26 +00004246 // Don't add qualified variants of arrays. For one, they're not allowed
4247 // (the qualifier would sink to the element type), and for another, the
4248 // only overload situation where it matters is subscript or pointer +- int,
4249 // and those shouldn't have qualifier variants anyway.
4250 if (PointeeTy->isArrayType())
4251 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004252 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00004253 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00004254 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004255 bool hasVolatile = VisibleQuals.hasVolatile();
4256 bool hasRestrict = VisibleQuals.hasRestrict();
4257
John McCall8ccfcb52009-09-24 19:53:00 +00004258 // Iterate through all strict supersets of BaseCVR.
4259 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4260 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004261 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4262 // in the types.
4263 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4264 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00004265 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004266 if (!buildObjCPtr)
4267 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4268 else
4269 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00004270 }
4271
4272 return true;
4273}
4274
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004275/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4276/// to the set of pointer types along with any more-qualified variants of
4277/// that type. For example, if @p Ty is "int const *", this routine
4278/// will add "int const *", "int const volatile *", "int const
4279/// restrict *", and "int const volatile restrict *" to the set of
4280/// pointer types. Returns true if the add of @p Ty itself succeeded,
4281/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004282///
4283/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004284bool
4285BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4286 QualType Ty) {
4287 // Insert this type.
4288 if (!MemberPointerTypes.insert(Ty))
4289 return false;
4290
John McCall8ccfcb52009-09-24 19:53:00 +00004291 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4292 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004293
John McCall8ccfcb52009-09-24 19:53:00 +00004294 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004295 // Don't add qualified variants of arrays. For one, they're not allowed
4296 // (the qualifier would sink to the element type), and for another, the
4297 // only overload situation where it matters is subscript or pointer +- int,
4298 // and those shouldn't have qualifier variants anyway.
4299 if (PointeeTy->isArrayType())
4300 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004301 const Type *ClassTy = PointerTy->getClass();
4302
4303 // Iterate through all strict supersets of the pointee type's CVR
4304 // qualifiers.
4305 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4306 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4307 if ((CVR | BaseCVR) != CVR) continue;
4308
4309 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4310 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004311 }
4312
4313 return true;
4314}
4315
Douglas Gregora11693b2008-11-12 17:17:38 +00004316/// AddTypesConvertedFrom - Add each of the types to which the type @p
4317/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004318/// primarily interested in pointer types and enumeration types. We also
4319/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004320/// AllowUserConversions is true if we should look at the conversion
4321/// functions of a class type, and AllowExplicitConversions if we
4322/// should also include the explicit conversion functions of a class
4323/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004324void
Douglas Gregor5fb53972009-01-14 15:45:31 +00004325BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004326 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004327 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004328 bool AllowExplicitConversions,
4329 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004330 // Only deal with canonical types.
4331 Ty = Context.getCanonicalType(Ty);
4332
4333 // Look through reference types; they aren't part of the type of an
4334 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004335 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00004336 Ty = RefTy->getPointeeType();
4337
4338 // We don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004339 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00004340
Sebastian Redl65ae2002009-11-05 16:36:20 +00004341 // If we're dealing with an array type, decay to the pointer.
4342 if (Ty->isArrayType())
4343 Ty = SemaRef.Context.getArrayDecayedType(Ty);
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004344 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4345 PointerTypes.insert(Ty);
4346 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004347 // Insert our type, and its more-qualified variants, into the set
4348 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004349 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00004350 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004351 } else if (Ty->isMemberPointerType()) {
4352 // Member pointers are far easier, since the pointee can't be converted.
4353 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4354 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00004355 } else if (Ty->isEnumeralType()) {
Chris Lattnera59a3e22009-03-29 00:04:01 +00004356 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004357 } else if (Ty->isVectorType()) {
4358 VectorTypes.insert(Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004359 } else if (AllowUserConversions) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004360 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004361 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004362 // No conversion functions in incomplete types.
4363 return;
4364 }
Mike Stump11289f42009-09-09 15:08:12 +00004365
Douglas Gregora11693b2008-11-12 17:17:38 +00004366 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCallad371252010-01-20 00:46:10 +00004367 const UnresolvedSetImpl *Conversions
Fariborz Jahanianae01f782009-10-07 17:26:09 +00004368 = ClassDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00004369 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004370 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004371 NamedDecl *D = I.getDecl();
4372 if (isa<UsingShadowDecl>(D))
4373 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004374
Mike Stump11289f42009-09-09 15:08:12 +00004375 // Skip conversion function templates; they don't tell us anything
Douglas Gregor05155d82009-08-21 23:19:43 +00004376 // about which builtin types we can convert to.
John McCallda4458e2010-03-31 01:36:47 +00004377 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor05155d82009-08-21 23:19:43 +00004378 continue;
4379
John McCallda4458e2010-03-31 01:36:47 +00004380 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004381 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004382 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004383 VisibleQuals);
4384 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004385 }
4386 }
4387 }
4388}
4389
Douglas Gregor84605ae2009-08-24 13:43:27 +00004390/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4391/// the volatile- and non-volatile-qualified assignment operators for the
4392/// given type to the candidate set.
4393static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4394 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004395 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004396 unsigned NumArgs,
4397 OverloadCandidateSet &CandidateSet) {
4398 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004399
Douglas Gregor84605ae2009-08-24 13:43:27 +00004400 // T& operator=(T&, T)
4401 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4402 ParamTypes[1] = T;
4403 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4404 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004405
Douglas Gregor84605ae2009-08-24 13:43:27 +00004406 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4407 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004408 ParamTypes[0]
4409 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004410 ParamTypes[1] = T;
4411 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004412 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004413 }
4414}
Mike Stump11289f42009-09-09 15:08:12 +00004415
Sebastian Redl1054fae2009-10-25 17:03:50 +00004416/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4417/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004418static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4419 Qualifiers VRQuals;
4420 const RecordType *TyRec;
4421 if (const MemberPointerType *RHSMPType =
4422 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004423 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004424 else
4425 TyRec = ArgExpr->getType()->getAs<RecordType>();
4426 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004427 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004428 VRQuals.addVolatile();
4429 VRQuals.addRestrict();
4430 return VRQuals;
4431 }
4432
4433 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004434 if (!ClassDecl->hasDefinition())
4435 return VRQuals;
4436
John McCallad371252010-01-20 00:46:10 +00004437 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004438 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004439
John McCallad371252010-01-20 00:46:10 +00004440 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004441 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004442 NamedDecl *D = I.getDecl();
4443 if (isa<UsingShadowDecl>(D))
4444 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4445 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004446 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4447 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4448 CanTy = ResTypeRef->getPointeeType();
4449 // Need to go down the pointer/mempointer chain and add qualifiers
4450 // as see them.
4451 bool done = false;
4452 while (!done) {
4453 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4454 CanTy = ResTypePtr->getPointeeType();
4455 else if (const MemberPointerType *ResTypeMPtr =
4456 CanTy->getAs<MemberPointerType>())
4457 CanTy = ResTypeMPtr->getPointeeType();
4458 else
4459 done = true;
4460 if (CanTy.isVolatileQualified())
4461 VRQuals.addVolatile();
4462 if (CanTy.isRestrictQualified())
4463 VRQuals.addRestrict();
4464 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4465 return VRQuals;
4466 }
4467 }
4468 }
4469 return VRQuals;
4470}
4471
Douglas Gregord08452f2008-11-19 15:42:04 +00004472/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4473/// operator overloads to the candidate set (C++ [over.built]), based
4474/// on the operator @p Op and the arguments given. For example, if the
4475/// operator is a binary '+', this routine might add "int
4476/// operator+(int, int)" to cover integer addition.
Douglas Gregora11693b2008-11-12 17:17:38 +00004477void
Mike Stump11289f42009-09-09 15:08:12 +00004478Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004479 SourceLocation OpLoc,
Douglas Gregord08452f2008-11-19 15:42:04 +00004480 Expr **Args, unsigned NumArgs,
4481 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004482 // The set of "promoted arithmetic types", which are the arithmetic
4483 // types are that preserved by promotion (C++ [over.built]p2). Note
4484 // that the first few of these types are the promoted integral
4485 // types; these types need to be first.
4486 // FIXME: What about complex?
4487 const unsigned FirstIntegralType = 0;
4488 const unsigned LastIntegralType = 13;
Mike Stump11289f42009-09-09 15:08:12 +00004489 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregora11693b2008-11-12 17:17:38 +00004490 LastPromotedIntegralType = 13;
4491 const unsigned FirstPromotedArithmeticType = 7,
4492 LastPromotedArithmeticType = 16;
4493 const unsigned NumArithmeticTypes = 16;
4494 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump11289f42009-09-09 15:08:12 +00004495 Context.BoolTy, Context.CharTy, Context.WCharTy,
4496// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregora11693b2008-11-12 17:17:38 +00004497 Context.SignedCharTy, Context.ShortTy,
4498 Context.UnsignedCharTy, Context.UnsignedShortTy,
4499 Context.IntTy, Context.LongTy, Context.LongLongTy,
4500 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
4501 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
4502 };
Douglas Gregorb8440a72009-10-21 22:01:30 +00004503 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
4504 "Invalid first promoted integral type");
4505 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4506 == Context.UnsignedLongLongTy &&
4507 "Invalid last promoted integral type");
4508 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
4509 "Invalid first promoted arithmetic type");
4510 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4511 == Context.LongDoubleTy &&
4512 "Invalid last promoted arithmetic type");
4513
Douglas Gregora11693b2008-11-12 17:17:38 +00004514 // Find all of the types that the arguments can convert to, but only
4515 // if the operator we're looking at has built-in operator candidates
4516 // that make use of these types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004517 Qualifiers VisibleTypeConversionsQuals;
4518 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00004519 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4520 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4521
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004522 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004523 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4524 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4525 OpLoc,
4526 true,
4527 (Op == OO_Exclaim ||
4528 Op == OO_AmpAmp ||
4529 Op == OO_PipePipe),
4530 VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004531
Douglas Gregor2bbc0262010-09-12 04:28:07 +00004532 // C++ [over.built]p1:
4533 // If there is a user-written candidate with the same name and parameter
4534 // types as a built-in candidate operator function, the built-in operator
4535 // function is hidden and is not included in the set of candidate functions.
4536 //
4537 // The text is actually in a note, but if we don't implement it then we end
4538 // up with ambiguities when the user provides an overloaded operator for
4539 // an enumeration type. Note that only enumeration types have this problem,
4540 // so we track which enumeration types we've seen operators for.
4541 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
4542 UserDefinedBinaryOperators;
4543
4544 if (CandidateTypes.enumeration_begin() != CandidateTypes.enumeration_end()) {
4545 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
4546 CEnd = CandidateSet.end();
4547 C != CEnd; ++C) {
4548 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
4549 continue;
4550
4551 // Check if the first parameter is of enumeration type.
4552 QualType FirstParamType
4553 = C->Function->getParamDecl(0)->getType().getUnqualifiedType();
4554 if (!FirstParamType->isEnumeralType())
4555 continue;
4556
4557 // Check if the second parameter is of enumeration type.
4558 QualType SecondParamType
4559 = C->Function->getParamDecl(1)->getType().getUnqualifiedType();
4560 if (!SecondParamType->isEnumeralType())
4561 continue;
4562
4563 // Add this operator to the set of known user-defined operators.
4564 UserDefinedBinaryOperators.insert(
4565 std::make_pair(Context.getCanonicalType(FirstParamType),
4566 Context.getCanonicalType(SecondParamType)));
4567 }
4568 }
4569
Douglas Gregora11693b2008-11-12 17:17:38 +00004570 bool isComparison = false;
4571 switch (Op) {
4572 case OO_None:
4573 case NUM_OVERLOADED_OPERATORS:
4574 assert(false && "Expected an overloaded operator");
4575 break;
4576
Douglas Gregord08452f2008-11-19 15:42:04 +00004577 case OO_Star: // '*' is either unary or binary
Mike Stump11289f42009-09-09 15:08:12 +00004578 if (NumArgs == 1)
Douglas Gregord08452f2008-11-19 15:42:04 +00004579 goto UnaryStar;
4580 else
4581 goto BinaryStar;
4582 break;
4583
4584 case OO_Plus: // '+' is either unary or binary
4585 if (NumArgs == 1)
4586 goto UnaryPlus;
4587 else
4588 goto BinaryPlus;
4589 break;
4590
4591 case OO_Minus: // '-' is either unary or binary
4592 if (NumArgs == 1)
4593 goto UnaryMinus;
4594 else
4595 goto BinaryMinus;
4596 break;
4597
4598 case OO_Amp: // '&' is either unary or binary
4599 if (NumArgs == 1)
4600 goto UnaryAmp;
4601 else
4602 goto BinaryAmp;
4603
4604 case OO_PlusPlus:
4605 case OO_MinusMinus:
4606 // C++ [over.built]p3:
4607 //
4608 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4609 // is either volatile or empty, there exist candidate operator
4610 // functions of the form
4611 //
4612 // VQ T& operator++(VQ T&);
4613 // T operator++(VQ T&, int);
4614 //
4615 // C++ [over.built]p4:
4616 //
4617 // For every pair (T, VQ), where T is an arithmetic type other
4618 // than bool, and VQ is either volatile or empty, there exist
4619 // candidate operator functions of the form
4620 //
4621 // VQ T& operator--(VQ T&);
4622 // T operator--(VQ T&, int);
Mike Stump11289f42009-09-09 15:08:12 +00004623 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregord08452f2008-11-19 15:42:04 +00004624 Arith < NumArithmeticTypes; ++Arith) {
4625 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump11289f42009-09-09 15:08:12 +00004626 QualType ParamTypes[2]
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004627 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregord08452f2008-11-19 15:42:04 +00004628
4629 // Non-volatile version.
4630 if (NumArgs == 1)
4631 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4632 else
4633 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004634 // heuristic to reduce number of builtin candidates in the set.
4635 // Add volatile version only if there are conversions to a volatile type.
4636 if (VisibleTypeConversionsQuals.hasVolatile()) {
4637 // Volatile version
4638 ParamTypes[0]
4639 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4640 if (NumArgs == 1)
4641 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4642 else
4643 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4644 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004645 }
4646
4647 // C++ [over.built]p5:
4648 //
4649 // For every pair (T, VQ), where T is a cv-qualified or
4650 // cv-unqualified object type, and VQ is either volatile or
4651 // empty, there exist candidate operator functions of the form
4652 //
4653 // T*VQ& operator++(T*VQ&);
4654 // T*VQ& operator--(T*VQ&);
4655 // T* operator++(T*VQ&, int);
4656 // T* operator--(T*VQ&, int);
4657 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4658 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4659 // Skip pointer types that aren't pointers to object types.
Eli Friedmana170cd62010-08-05 02:49:48 +00004660 if (!(*Ptr)->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregord08452f2008-11-19 15:42:04 +00004661 continue;
4662
Mike Stump11289f42009-09-09 15:08:12 +00004663 QualType ParamTypes[2] = {
4664 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregord08452f2008-11-19 15:42:04 +00004665 };
Mike Stump11289f42009-09-09 15:08:12 +00004666
Douglas Gregord08452f2008-11-19 15:42:04 +00004667 // Without volatile
4668 if (NumArgs == 1)
4669 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4670 else
4671 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4672
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004673 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4674 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00004675 // With volatile
John McCall8ccfcb52009-09-24 19:53:00 +00004676 ParamTypes[0]
4677 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregord08452f2008-11-19 15:42:04 +00004678 if (NumArgs == 1)
4679 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4680 else
4681 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4682 }
4683 }
4684 break;
4685
4686 UnaryStar:
4687 // C++ [over.built]p6:
4688 // For every cv-qualified or cv-unqualified object type T, there
4689 // exist candidate operator functions of the form
4690 //
4691 // T& operator*(T*);
4692 //
4693 // C++ [over.built]p7:
4694 // For every function type T, there exist candidate operator
4695 // functions of the form
4696 // T& operator*(T*);
4697 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4698 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4699 QualType ParamTy = *Ptr;
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00004700 QualType PointeeTy = ParamTy->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004701 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregord08452f2008-11-19 15:42:04 +00004702 &ParamTy, Args, 1, CandidateSet);
4703 }
4704 break;
4705
4706 UnaryPlus:
4707 // C++ [over.built]p8:
4708 // For every type T, there exist candidate operator functions of
4709 // the form
4710 //
4711 // T* operator+(T*);
4712 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4713 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4714 QualType ParamTy = *Ptr;
4715 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4716 }
Mike Stump11289f42009-09-09 15:08:12 +00004717
Douglas Gregord08452f2008-11-19 15:42:04 +00004718 // Fall through
4719
4720 UnaryMinus:
4721 // C++ [over.built]p9:
4722 // For every promoted arithmetic type T, there exist candidate
4723 // operator functions of the form
4724 //
4725 // T operator+(T);
4726 // T operator-(T);
Mike Stump11289f42009-09-09 15:08:12 +00004727 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004728 Arith < LastPromotedArithmeticType; ++Arith) {
4729 QualType ArithTy = ArithmeticTypes[Arith];
4730 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4731 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004732
4733 // Extension: We also add these operators for vector types.
4734 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4735 VecEnd = CandidateTypes.vector_end();
4736 Vec != VecEnd; ++Vec) {
4737 QualType VecTy = *Vec;
4738 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4739 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004740 break;
4741
4742 case OO_Tilde:
4743 // C++ [over.built]p10:
4744 // For every promoted integral type T, there exist candidate
4745 // operator functions of the form
4746 //
4747 // T operator~(T);
Mike Stump11289f42009-09-09 15:08:12 +00004748 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregord08452f2008-11-19 15:42:04 +00004749 Int < LastPromotedIntegralType; ++Int) {
4750 QualType IntTy = ArithmeticTypes[Int];
4751 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4752 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004753
4754 // Extension: We also add this operator for vector types.
4755 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4756 VecEnd = CandidateTypes.vector_end();
4757 Vec != VecEnd; ++Vec) {
4758 QualType VecTy = *Vec;
4759 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4760 }
Douglas Gregord08452f2008-11-19 15:42:04 +00004761 break;
4762
Douglas Gregora11693b2008-11-12 17:17:38 +00004763 case OO_New:
4764 case OO_Delete:
4765 case OO_Array_New:
4766 case OO_Array_Delete:
Douglas Gregora11693b2008-11-12 17:17:38 +00004767 case OO_Call:
Douglas Gregord08452f2008-11-19 15:42:04 +00004768 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregora11693b2008-11-12 17:17:38 +00004769 break;
4770
4771 case OO_Comma:
Douglas Gregord08452f2008-11-19 15:42:04 +00004772 UnaryAmp:
4773 case OO_Arrow:
Douglas Gregora11693b2008-11-12 17:17:38 +00004774 // C++ [over.match.oper]p3:
4775 // -- For the operator ',', the unary operator '&', or the
4776 // operator '->', the built-in candidates set is empty.
Douglas Gregora11693b2008-11-12 17:17:38 +00004777 break;
4778
Douglas Gregor84605ae2009-08-24 13:43:27 +00004779 case OO_EqualEqual:
4780 case OO_ExclaimEqual:
4781 // C++ [over.match.oper]p16:
Mike Stump11289f42009-09-09 15:08:12 +00004782 // For every pointer to member type T, there exist candidate operator
4783 // functions of the form
Douglas Gregor84605ae2009-08-24 13:43:27 +00004784 //
4785 // bool operator==(T,T);
4786 // bool operator!=(T,T);
Mike Stump11289f42009-09-09 15:08:12 +00004787 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor84605ae2009-08-24 13:43:27 +00004788 MemPtr = CandidateTypes.member_pointer_begin(),
4789 MemPtrEnd = CandidateTypes.member_pointer_end();
4790 MemPtr != MemPtrEnd;
4791 ++MemPtr) {
4792 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4793 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4794 }
Mike Stump11289f42009-09-09 15:08:12 +00004795
Douglas Gregor84605ae2009-08-24 13:43:27 +00004796 // Fall through
Mike Stump11289f42009-09-09 15:08:12 +00004797
Douglas Gregora11693b2008-11-12 17:17:38 +00004798 case OO_Less:
4799 case OO_Greater:
4800 case OO_LessEqual:
4801 case OO_GreaterEqual:
Douglas Gregora11693b2008-11-12 17:17:38 +00004802 // C++ [over.built]p15:
4803 //
4804 // For every pointer or enumeration type T, there exist
4805 // candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004806 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004807 // bool operator<(T, T);
4808 // bool operator>(T, T);
4809 // bool operator<=(T, T);
4810 // bool operator>=(T, T);
4811 // bool operator==(T, T);
4812 // bool operator!=(T, T);
4813 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4814 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4815 QualType ParamTypes[2] = { *Ptr, *Ptr };
4816 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4817 }
Mike Stump11289f42009-09-09 15:08:12 +00004818 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregora11693b2008-11-12 17:17:38 +00004819 = CandidateTypes.enumeration_begin();
4820 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4821 QualType ParamTypes[2] = { *Enum, *Enum };
Douglas Gregor2bbc0262010-09-12 04:28:07 +00004822 CanQualType CanonType = Context.getCanonicalType(*Enum);
4823 if (!UserDefinedBinaryOperators.count(
4824 std::make_pair(CanonType, CanonType)))
4825 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregora11693b2008-11-12 17:17:38 +00004826 }
4827
4828 // Fall through.
4829 isComparison = true;
4830
Douglas Gregord08452f2008-11-19 15:42:04 +00004831 BinaryPlus:
4832 BinaryMinus:
Douglas Gregora11693b2008-11-12 17:17:38 +00004833 if (!isComparison) {
4834 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4835
4836 // C++ [over.built]p13:
4837 //
4838 // For every cv-qualified or cv-unqualified object type T
4839 // there exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00004840 //
Douglas Gregora11693b2008-11-12 17:17:38 +00004841 // T* operator+(T*, ptrdiff_t);
4842 // T& operator[](T*, ptrdiff_t); [BELOW]
4843 // T* operator-(T*, ptrdiff_t);
4844 // T* operator+(ptrdiff_t, T*);
4845 // T& operator[](ptrdiff_t, T*); [BELOW]
4846 //
4847 // C++ [over.built]p14:
4848 //
4849 // For every T, where T is a pointer to object type, there
4850 // exist candidate operator functions of the form
4851 //
4852 // ptrdiff_t operator-(T, T);
Mike Stump11289f42009-09-09 15:08:12 +00004853 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregora11693b2008-11-12 17:17:38 +00004854 = CandidateTypes.pointer_begin();
4855 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4856 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4857
4858 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4859 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4860
4861 if (Op == OO_Plus) {
4862 // T* operator+(ptrdiff_t, T*);
4863 ParamTypes[0] = ParamTypes[1];
4864 ParamTypes[1] = *Ptr;
4865 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4866 } else {
4867 // ptrdiff_t operator-(T, T);
4868 ParamTypes[1] = *Ptr;
4869 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4870 Args, 2, CandidateSet);
4871 }
4872 }
4873 }
4874 // Fall through
4875
Douglas Gregora11693b2008-11-12 17:17:38 +00004876 case OO_Slash:
Douglas Gregord08452f2008-11-19 15:42:04 +00004877 BinaryStar:
Sebastian Redl1a99f442009-04-16 17:51:27 +00004878 Conditional:
Douglas Gregora11693b2008-11-12 17:17:38 +00004879 // C++ [over.built]p12:
4880 //
4881 // For every pair of promoted arithmetic types L and R, there
4882 // exist candidate operator functions of the form
4883 //
4884 // LR operator*(L, R);
4885 // LR operator/(L, R);
4886 // LR operator+(L, R);
4887 // LR operator-(L, R);
4888 // bool operator<(L, R);
4889 // bool operator>(L, R);
4890 // bool operator<=(L, R);
4891 // bool operator>=(L, R);
4892 // bool operator==(L, R);
4893 // bool operator!=(L, R);
4894 //
4895 // where LR is the result of the usual arithmetic conversions
4896 // between types L and R.
Sebastian Redl1a99f442009-04-16 17:51:27 +00004897 //
4898 // C++ [over.built]p24:
4899 //
4900 // For every pair of promoted arithmetic types L and R, there exist
4901 // candidate operator functions of the form
4902 //
4903 // LR operator?(bool, L, R);
4904 //
4905 // where LR is the result of the usual arithmetic conversions
4906 // between types L and R.
4907 // Our candidates ignore the first parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004908 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004909 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004910 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004911 Right < LastPromotedArithmeticType; ++Right) {
4912 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004913 QualType Result
4914 = isComparison
4915 ? Context.BoolTy
4916 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004917 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4918 }
4919 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004920
4921 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
4922 // conditional operator for vector types.
4923 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4924 Vec1End = CandidateTypes.vector_end();
4925 Vec1 != Vec1End; ++Vec1)
4926 for (BuiltinCandidateTypeSet::iterator
4927 Vec2 = CandidateTypes.vector_begin(),
4928 Vec2End = CandidateTypes.vector_end();
4929 Vec2 != Vec2End; ++Vec2) {
4930 QualType LandR[2] = { *Vec1, *Vec2 };
4931 QualType Result;
4932 if (isComparison)
4933 Result = Context.BoolTy;
4934 else {
4935 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
4936 Result = *Vec1;
4937 else
4938 Result = *Vec2;
4939 }
4940
4941 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4942 }
4943
Douglas Gregora11693b2008-11-12 17:17:38 +00004944 break;
4945
4946 case OO_Percent:
Douglas Gregord08452f2008-11-19 15:42:04 +00004947 BinaryAmp:
Douglas Gregora11693b2008-11-12 17:17:38 +00004948 case OO_Caret:
4949 case OO_Pipe:
4950 case OO_LessLess:
4951 case OO_GreaterGreater:
4952 // C++ [over.built]p17:
4953 //
4954 // For every pair of promoted integral types L and R, there
4955 // exist candidate operator functions of the form
4956 //
4957 // LR operator%(L, R);
4958 // LR operator&(L, R);
4959 // LR operator^(L, R);
4960 // LR operator|(L, R);
4961 // L operator<<(L, R);
4962 // L operator>>(L, R);
4963 //
4964 // where LR is the result of the usual arithmetic conversions
4965 // between types L and R.
Mike Stump11289f42009-09-09 15:08:12 +00004966 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004967 Left < LastPromotedIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00004968 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00004969 Right < LastPromotedIntegralType; ++Right) {
4970 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4971 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4972 ? LandR[0]
Eli Friedman5ae98ee2009-08-19 07:44:53 +00004973 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregora11693b2008-11-12 17:17:38 +00004974 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4975 }
4976 }
4977 break;
4978
4979 case OO_Equal:
4980 // C++ [over.built]p20:
4981 //
4982 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor84605ae2009-08-24 13:43:27 +00004983 // pointer to member type and VQ is either volatile or
Douglas Gregora11693b2008-11-12 17:17:38 +00004984 // empty, there exist candidate operator functions of the form
4985 //
4986 // VQ T& operator=(VQ T&, T);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004987 for (BuiltinCandidateTypeSet::iterator
4988 Enum = CandidateTypes.enumeration_begin(),
4989 EnumEnd = CandidateTypes.enumeration_end();
4990 Enum != EnumEnd; ++Enum)
Mike Stump11289f42009-09-09 15:08:12 +00004991 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004992 CandidateSet);
4993 for (BuiltinCandidateTypeSet::iterator
4994 MemPtr = CandidateTypes.member_pointer_begin(),
4995 MemPtrEnd = CandidateTypes.member_pointer_end();
4996 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump11289f42009-09-09 15:08:12 +00004997 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004998 CandidateSet);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004999
5000 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00005001
5002 case OO_PlusEqual:
5003 case OO_MinusEqual:
5004 // C++ [over.built]p19:
5005 //
5006 // For every pair (T, VQ), where T is any type and VQ is either
5007 // volatile or empty, there exist candidate operator functions
5008 // of the form
5009 //
5010 // T*VQ& operator=(T*VQ&, T*);
5011 //
5012 // C++ [over.built]p21:
5013 //
5014 // For every pair (T, VQ), where T is a cv-qualified or
5015 // cv-unqualified object type and VQ is either volatile or
5016 // empty, there exist candidate operator functions of the form
5017 //
5018 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5019 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5020 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
5021 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5022 QualType ParamTypes[2];
5023 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
5024
5025 // non-volatile version
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005026 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregorc5e61072009-01-13 00:52:54 +00005027 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5028 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00005029
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005030 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5031 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregord08452f2008-11-19 15:42:04 +00005032 // volatile version
John McCall8ccfcb52009-09-24 19:53:00 +00005033 ParamTypes[0]
5034 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregorc5e61072009-01-13 00:52:54 +00005035 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5036 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregord08452f2008-11-19 15:42:04 +00005037 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005038 }
5039 // Fall through.
5040
5041 case OO_StarEqual:
5042 case OO_SlashEqual:
5043 // C++ [over.built]p18:
5044 //
5045 // For every triple (L, VQ, R), where L is an arithmetic type,
5046 // VQ is either volatile or empty, and R is a promoted
5047 // arithmetic type, there exist candidate operator functions of
5048 // the form
5049 //
5050 // VQ L& operator=(VQ L&, R);
5051 // VQ L& operator*=(VQ L&, R);
5052 // VQ L& operator/=(VQ L&, R);
5053 // VQ L& operator+=(VQ L&, R);
5054 // VQ L& operator-=(VQ L&, R);
5055 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00005056 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005057 Right < LastPromotedArithmeticType; ++Right) {
5058 QualType ParamTypes[2];
5059 ParamTypes[1] = ArithmeticTypes[Right];
5060
5061 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005062 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregorc5e61072009-01-13 00:52:54 +00005063 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5064 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00005065
5066 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005067 if (VisibleTypeConversionsQuals.hasVolatile()) {
5068 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
5069 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5070 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5071 /*IsAssigmentOperator=*/Op == OO_Equal);
5072 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005073 }
5074 }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005075
5076 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5077 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
5078 Vec1End = CandidateTypes.vector_end();
5079 Vec1 != Vec1End; ++Vec1)
5080 for (BuiltinCandidateTypeSet::iterator
5081 Vec2 = CandidateTypes.vector_begin(),
5082 Vec2End = CandidateTypes.vector_end();
5083 Vec2 != Vec2End; ++Vec2) {
5084 QualType ParamTypes[2];
5085 ParamTypes[1] = *Vec2;
5086 // Add this built-in operator as a candidate (VQ is empty).
5087 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
5088 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5089 /*IsAssigmentOperator=*/Op == OO_Equal);
5090
5091 // Add this built-in operator as a candidate (VQ is 'volatile').
5092 if (VisibleTypeConversionsQuals.hasVolatile()) {
5093 ParamTypes[0] = Context.getVolatileType(*Vec1);
5094 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5095 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5096 /*IsAssigmentOperator=*/Op == OO_Equal);
5097 }
5098 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005099 break;
5100
5101 case OO_PercentEqual:
5102 case OO_LessLessEqual:
5103 case OO_GreaterGreaterEqual:
5104 case OO_AmpEqual:
5105 case OO_CaretEqual:
5106 case OO_PipeEqual:
5107 // C++ [over.built]p22:
5108 //
5109 // For every triple (L, VQ, R), where L is an integral type, VQ
5110 // is either volatile or empty, and R is a promoted integral
5111 // type, there exist candidate operator functions of the form
5112 //
5113 // VQ L& operator%=(VQ L&, R);
5114 // VQ L& operator<<=(VQ L&, R);
5115 // VQ L& operator>>=(VQ L&, R);
5116 // VQ L& operator&=(VQ L&, R);
5117 // VQ L& operator^=(VQ L&, R);
5118 // VQ L& operator|=(VQ L&, R);
5119 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump11289f42009-09-09 15:08:12 +00005120 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregora11693b2008-11-12 17:17:38 +00005121 Right < LastPromotedIntegralType; ++Right) {
5122 QualType ParamTypes[2];
5123 ParamTypes[1] = ArithmeticTypes[Right];
5124
5125 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005126 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregora11693b2008-11-12 17:17:38 +00005127 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana4a93342009-10-20 00:04:40 +00005128 if (VisibleTypeConversionsQuals.hasVolatile()) {
5129 // Add this built-in operator as a candidate (VQ is 'volatile').
5130 ParamTypes[0] = ArithmeticTypes[Left];
5131 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
5132 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5133 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5134 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005135 }
5136 }
5137 break;
5138
Douglas Gregord08452f2008-11-19 15:42:04 +00005139 case OO_Exclaim: {
5140 // C++ [over.operator]p23:
5141 //
5142 // There also exist candidate operator functions of the form
5143 //
Mike Stump11289f42009-09-09 15:08:12 +00005144 // bool operator!(bool);
Douglas Gregord08452f2008-11-19 15:42:04 +00005145 // bool operator&&(bool, bool); [BELOW]
5146 // bool operator||(bool, bool); [BELOW]
5147 QualType ParamTy = Context.BoolTy;
Douglas Gregor5fb53972009-01-14 15:45:31 +00005148 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5149 /*IsAssignmentOperator=*/false,
5150 /*NumContextualBoolArguments=*/1);
Douglas Gregord08452f2008-11-19 15:42:04 +00005151 break;
5152 }
5153
Douglas Gregora11693b2008-11-12 17:17:38 +00005154 case OO_AmpAmp:
5155 case OO_PipePipe: {
5156 // C++ [over.operator]p23:
5157 //
5158 // There also exist candidate operator functions of the form
5159 //
Douglas Gregord08452f2008-11-19 15:42:04 +00005160 // bool operator!(bool); [ABOVE]
Douglas Gregora11693b2008-11-12 17:17:38 +00005161 // bool operator&&(bool, bool);
5162 // bool operator||(bool, bool);
5163 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor5fb53972009-01-14 15:45:31 +00005164 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5165 /*IsAssignmentOperator=*/false,
5166 /*NumContextualBoolArguments=*/2);
Douglas Gregora11693b2008-11-12 17:17:38 +00005167 break;
5168 }
5169
5170 case OO_Subscript:
5171 // C++ [over.built]p13:
5172 //
5173 // For every cv-qualified or cv-unqualified object type T there
5174 // exist candidate operator functions of the form
Mike Stump11289f42009-09-09 15:08:12 +00005175 //
Douglas Gregora11693b2008-11-12 17:17:38 +00005176 // T* operator+(T*, ptrdiff_t); [ABOVE]
5177 // T& operator[](T*, ptrdiff_t);
5178 // T* operator-(T*, ptrdiff_t); [ABOVE]
5179 // T* operator+(ptrdiff_t, T*); [ABOVE]
5180 // T& operator[](ptrdiff_t, T*);
5181 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
5182 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5183 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00005184 QualType PointeeType = (*Ptr)->getPointeeType();
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005185 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregora11693b2008-11-12 17:17:38 +00005186
5187 // T& operator[](T*, ptrdiff_t)
5188 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5189
5190 // T& operator[](ptrdiff_t, T*);
5191 ParamTypes[0] = ParamTypes[1];
5192 ParamTypes[1] = *Ptr;
5193 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005194 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005195 break;
5196
5197 case OO_ArrowStar:
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005198 // C++ [over.built]p11:
5199 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5200 // C1 is the same type as C2 or is a derived class of C2, T is an object
5201 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5202 // there exist candidate operator functions of the form
5203 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5204 // where CV12 is the union of CV1 and CV2.
5205 {
5206 for (BuiltinCandidateTypeSet::iterator Ptr =
5207 CandidateTypes.pointer_begin();
5208 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5209 QualType C1Ty = (*Ptr);
5210 QualType C1;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005211 QualifierCollector Q1;
Argyrios Kyrtzidis421ad5e2010-08-23 07:12:16 +00005212 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5213 if (!isa<RecordType>(C1))
5214 continue;
5215 // heuristic to reduce number of builtin candidates in the set.
5216 // Add volatile/restrict version only if there are conversions to a
5217 // volatile/restrict type.
5218 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5219 continue;
5220 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5221 continue;
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005222 for (BuiltinCandidateTypeSet::iterator
5223 MemPtr = CandidateTypes.member_pointer_begin(),
5224 MemPtrEnd = CandidateTypes.member_pointer_end();
5225 MemPtr != MemPtrEnd; ++MemPtr) {
5226 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5227 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian12df37c2009-10-07 16:56:50 +00005228 C2 = C2.getUnqualifiedType();
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005229 if (C1 != C2 && !IsDerivedFrom(C1, C2))
5230 break;
5231 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5232 // build CV12 T&
5233 QualType T = mptr->getPointeeType();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005234 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5235 T.isVolatileQualified())
5236 continue;
5237 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5238 T.isRestrictQualified())
5239 continue;
Fariborz Jahanian4dc12462009-10-09 16:34:40 +00005240 T = Q1.apply(T);
Fariborz Jahanian34d93dc2009-10-06 23:08:05 +00005241 QualType ResultTy = Context.getLValueReferenceType(T);
5242 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5243 }
5244 }
5245 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005246 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005247
5248 case OO_Conditional:
5249 // Note that we don't consider the first argument, since it has been
5250 // contextually converted to bool long ago. The candidates below are
5251 // therefore added as binary.
5252 //
5253 // C++ [over.built]p24:
5254 // For every type T, where T is a pointer or pointer-to-member type,
5255 // there exist candidate operator functions of the form
5256 //
5257 // T operator?(bool, T, T);
5258 //
Sebastian Redl1a99f442009-04-16 17:51:27 +00005259 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
5260 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
5261 QualType ParamTypes[2] = { *Ptr, *Ptr };
5262 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5263 }
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005264 for (BuiltinCandidateTypeSet::iterator Ptr =
5265 CandidateTypes.member_pointer_begin(),
5266 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
5267 QualType ParamTypes[2] = { *Ptr, *Ptr };
5268 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5269 }
Sebastian Redl1a99f442009-04-16 17:51:27 +00005270 goto Conditional;
Douglas Gregora11693b2008-11-12 17:17:38 +00005271 }
5272}
5273
Douglas Gregore254f902009-02-04 00:32:51 +00005274/// \brief Add function candidates found via argument-dependent lookup
5275/// to the set of overloading candidates.
5276///
5277/// This routine performs argument-dependent name lookup based on the
5278/// given function name (which may also be an operator name) and adds
5279/// all of the overload candidates found by ADL to the overload
5280/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00005281void
Douglas Gregore254f902009-02-04 00:32:51 +00005282Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00005283 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00005284 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00005285 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005286 OverloadCandidateSet& CandidateSet,
5287 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00005288 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00005289
John McCall91f61fc2010-01-26 06:04:06 +00005290 // FIXME: This approach for uniquing ADL results (and removing
5291 // redundant candidates from the set) relies on pointer-equality,
5292 // which means we need to key off the canonical decl. However,
5293 // always going back to the canonical decl might not get us the
5294 // right set of default arguments. What default arguments are
5295 // we supposed to consider on ADL candidates, anyway?
5296
Douglas Gregorcabea402009-09-22 15:41:20 +00005297 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00005298 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00005299
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005300 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005301 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5302 CandEnd = CandidateSet.end();
5303 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00005304 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00005305 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00005306 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00005307 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00005308 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005309
5310 // For each of the ADL candidates we found, add it to the overload
5311 // set.
John McCall8fe68082010-01-26 07:16:45 +00005312 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00005313 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00005314 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00005315 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00005316 continue;
5317
John McCalla0296f72010-03-19 07:35:19 +00005318 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005319 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005320 } else
John McCall4c4c1df2010-01-26 03:27:55 +00005321 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00005322 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00005323 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00005324 }
Douglas Gregore254f902009-02-04 00:32:51 +00005325}
5326
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005327/// isBetterOverloadCandidate - Determines whether the first overload
5328/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00005329bool
John McCall5c32be02010-08-24 20:38:10 +00005330isBetterOverloadCandidate(Sema &S,
5331 const OverloadCandidate& Cand1,
5332 const OverloadCandidate& Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005333 SourceLocation Loc,
5334 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005335 // Define viable functions to be better candidates than non-viable
5336 // functions.
5337 if (!Cand2.Viable)
5338 return Cand1.Viable;
5339 else if (!Cand1.Viable)
5340 return false;
5341
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005342 // C++ [over.match.best]p1:
5343 //
5344 // -- if F is a static member function, ICS1(F) is defined such
5345 // that ICS1(F) is neither better nor worse than ICS1(G) for
5346 // any function G, and, symmetrically, ICS1(G) is neither
5347 // better nor worse than ICS1(F).
5348 unsigned StartArg = 0;
5349 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5350 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005351
Douglas Gregord3cb3562009-07-07 23:38:56 +00005352 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005353 // A viable function F1 is defined to be a better function than another
5354 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00005355 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005356 unsigned NumArgs = Cand1.Conversions.size();
5357 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5358 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005359 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00005360 switch (CompareImplicitConversionSequences(S,
5361 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005362 Cand2.Conversions[ArgIdx])) {
5363 case ImplicitConversionSequence::Better:
5364 // Cand1 has a better conversion sequence.
5365 HasBetterConversion = true;
5366 break;
5367
5368 case ImplicitConversionSequence::Worse:
5369 // Cand1 can't be better than Cand2.
5370 return false;
5371
5372 case ImplicitConversionSequence::Indistinguishable:
5373 // Do nothing.
5374 break;
5375 }
5376 }
5377
Mike Stump11289f42009-09-09 15:08:12 +00005378 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00005379 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005380 if (HasBetterConversion)
5381 return true;
5382
Mike Stump11289f42009-09-09 15:08:12 +00005383 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00005384 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00005385 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00005386 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5387 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005388
5389 // -- F1 and F2 are function template specializations, and the function
5390 // template for F1 is more specialized than the template for F2
5391 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00005392 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00005393 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5394 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor05155d82009-08-21 23:19:43 +00005395 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00005396 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5397 Cand2.Function->getPrimaryTemplate(),
5398 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00005399 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5400 : TPOC_Call))
Douglas Gregor05155d82009-08-21 23:19:43 +00005401 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005402
Douglas Gregora1f013e2008-11-07 22:36:19 +00005403 // -- the context is an initialization by user-defined conversion
5404 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5405 // from the return type of F1 to the destination type (i.e.,
5406 // the type of the entity being initialized) is a better
5407 // conversion sequence than the standard conversion sequence
5408 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00005409 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005410 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00005411 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00005412 switch (CompareStandardConversionSequences(S,
5413 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005414 Cand2.FinalConversion)) {
5415 case ImplicitConversionSequence::Better:
5416 // Cand1 has a better conversion sequence.
5417 return true;
5418
5419 case ImplicitConversionSequence::Worse:
5420 // Cand1 can't be better than Cand2.
5421 return false;
5422
5423 case ImplicitConversionSequence::Indistinguishable:
5424 // Do nothing
5425 break;
5426 }
5427 }
5428
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005429 return false;
5430}
5431
Mike Stump11289f42009-09-09 15:08:12 +00005432/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005433/// within an overload candidate set.
5434///
5435/// \param CandidateSet the set of candidate functions.
5436///
5437/// \param Loc the location of the function name (or operator symbol) for
5438/// which overload resolution occurs.
5439///
Mike Stump11289f42009-09-09 15:08:12 +00005440/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005441/// function, Best points to the candidate function found.
5442///
5443/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00005444OverloadingResult
5445OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005446 iterator& Best,
5447 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005448 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00005449 Best = end();
5450 for (iterator Cand = begin(); Cand != end(); ++Cand) {
5451 if (Cand->Viable)
Douglas Gregord5b730c92010-09-12 08:07:23 +00005452 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
5453 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005454 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005455 }
5456
5457 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00005458 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005459 return OR_No_Viable_Function;
5460
5461 // Make sure that this function is better than every other viable
5462 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00005463 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00005464 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005465 Cand != Best &&
Douglas Gregord5b730c92010-09-12 08:07:23 +00005466 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
5467 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00005468 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005469 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005470 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005471 }
Mike Stump11289f42009-09-09 15:08:12 +00005472
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005473 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00005474 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005475 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005476 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00005477 return OR_Deleted;
5478
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005479 // C++ [basic.def.odr]p2:
5480 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00005481 // when referred to from a potentially-evaluated expression. [Note: this
5482 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005483 // (clause 13), user-defined conversions (12.3.2), allocation function for
5484 // placement new (5.3.4), as well as non-default initialization (8.5).
5485 if (Best->Function)
John McCall5c32be02010-08-24 20:38:10 +00005486 S.MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005487 return OR_Success;
5488}
5489
John McCall53262c92010-01-12 02:15:36 +00005490namespace {
5491
5492enum OverloadCandidateKind {
5493 oc_function,
5494 oc_method,
5495 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005496 oc_function_template,
5497 oc_method_template,
5498 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00005499 oc_implicit_default_constructor,
5500 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00005501 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00005502};
5503
John McCalle1ac8d12010-01-13 00:25:19 +00005504OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5505 FunctionDecl *Fn,
5506 std::string &Description) {
5507 bool isTemplate = false;
5508
5509 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5510 isTemplate = true;
5511 Description = S.getTemplateArgumentBindingsText(
5512 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5513 }
John McCallfd0b2f82010-01-06 09:43:14 +00005514
5515 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00005516 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005517 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005518
John McCall53262c92010-01-12 02:15:36 +00005519 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5520 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00005521 }
5522
5523 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5524 // This actually gets spelled 'candidate function' for now, but
5525 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00005526 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00005527 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00005528
Douglas Gregorec3bec02010-09-27 22:37:28 +00005529 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00005530 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00005531 return oc_implicit_copy_assignment;
5532 }
5533
John McCalle1ac8d12010-01-13 00:25:19 +00005534 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00005535}
5536
5537} // end anonymous namespace
5538
5539// Notes the location of an overload candidate.
5540void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00005541 std::string FnDesc;
5542 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5543 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5544 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00005545}
5546
John McCall0d1da222010-01-12 00:44:57 +00005547/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5548/// "lead" diagnostic; it will be given two arguments, the source and
5549/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00005550void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
5551 Sema &S,
5552 SourceLocation CaretLoc,
5553 const PartialDiagnostic &PDiag) const {
5554 S.Diag(CaretLoc, PDiag)
5555 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00005556 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00005557 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
5558 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00005559 }
John McCall12f97bc2010-01-08 04:41:39 +00005560}
5561
John McCall0d1da222010-01-12 00:44:57 +00005562namespace {
5563
John McCall6a61b522010-01-13 09:16:55 +00005564void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5565 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5566 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00005567 assert(Cand->Function && "for now, candidate must be a function");
5568 FunctionDecl *Fn = Cand->Function;
5569
5570 // There's a conversion slot for the object argument if this is a
5571 // non-constructor method. Note that 'I' corresponds the
5572 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00005573 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00005574 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00005575 if (I == 0)
5576 isObjectArgument = true;
5577 else
5578 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00005579 }
5580
John McCalle1ac8d12010-01-13 00:25:19 +00005581 std::string FnDesc;
5582 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5583
John McCall6a61b522010-01-13 09:16:55 +00005584 Expr *FromExpr = Conv.Bad.FromExpr;
5585 QualType FromTy = Conv.Bad.getFromType();
5586 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00005587
John McCallfb7ad0f2010-02-02 02:42:52 +00005588 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00005589 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00005590 Expr *E = FromExpr->IgnoreParens();
5591 if (isa<UnaryOperator>(E))
5592 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00005593 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00005594
5595 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5596 << (unsigned) FnKind << FnDesc
5597 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5598 << ToTy << Name << I+1;
5599 return;
5600 }
5601
John McCall6d174642010-01-23 08:10:49 +00005602 // Do some hand-waving analysis to see if the non-viability is due
5603 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00005604 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5605 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5606 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5607 CToTy = RT->getPointeeType();
5608 else {
5609 // TODO: detect and diagnose the full richness of const mismatches.
5610 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5611 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5612 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5613 }
5614
5615 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5616 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5617 // It is dumb that we have to do this here.
5618 while (isa<ArrayType>(CFromTy))
5619 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5620 while (isa<ArrayType>(CToTy))
5621 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5622
5623 Qualifiers FromQs = CFromTy.getQualifiers();
5624 Qualifiers ToQs = CToTy.getQualifiers();
5625
5626 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5627 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5628 << (unsigned) FnKind << FnDesc
5629 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5630 << FromTy
5631 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5632 << (unsigned) isObjectArgument << I+1;
5633 return;
5634 }
5635
5636 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5637 assert(CVR && "unexpected qualifiers mismatch");
5638
5639 if (isObjectArgument) {
5640 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5641 << (unsigned) FnKind << FnDesc
5642 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5643 << FromTy << (CVR - 1);
5644 } else {
5645 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5646 << (unsigned) FnKind << FnDesc
5647 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5648 << FromTy << (CVR - 1) << I+1;
5649 }
5650 return;
5651 }
5652
John McCall6d174642010-01-23 08:10:49 +00005653 // Diagnose references or pointers to incomplete types differently,
5654 // since it's far from impossible that the incompleteness triggered
5655 // the failure.
5656 QualType TempFromTy = FromTy.getNonReferenceType();
5657 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5658 TempFromTy = PTy->getPointeeType();
5659 if (TempFromTy->isIncompleteType()) {
5660 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5661 << (unsigned) FnKind << FnDesc
5662 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5663 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5664 return;
5665 }
5666
Douglas Gregor56f2e342010-06-30 23:01:39 +00005667 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005668 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00005669 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
5670 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
5671 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5672 FromPtrTy->getPointeeType()) &&
5673 !FromPtrTy->getPointeeType()->isIncompleteType() &&
5674 !ToPtrTy->getPointeeType()->isIncompleteType() &&
5675 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
5676 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005677 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00005678 }
5679 } else if (const ObjCObjectPointerType *FromPtrTy
5680 = FromTy->getAs<ObjCObjectPointerType>()) {
5681 if (const ObjCObjectPointerType *ToPtrTy
5682 = ToTy->getAs<ObjCObjectPointerType>())
5683 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
5684 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
5685 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5686 FromPtrTy->getPointeeType()) &&
5687 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005688 BaseToDerivedConversion = 2;
5689 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
5690 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
5691 !FromTy->isIncompleteType() &&
5692 !ToRefTy->getPointeeType()->isIncompleteType() &&
5693 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
5694 BaseToDerivedConversion = 3;
5695 }
5696
5697 if (BaseToDerivedConversion) {
Douglas Gregor56f2e342010-06-30 23:01:39 +00005698 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005699 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00005700 << (unsigned) FnKind << FnDesc
5701 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00005702 << (BaseToDerivedConversion - 1)
Douglas Gregor56f2e342010-06-30 23:01:39 +00005703 << FromTy << ToTy << I+1;
5704 return;
5705 }
5706
John McCall47000992010-01-14 03:28:57 +00005707 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00005708 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5709 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00005710 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00005711 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00005712}
5713
5714void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5715 unsigned NumFormalArgs) {
5716 // TODO: treat calls to a missing default constructor as a special case
5717
5718 FunctionDecl *Fn = Cand->Function;
5719 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5720
5721 unsigned MinParams = Fn->getMinRequiredArguments();
5722
5723 // at least / at most / exactly
Douglas Gregor02eb4832010-05-08 18:13:28 +00005724 // FIXME: variadic templates "at most" should account for parameter packs
John McCall6a61b522010-01-13 09:16:55 +00005725 unsigned mode, modeCount;
5726 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005727 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5728 (Cand->FailureKind == ovl_fail_bad_deduction &&
5729 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCall6a61b522010-01-13 09:16:55 +00005730 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5731 mode = 0; // "at least"
5732 else
5733 mode = 2; // "exactly"
5734 modeCount = MinParams;
5735 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00005736 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5737 (Cand->FailureKind == ovl_fail_bad_deduction &&
5738 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00005739 if (MinParams != FnTy->getNumArgs())
5740 mode = 1; // "at most"
5741 else
5742 mode = 2; // "exactly"
5743 modeCount = FnTy->getNumArgs();
5744 }
5745
5746 std::string Description;
5747 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5748
5749 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregor02eb4832010-05-08 18:13:28 +00005750 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5751 << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00005752}
5753
John McCall8b9ed552010-02-01 18:53:26 +00005754/// Diagnose a failed template-argument deduction.
5755void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5756 Expr **Args, unsigned NumArgs) {
5757 FunctionDecl *Fn = Cand->Function; // pattern
5758
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005759 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005760 NamedDecl *ParamD;
5761 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5762 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5763 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00005764 switch (Cand->DeductionFailure.Result) {
5765 case Sema::TDK_Success:
5766 llvm_unreachable("TDK_success while diagnosing bad deduction");
5767
5768 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00005769 assert(ParamD && "no parameter found for incomplete deduction result");
5770 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5771 << ParamD->getDeclName();
5772 return;
5773 }
5774
John McCall42d7d192010-08-05 09:05:08 +00005775 case Sema::TDK_Underqualified: {
5776 assert(ParamD && "no parameter found for bad qualifiers deduction result");
5777 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
5778
5779 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
5780
5781 // Param will have been canonicalized, but it should just be a
5782 // qualified version of ParamD, so move the qualifiers to that.
5783 QualifierCollector Qs(S.Context);
5784 Qs.strip(Param);
5785 QualType NonCanonParam = Qs.apply(TParam->getTypeForDecl());
5786 assert(S.Context.hasSameType(Param, NonCanonParam));
5787
5788 // Arg has also been canonicalized, but there's nothing we can do
5789 // about that. It also doesn't matter as much, because it won't
5790 // have any template parameters in it (because deduction isn't
5791 // done on dependent types).
5792 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
5793
5794 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
5795 << ParamD->getDeclName() << Arg << NonCanonParam;
5796 return;
5797 }
5798
5799 case Sema::TDK_Inconsistent: {
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005800 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005801 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005802 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005803 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005804 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005805 which = 1;
5806 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005807 which = 2;
5808 }
5809
5810 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5811 << which << ParamD->getDeclName()
5812 << *Cand->DeductionFailure.getFirstArg()
5813 << *Cand->DeductionFailure.getSecondArg();
5814 return;
5815 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00005816
Douglas Gregor1d72edd2010-05-08 19:15:54 +00005817 case Sema::TDK_InvalidExplicitArguments:
5818 assert(ParamD && "no parameter found for invalid explicit arguments");
5819 if (ParamD->getDeclName())
5820 S.Diag(Fn->getLocation(),
5821 diag::note_ovl_candidate_explicit_arg_mismatch_named)
5822 << ParamD->getDeclName();
5823 else {
5824 int index = 0;
5825 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5826 index = TTP->getIndex();
5827 else if (NonTypeTemplateParmDecl *NTTP
5828 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5829 index = NTTP->getIndex();
5830 else
5831 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
5832 S.Diag(Fn->getLocation(),
5833 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
5834 << (index + 1);
5835 }
5836 return;
5837
Douglas Gregor02eb4832010-05-08 18:13:28 +00005838 case Sema::TDK_TooManyArguments:
5839 case Sema::TDK_TooFewArguments:
5840 DiagnoseArityMismatch(S, Cand, NumArgs);
5841 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00005842
5843 case Sema::TDK_InstantiationDepth:
5844 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
5845 return;
5846
5847 case Sema::TDK_SubstitutionFailure: {
5848 std::string ArgString;
5849 if (TemplateArgumentList *Args
5850 = Cand->DeductionFailure.getTemplateArgumentList())
5851 ArgString = S.getTemplateArgumentBindingsText(
5852 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
5853 *Args);
5854 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
5855 << ArgString;
5856 return;
5857 }
Douglas Gregor3626a5c2010-05-08 17:41:32 +00005858
John McCall8b9ed552010-02-01 18:53:26 +00005859 // TODO: diagnose these individually, then kill off
5860 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00005861 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00005862 case Sema::TDK_FailedOverloadResolution:
5863 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
5864 return;
5865 }
5866}
5867
5868/// Generates a 'note' diagnostic for an overload candidate. We've
5869/// already generated a primary error at the call site.
5870///
5871/// It really does need to be a single diagnostic with its caret
5872/// pointed at the candidate declaration. Yes, this creates some
5873/// major challenges of technical writing. Yes, this makes pointing
5874/// out problems with specific arguments quite awkward. It's still
5875/// better than generating twenty screens of text for every failed
5876/// overload.
5877///
5878/// It would be great to be able to express per-candidate problems
5879/// more richly for those diagnostic clients that cared, but we'd
5880/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00005881void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
5882 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00005883 FunctionDecl *Fn = Cand->Function;
5884
John McCall12f97bc2010-01-08 04:41:39 +00005885 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00005886 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00005887 std::string FnDesc;
5888 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00005889
5890 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00005891 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00005892 return;
John McCall12f97bc2010-01-08 04:41:39 +00005893 }
5894
John McCalle1ac8d12010-01-13 00:25:19 +00005895 // We don't really have anything else to say about viable candidates.
5896 if (Cand->Viable) {
5897 S.NoteOverloadCandidate(Fn);
5898 return;
5899 }
John McCall0d1da222010-01-12 00:44:57 +00005900
John McCall6a61b522010-01-13 09:16:55 +00005901 switch (Cand->FailureKind) {
5902 case ovl_fail_too_many_arguments:
5903 case ovl_fail_too_few_arguments:
5904 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00005905
John McCall6a61b522010-01-13 09:16:55 +00005906 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00005907 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5908
John McCallfe796dd2010-01-23 05:17:32 +00005909 case ovl_fail_trivial_conversion:
5910 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005911 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00005912 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005913
John McCall65eb8792010-02-25 01:37:24 +00005914 case ovl_fail_bad_conversion: {
5915 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5916 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00005917 if (Cand->Conversions[I].isBad())
5918 return DiagnoseBadConversion(S, Cand, I);
5919
5920 // FIXME: this currently happens when we're called from SemaInit
5921 // when user-conversion overload fails. Figure out how to handle
5922 // those conditions and diagnose them well.
5923 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00005924 }
John McCall65eb8792010-02-25 01:37:24 +00005925 }
John McCalld3224162010-01-08 00:58:21 +00005926}
5927
5928void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5929 // Desugar the type of the surrogate down to a function type,
5930 // retaining as many typedefs as possible while still showing
5931 // the function type (and, therefore, its parameter types).
5932 QualType FnType = Cand->Surrogate->getConversionType();
5933 bool isLValueReference = false;
5934 bool isRValueReference = false;
5935 bool isPointer = false;
5936 if (const LValueReferenceType *FnTypeRef =
5937 FnType->getAs<LValueReferenceType>()) {
5938 FnType = FnTypeRef->getPointeeType();
5939 isLValueReference = true;
5940 } else if (const RValueReferenceType *FnTypeRef =
5941 FnType->getAs<RValueReferenceType>()) {
5942 FnType = FnTypeRef->getPointeeType();
5943 isRValueReference = true;
5944 }
5945 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5946 FnType = FnTypePtr->getPointeeType();
5947 isPointer = true;
5948 }
5949 // Desugar down to a function type.
5950 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5951 // Reconstruct the pointer/reference as appropriate.
5952 if (isPointer) FnType = S.Context.getPointerType(FnType);
5953 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5954 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5955
5956 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5957 << FnType;
5958}
5959
5960void NoteBuiltinOperatorCandidate(Sema &S,
5961 const char *Opc,
5962 SourceLocation OpLoc,
5963 OverloadCandidate *Cand) {
5964 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5965 std::string TypeStr("operator");
5966 TypeStr += Opc;
5967 TypeStr += "(";
5968 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5969 if (Cand->Conversions.size() == 1) {
5970 TypeStr += ")";
5971 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5972 } else {
5973 TypeStr += ", ";
5974 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5975 TypeStr += ")";
5976 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5977 }
5978}
5979
5980void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5981 OverloadCandidate *Cand) {
5982 unsigned NoOperands = Cand->Conversions.size();
5983 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5984 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00005985 if (ICS.isBad()) break; // all meaningless after first invalid
5986 if (!ICS.isAmbiguous()) continue;
5987
John McCall5c32be02010-08-24 20:38:10 +00005988 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00005989 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00005990 }
5991}
5992
John McCall3712d9e2010-01-15 23:32:50 +00005993SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5994 if (Cand->Function)
5995 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00005996 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00005997 return Cand->Surrogate->getLocation();
5998 return SourceLocation();
5999}
6000
John McCallad2587a2010-01-12 00:48:53 +00006001struct CompareOverloadCandidatesForDisplay {
6002 Sema &S;
6003 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00006004
6005 bool operator()(const OverloadCandidate *L,
6006 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00006007 // Fast-path this check.
6008 if (L == R) return false;
6009
John McCall12f97bc2010-01-08 04:41:39 +00006010 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00006011 if (L->Viable) {
6012 if (!R->Viable) return true;
6013
6014 // TODO: introduce a tri-valued comparison for overload
6015 // candidates. Would be more worthwhile if we had a sort
6016 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00006017 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6018 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00006019 } else if (R->Viable)
6020 return false;
John McCall12f97bc2010-01-08 04:41:39 +00006021
John McCall3712d9e2010-01-15 23:32:50 +00006022 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00006023
John McCall3712d9e2010-01-15 23:32:50 +00006024 // Criteria by which we can sort non-viable candidates:
6025 if (!L->Viable) {
6026 // 1. Arity mismatches come after other candidates.
6027 if (L->FailureKind == ovl_fail_too_many_arguments ||
6028 L->FailureKind == ovl_fail_too_few_arguments)
6029 return false;
6030 if (R->FailureKind == ovl_fail_too_many_arguments ||
6031 R->FailureKind == ovl_fail_too_few_arguments)
6032 return true;
John McCall12f97bc2010-01-08 04:41:39 +00006033
John McCallfe796dd2010-01-23 05:17:32 +00006034 // 2. Bad conversions come first and are ordered by the number
6035 // of bad conversions and quality of good conversions.
6036 if (L->FailureKind == ovl_fail_bad_conversion) {
6037 if (R->FailureKind != ovl_fail_bad_conversion)
6038 return true;
6039
6040 // If there's any ordering between the defined conversions...
6041 // FIXME: this might not be transitive.
6042 assert(L->Conversions.size() == R->Conversions.size());
6043
6044 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00006045 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6046 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00006047 switch (CompareImplicitConversionSequences(S,
6048 L->Conversions[I],
6049 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00006050 case ImplicitConversionSequence::Better:
6051 leftBetter++;
6052 break;
6053
6054 case ImplicitConversionSequence::Worse:
6055 leftBetter--;
6056 break;
6057
6058 case ImplicitConversionSequence::Indistinguishable:
6059 break;
6060 }
6061 }
6062 if (leftBetter > 0) return true;
6063 if (leftBetter < 0) return false;
6064
6065 } else if (R->FailureKind == ovl_fail_bad_conversion)
6066 return false;
6067
John McCall3712d9e2010-01-15 23:32:50 +00006068 // TODO: others?
6069 }
6070
6071 // Sort everything else by location.
6072 SourceLocation LLoc = GetLocationForCandidate(L);
6073 SourceLocation RLoc = GetLocationForCandidate(R);
6074
6075 // Put candidates without locations (e.g. builtins) at the end.
6076 if (LLoc.isInvalid()) return false;
6077 if (RLoc.isInvalid()) return true;
6078
6079 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00006080 }
6081};
6082
John McCallfe796dd2010-01-23 05:17:32 +00006083/// CompleteNonViableCandidate - Normally, overload resolution only
6084/// computes up to the first
6085void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6086 Expr **Args, unsigned NumArgs) {
6087 assert(!Cand->Viable);
6088
6089 // Don't do anything on failures other than bad conversion.
6090 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6091
6092 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00006093 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00006094 unsigned ConvCount = Cand->Conversions.size();
6095 while (true) {
6096 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6097 ConvIdx++;
6098 if (Cand->Conversions[ConvIdx - 1].isBad())
6099 break;
6100 }
6101
6102 if (ConvIdx == ConvCount)
6103 return;
6104
John McCall65eb8792010-02-25 01:37:24 +00006105 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6106 "remaining conversion is initialized?");
6107
Douglas Gregoradc7a702010-04-16 17:45:54 +00006108 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00006109 // operation somehow.
6110 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00006111
6112 const FunctionProtoType* Proto;
6113 unsigned ArgIdx = ConvIdx;
6114
6115 if (Cand->IsSurrogate) {
6116 QualType ConvType
6117 = Cand->Surrogate->getConversionType().getNonReferenceType();
6118 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6119 ConvType = ConvPtrType->getPointeeType();
6120 Proto = ConvType->getAs<FunctionProtoType>();
6121 ArgIdx--;
6122 } else if (Cand->Function) {
6123 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6124 if (isa<CXXMethodDecl>(Cand->Function) &&
6125 !isa<CXXConstructorDecl>(Cand->Function))
6126 ArgIdx--;
6127 } else {
6128 // Builtin binary operator with a bad first conversion.
6129 assert(ConvCount <= 3);
6130 for (; ConvIdx != ConvCount; ++ConvIdx)
6131 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006132 = TryCopyInitialization(S, Args[ConvIdx],
6133 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6134 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006135 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00006136 return;
6137 }
6138
6139 // Fill in the rest of the conversions.
6140 unsigned NumArgsInProto = Proto->getNumArgs();
6141 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6142 if (ArgIdx < NumArgsInProto)
6143 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006144 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6145 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006146 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00006147 else
6148 Cand->Conversions[ConvIdx].setEllipsis();
6149 }
6150}
6151
John McCalld3224162010-01-08 00:58:21 +00006152} // end anonymous namespace
6153
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006154/// PrintOverloadCandidates - When overload resolution fails, prints
6155/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00006156/// set.
John McCall5c32be02010-08-24 20:38:10 +00006157void OverloadCandidateSet::NoteCandidates(Sema &S,
6158 OverloadCandidateDisplayKind OCD,
6159 Expr **Args, unsigned NumArgs,
6160 const char *Opc,
6161 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00006162 // Sort the candidates by viability and position. Sorting directly would
6163 // be prohibitive, so we make a set of pointers and sort those.
6164 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00006165 if (OCD == OCD_AllCandidates) Cands.reserve(size());
6166 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00006167 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00006168 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00006169 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00006170 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006171 if (Cand->Function || Cand->IsSurrogate)
6172 Cands.push_back(Cand);
6173 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6174 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00006175 }
6176 }
6177
John McCallad2587a2010-01-12 00:48:53 +00006178 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00006179 CompareOverloadCandidatesForDisplay(S));
John McCall12f97bc2010-01-08 04:41:39 +00006180
John McCall0d1da222010-01-12 00:44:57 +00006181 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00006182
John McCall12f97bc2010-01-08 04:41:39 +00006183 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall5c32be02010-08-24 20:38:10 +00006184 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006185 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00006186 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6187 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00006188
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006189 // Set an arbitrary limit on the number of candidate functions we'll spam
6190 // the user with. FIXME: This limit should depend on details of the
6191 // candidate list.
6192 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6193 break;
6194 }
6195 ++CandsShown;
6196
John McCalld3224162010-01-08 00:58:21 +00006197 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00006198 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00006199 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00006200 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006201 else {
6202 assert(Cand->Viable &&
6203 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00006204 // Generally we only see ambiguities including viable builtin
6205 // operators if overload resolution got screwed up by an
6206 // ambiguous user-defined conversion.
6207 //
6208 // FIXME: It's quite possible for different conversions to see
6209 // different ambiguities, though.
6210 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00006211 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00006212 ReportedAmbiguousConversions = true;
6213 }
John McCalld3224162010-01-08 00:58:21 +00006214
John McCall0d1da222010-01-12 00:44:57 +00006215 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00006216 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00006217 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006218 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006219
6220 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00006221 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006222}
6223
John McCalla0296f72010-03-19 07:35:19 +00006224static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00006225 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00006226 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006227
John McCalla0296f72010-03-19 07:35:19 +00006228 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006229}
6230
Douglas Gregorcd695e52008-11-10 20:40:00 +00006231/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6232/// an overloaded function (C++ [over.over]), where @p From is an
6233/// expression with overloaded function type and @p ToType is the type
6234/// we're trying to resolve to. For example:
6235///
6236/// @code
6237/// int f(double);
6238/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00006239///
Douglas Gregorcd695e52008-11-10 20:40:00 +00006240/// int (*pfd)(double) = f; // selects f(double)
6241/// @endcode
6242///
6243/// This routine returns the resulting FunctionDecl if it could be
6244/// resolved, and NULL otherwise. When @p Complain is true, this
6245/// routine will emit diagnostics if there is an error.
6246FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006247Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00006248 bool Complain,
6249 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006250 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006251 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006252 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00006253 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006254 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00006255 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006256 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006257 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006258 FunctionType = MemTypePtr->getPointeeType();
6259 IsMember = true;
6260 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006261
Douglas Gregorcd695e52008-11-10 20:40:00 +00006262 // C++ [over.over]p1:
6263 // [...] [Note: any redundant set of parentheses surrounding the
6264 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00006265 // C++ [over.over]p1:
6266 // [...] The overloaded function name can be preceded by the &
6267 // operator.
John McCall7d460512010-08-24 23:26:21 +00006268 // However, remember whether the expression has member-pointer form:
6269 // C++ [expr.unary.op]p4:
6270 // A pointer to member is only formed when an explicit & is used
6271 // and its operand is a qualified-id not enclosed in
6272 // parentheses.
John McCall8d08b9b2010-08-27 09:08:28 +00006273 OverloadExpr::FindResult Ovl = OverloadExpr::find(From);
6274 OverloadExpr *OvlExpr = Ovl.Expression;
John McCall7d460512010-08-24 23:26:21 +00006275
Douglas Gregor064fdb22010-04-14 23:11:21 +00006276 // We expect a pointer or reference to function, or a function pointer.
6277 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6278 if (!FunctionType->isFunctionType()) {
6279 if (Complain)
6280 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6281 << OvlExpr->getName() << ToType;
6282
6283 return 0;
6284 }
6285
John McCall24d18942010-08-24 22:52:39 +00006286 // If the overload expression doesn't have the form of a pointer to
John McCall7d460512010-08-24 23:26:21 +00006287 // member, don't try to convert it to a pointer-to-member type.
John McCall8d08b9b2010-08-27 09:08:28 +00006288 if (IsMember && !Ovl.HasFormOfMemberPointer) {
John McCall24d18942010-08-24 22:52:39 +00006289 if (!Complain) return 0;
6290
6291 // TODO: Should we condition this on whether any functions might
6292 // have matched, or is it more appropriate to do that in callers?
6293 // TODO: a fixit wouldn't hurt.
6294 Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
6295 << ToType << OvlExpr->getSourceRange();
6296 return 0;
6297 }
6298
6299 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6300 if (OvlExpr->hasExplicitTemplateArgs()) {
6301 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6302 ExplicitTemplateArgs = &ETABuffer;
6303 }
6304
Douglas Gregor064fdb22010-04-14 23:11:21 +00006305 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006306
Douglas Gregorcd695e52008-11-10 20:40:00 +00006307 // Look through all of the overloaded functions, searching for one
6308 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00006309 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006310 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
6311
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006312 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00006313 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6314 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006315 // Look through any using declarations to find the underlying function.
6316 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6317
Douglas Gregorcd695e52008-11-10 20:40:00 +00006318 // C++ [over.over]p3:
6319 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00006320 // targets of type "pointer-to-function" or "reference-to-function."
6321 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006322 // type "pointer-to-member-function."
6323 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00006324
Mike Stump11289f42009-09-09 15:08:12 +00006325 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006326 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00006327 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006328 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00006329 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006330 // static when converting to member pointer.
6331 if (Method->isStatic() == IsMember)
6332 continue;
6333 } else if (IsMember)
6334 continue;
Mike Stump11289f42009-09-09 15:08:12 +00006335
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006336 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006337 // If the name is a function template, template argument deduction is
6338 // done (14.8.2.2), and if the argument deduction succeeds, the
6339 // resulting template argument list is used to generate a single
6340 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006341 // overloaded functions considered.
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006342 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor9b146582009-07-08 20:55:45 +00006343 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006344 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00006345 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00006346 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00006347 FunctionType, Specialization, Info)) {
6348 // FIXME: make a note of the failed deduction for diagnostics.
6349 (void)Result;
6350 } else {
Douglas Gregor3a923c2d2009-09-24 23:14:47 +00006351 // FIXME: If the match isn't exact, shouldn't we just drop this as
6352 // a candidate? Find a testcase before changing the code.
Mike Stump11289f42009-09-09 15:08:12 +00006353 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00006354 == Context.getCanonicalType(Specialization->getType()));
John McCalla0296f72010-03-19 07:35:19 +00006355 Matches.push_back(std::make_pair(I.getPair(),
6356 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor9b146582009-07-08 20:55:45 +00006357 }
John McCalld14a8642009-11-21 08:51:07 +00006358
6359 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00006360 }
Mike Stump11289f42009-09-09 15:08:12 +00006361
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006362 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006363 // Skip non-static functions when converting to pointer, and static
6364 // when converting to member pointer.
6365 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00006366 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00006367
6368 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00006369 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00006370 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006371 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006372 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00006373
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006374 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00006375 QualType ResultTy;
6376 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6377 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6378 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00006379 Matches.push_back(std::make_pair(I.getPair(),
6380 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006381 FoundNonTemplateFunction = true;
6382 }
Mike Stump11289f42009-09-09 15:08:12 +00006383 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006384 }
6385
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006386 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00006387 if (Matches.empty()) {
6388 if (Complain) {
6389 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6390 << OvlExpr->getName() << FunctionType;
6391 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6392 E = OvlExpr->decls_end();
6393 I != E; ++I)
6394 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6395 NoteOverloadCandidate(F);
6396 }
6397
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006398 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00006399 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006400 FunctionDecl *Result = Matches[0].second;
John McCall16df1e52010-03-30 21:47:33 +00006401 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006402 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCall58cc69d2010-01-27 01:50:18 +00006403 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00006404 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006405 return Result;
6406 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006407
6408 // C++ [over.over]p4:
6409 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00006410 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006411 // [...] and any given function template specialization F1 is
6412 // eliminated if the set contains a second function template
6413 // specialization whose function template is more specialized
6414 // than the function template of F1 according to the partial
6415 // ordering rules of 14.5.5.2.
6416
6417 // The algorithm specified above is quadratic. We instead use a
6418 // two-pass algorithm (similar to the one used to identify the
6419 // best viable function in an overload set) that identifies the
6420 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00006421
6422 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6423 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6424 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00006425
6426 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00006427 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006428 TPOC_Other, From->getLocStart(),
6429 PDiag(),
6430 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006431 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00006432 PDiag(diag::note_ovl_candidate)
6433 << (unsigned) oc_function_template);
Douglas Gregorbdd7b232010-09-12 08:16:09 +00006434 if (Result == MatchesCopy.end())
6435 return 0;
6436
John McCall58cc69d2010-01-27 01:50:18 +00006437 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00006438 FoundResult = Matches[Result - MatchesCopy.begin()].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00006439 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00006440 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall4fa0d5f2010-05-06 18:15:07 +00006441 DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc());
6442 }
John McCall58cc69d2010-01-27 01:50:18 +00006443 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006444 }
Mike Stump11289f42009-09-09 15:08:12 +00006445
Douglas Gregorfae1d712009-09-26 03:56:17 +00006446 // [...] any function template specializations in the set are
6447 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00006448 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00006449 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00006450 ++I;
6451 else {
John McCalla0296f72010-03-19 07:35:19 +00006452 Matches[I] = Matches[--N];
6453 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00006454 }
6455 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00006456
Mike Stump11289f42009-09-09 15:08:12 +00006457 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006458 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00006459 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006460 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00006461 FoundResult = Matches[0].first;
John McCall4fa0d5f2010-05-06 18:15:07 +00006462 if (Complain) {
John McCalla0296f72010-03-19 07:35:19 +00006463 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
John McCall4fa0d5f2010-05-06 18:15:07 +00006464 DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc());
6465 }
John McCalla0296f72010-03-19 07:35:19 +00006466 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006467 }
Mike Stump11289f42009-09-09 15:08:12 +00006468
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006469 // FIXME: We should probably return the same thing that BestViableFunction
6470 // returns (even if we issue the diagnostics here).
6471 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006472 << Matches[0].second->getDeclName();
6473 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6474 NoteOverloadCandidate(Matches[I].second);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006475 return 0;
6476}
6477
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006478/// \brief Given an expression that refers to an overloaded function, try to
6479/// resolve that overloaded function expression down to a single function.
6480///
6481/// This routine can only resolve template-ids that refer to a single function
6482/// template, where that template-id refers to a single template whose template
6483/// arguments are either provided by the template-id or have defaults,
6484/// as described in C++0x [temp.arg.explicit]p3.
6485FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6486 // C++ [over.over]p1:
6487 // [...] [Note: any redundant set of parentheses surrounding the
6488 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006489 // C++ [over.over]p1:
6490 // [...] The overloaded function name can be preceded by the &
6491 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00006492
6493 if (From->getType() != Context.OverloadTy)
6494 return 0;
6495
John McCall8d08b9b2010-08-27 09:08:28 +00006496 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006497
6498 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00006499 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006500 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00006501
6502 TemplateArgumentListInfo ExplicitTemplateArgs;
6503 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006504
6505 // Look through all of the overloaded functions, searching for one
6506 // whose type matches exactly.
6507 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00006508 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6509 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006510 // C++0x [temp.arg.explicit]p3:
6511 // [...] In contexts where deduction is done and fails, or in contexts
6512 // where deduction is not done, if a template argument list is
6513 // specified and it, along with any default template arguments,
6514 // identifies a single function template specialization, then the
6515 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00006516 FunctionTemplateDecl *FunctionTemplate
6517 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006518
6519 // C++ [over.over]p2:
6520 // If the name is a function template, template argument deduction is
6521 // done (14.8.2.2), and if the argument deduction succeeds, the
6522 // resulting template argument list is used to generate a single
6523 // function template specialization, which is added to the set of
6524 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006525 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006526 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00006527 if (TemplateDeductionResult Result
6528 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6529 Specialization, Info)) {
6530 // FIXME: make a note of the failed deduction for diagnostics.
6531 (void)Result;
6532 continue;
6533 }
6534
6535 // Multiple matches; we can't resolve to a single declaration.
6536 if (Matched)
6537 return 0;
6538
6539 Matched = Specialization;
6540 }
6541
6542 return Matched;
6543}
6544
Douglas Gregorcabea402009-09-22 15:41:20 +00006545/// \brief Add a single candidate to the overload set.
6546static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00006547 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00006548 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006549 Expr **Args, unsigned NumArgs,
6550 OverloadCandidateSet &CandidateSet,
6551 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00006552 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00006553 if (isa<UsingShadowDecl>(Callee))
6554 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6555
Douglas Gregorcabea402009-09-22 15:41:20 +00006556 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00006557 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00006558 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006559 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006560 return;
John McCalld14a8642009-11-21 08:51:07 +00006561 }
6562
6563 if (FunctionTemplateDecl *FuncTemplate
6564 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00006565 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6566 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006567 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00006568 return;
6569 }
6570
6571 assert(false && "unhandled case in overloaded call candidate");
6572
6573 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00006574}
6575
6576/// \brief Add the overload candidates named by callee and/or found by argument
6577/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00006578void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00006579 Expr **Args, unsigned NumArgs,
6580 OverloadCandidateSet &CandidateSet,
6581 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00006582
6583#ifndef NDEBUG
6584 // Verify that ArgumentDependentLookup is consistent with the rules
6585 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00006586 //
Douglas Gregorcabea402009-09-22 15:41:20 +00006587 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6588 // and let Y be the lookup set produced by argument dependent
6589 // lookup (defined as follows). If X contains
6590 //
6591 // -- a declaration of a class member, or
6592 //
6593 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00006594 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00006595 //
6596 // -- a declaration that is neither a function or a function
6597 // template
6598 //
6599 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00006600
John McCall57500772009-12-16 12:17:52 +00006601 if (ULE->requiresADL()) {
6602 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6603 E = ULE->decls_end(); I != E; ++I) {
6604 assert(!(*I)->getDeclContext()->isRecord());
6605 assert(isa<UsingShadowDecl>(*I) ||
6606 !(*I)->getDeclContext()->isFunctionOrMethod());
6607 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00006608 }
6609 }
6610#endif
6611
John McCall57500772009-12-16 12:17:52 +00006612 // It would be nice to avoid this copy.
6613 TemplateArgumentListInfo TABuffer;
6614 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6615 if (ULE->hasExplicitTemplateArgs()) {
6616 ULE->copyTemplateArgumentsInto(TABuffer);
6617 ExplicitTemplateArgs = &TABuffer;
6618 }
6619
6620 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6621 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00006622 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00006623 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00006624 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00006625
John McCall57500772009-12-16 12:17:52 +00006626 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00006627 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6628 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006629 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006630 CandidateSet,
6631 PartialOverloading);
6632}
John McCalld681c392009-12-16 08:11:27 +00006633
6634/// Attempts to recover from a call where no functions were found.
6635///
6636/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00006637static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006638BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00006639 UnresolvedLookupExpr *ULE,
6640 SourceLocation LParenLoc,
6641 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00006642 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00006643
6644 CXXScopeSpec SS;
6645 if (ULE->getQualifier()) {
6646 SS.setScopeRep(ULE->getQualifier());
6647 SS.setRange(ULE->getQualifierRange());
6648 }
6649
John McCall57500772009-12-16 12:17:52 +00006650 TemplateArgumentListInfo TABuffer;
6651 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6652 if (ULE->hasExplicitTemplateArgs()) {
6653 ULE->copyTemplateArgumentsInto(TABuffer);
6654 ExplicitTemplateArgs = &TABuffer;
6655 }
6656
John McCalld681c392009-12-16 08:11:27 +00006657 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6658 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00006659 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCallfaf5fb42010-08-26 23:41:50 +00006660 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00006661
John McCall57500772009-12-16 12:17:52 +00006662 assert(!R.empty() && "lookup results empty despite recovery");
6663
6664 // Build an implicit member call if appropriate. Just drop the
6665 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00006666 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00006667 if ((*R.begin())->isCXXClassMember())
6668 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6669 else if (ExplicitTemplateArgs)
6670 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6671 else
6672 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6673
6674 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00006675 return ExprError();
John McCall57500772009-12-16 12:17:52 +00006676
6677 // This shouldn't cause an infinite loop because we're giving it
6678 // an expression with non-empty lookup results, which should never
6679 // end up here.
John McCallb268a282010-08-23 23:25:46 +00006680 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00006681 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006682}
Douglas Gregor4038cf42010-06-08 17:35:15 +00006683
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006684/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00006685/// (which eventually refers to the declaration Func) and the call
6686/// arguments Args/NumArgs, attempt to resolve the function call down
6687/// to a specific function. If overload resolution succeeds, returns
6688/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00006689/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006690/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00006691ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006692Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00006693 SourceLocation LParenLoc,
6694 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00006695 SourceLocation RParenLoc) {
6696#ifndef NDEBUG
6697 if (ULE->requiresADL()) {
6698 // To do ADL, we must have found an unqualified name.
6699 assert(!ULE->getQualifier() && "qualified name with ADL");
6700
6701 // We don't perform ADL for implicit declarations of builtins.
6702 // Verify that this was correctly set up.
6703 FunctionDecl *F;
6704 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6705 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6706 F->getBuiltinID() && F->isImplicit())
6707 assert(0 && "performing ADL for builtin");
6708
6709 // We don't perform ADL in C.
6710 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6711 }
6712#endif
6713
John McCallbc077cf2010-02-08 23:07:23 +00006714 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00006715
John McCall57500772009-12-16 12:17:52 +00006716 // Add the functions denoted by the callee to the set of candidate
6717 // functions, including those from argument-dependent lookup.
6718 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00006719
6720 // If we found nothing, try to recover.
6721 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6722 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00006723 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00006724 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00006725 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00006726
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006727 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006728 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00006729 case OR_Success: {
6730 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00006731 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00006732 DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00006733 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall57500772009-12-16 12:17:52 +00006734 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6735 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006736
6737 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00006738 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006739 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00006740 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00006741 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006742 break;
6743
6744 case OR_Ambiguous:
6745 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00006746 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00006747 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006748 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00006749
6750 case OR_Deleted:
6751 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6752 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00006753 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00006754 << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00006755 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00006756 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006757 }
6758
Douglas Gregorb412e172010-07-25 18:17:45 +00006759 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00006760 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00006761}
6762
John McCall4c4c1df2010-01-26 03:27:55 +00006763static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00006764 return Functions.size() > 1 ||
6765 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6766}
6767
Douglas Gregor084d8552009-03-13 23:49:33 +00006768/// \brief Create a unary operation that may resolve to an overloaded
6769/// operator.
6770///
6771/// \param OpLoc The location of the operator itself (e.g., '*').
6772///
6773/// \param OpcIn The UnaryOperator::Opcode that describes this
6774/// operator.
6775///
6776/// \param Functions The set of non-member functions that will be
6777/// considered by overload resolution. The caller needs to build this
6778/// set based on the context using, e.g.,
6779/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6780/// set should not contain any member functions; those will be added
6781/// by CreateOverloadedUnaryOp().
6782///
6783/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00006784ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00006785Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6786 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00006787 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006788 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00006789
6790 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6791 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6792 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006793 // TODO: provide better source location info.
6794 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006795
6796 Expr *Args[2] = { Input, 0 };
6797 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00006798
Douglas Gregor084d8552009-03-13 23:49:33 +00006799 // For post-increment and post-decrement, add the implicit '0' as
6800 // the second argument, so that we know this is a post-increment or
6801 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00006802 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006803 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00006804 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
6805 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00006806 NumArgs = 2;
6807 }
6808
6809 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00006810 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00006811 return Owned(new (Context) UnaryOperator(Input,
Douglas Gregor630dec52010-06-17 15:46:20 +00006812 Opc,
6813 Context.DependentTy,
6814 OpLoc));
6815
John McCall58cc69d2010-01-27 01:50:18 +00006816 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00006817 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006818 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006819 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006820 /*ADL*/ true, IsOverloaded(Fns),
6821 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00006822 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6823 &Args[0], NumArgs,
6824 Context.DependentTy,
6825 OpLoc));
6826 }
6827
6828 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00006829 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006830
6831 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00006832 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00006833
6834 // Add operator candidates that are member functions.
6835 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6836
John McCall4c4c1df2010-01-26 03:27:55 +00006837 // Add candidates from ADL.
6838 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00006839 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00006840 /*ExplicitTemplateArgs*/ 0,
6841 CandidateSet);
6842
Douglas Gregor084d8552009-03-13 23:49:33 +00006843 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00006844 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00006845
6846 // Perform overload resolution.
6847 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00006848 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00006849 case OR_Success: {
6850 // We found a built-in operator or an overloaded operator.
6851 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00006852
Douglas Gregor084d8552009-03-13 23:49:33 +00006853 if (FnDecl) {
6854 // We matched an overloaded operator. Build a call to that
6855 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00006856
Douglas Gregor084d8552009-03-13 23:49:33 +00006857 // Convert the arguments.
6858 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00006859 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00006860
John McCall16df1e52010-03-30 21:47:33 +00006861 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6862 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00006863 return ExprError();
6864 } else {
6865 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00006866 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00006867 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00006868 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00006869 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00006870 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00006871 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00006872 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00006873 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00006874 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00006875 }
6876
John McCall4fa0d5f2010-05-06 18:15:07 +00006877 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6878
Douglas Gregor084d8552009-03-13 23:49:33 +00006879 // Determine the result type
Douglas Gregor603d81b2010-07-13 08:18:22 +00006880 QualType ResultTy = FnDecl->getCallResultType();
Mike Stump11289f42009-09-09 15:08:12 +00006881
Douglas Gregor084d8552009-03-13 23:49:33 +00006882 // Build the actual expression node.
6883 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6884 SourceLocation());
6885 UsualUnaryConversions(FnExpr);
Mike Stump11289f42009-09-09 15:08:12 +00006886
Eli Friedman030eee42009-11-18 03:58:17 +00006887 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00006888 CallExpr *TheCall =
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006889 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCallb268a282010-08-23 23:25:46 +00006890 Args, NumArgs, ResultTy, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00006891
John McCallb268a282010-08-23 23:25:46 +00006892 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00006893 FnDecl))
6894 return ExprError();
6895
John McCallb268a282010-08-23 23:25:46 +00006896 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00006897 } else {
6898 // We matched a built-in operator. Convert the arguments, then
6899 // break out so that we will build the appropriate built-in
6900 // operator node.
6901 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00006902 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00006903 return ExprError();
6904
6905 break;
6906 }
6907 }
6908
6909 case OR_No_Viable_Function:
6910 // No viable function; fall through to handling this as a
6911 // built-in operator, which will produce an error message for us.
6912 break;
6913
6914 case OR_Ambiguous:
6915 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6916 << UnaryOperator::getOpcodeStr(Opc)
6917 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00006918 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
6919 Args, NumArgs,
6920 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00006921 return ExprError();
6922
6923 case OR_Deleted:
6924 Diag(OpLoc, diag::err_ovl_deleted_oper)
6925 << Best->Function->isDeleted()
6926 << UnaryOperator::getOpcodeStr(Opc)
6927 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00006928 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00006929 return ExprError();
6930 }
6931
6932 // Either we found no viable overloaded operator or we matched a
6933 // built-in operator. In either case, fall through to trying to
6934 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00006935 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00006936}
6937
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006938/// \brief Create a binary operation that may resolve to an overloaded
6939/// operator.
6940///
6941/// \param OpLoc The location of the operator itself (e.g., '+').
6942///
6943/// \param OpcIn The BinaryOperator::Opcode that describes this
6944/// operator.
6945///
6946/// \param Functions The set of non-member functions that will be
6947/// considered by overload resolution. The caller needs to build this
6948/// set based on the context using, e.g.,
6949/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6950/// set should not contain any member functions; those will be added
6951/// by CreateOverloadedBinOp().
6952///
6953/// \param LHS Left-hand argument.
6954/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00006955ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006956Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00006957 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00006958 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006959 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006960 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00006961 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006962
6963 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6964 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6965 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6966
6967 // If either side is type-dependent, create an appropriate dependent
6968 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00006969 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00006970 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00006971 // If there are no functions to store, just build a dependent
6972 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00006973 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00006974 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6975 Context.DependentTy, OpLoc));
6976
6977 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6978 Context.DependentTy,
6979 Context.DependentTy,
6980 Context.DependentTy,
6981 OpLoc));
6982 }
John McCall4c4c1df2010-01-26 03:27:55 +00006983
6984 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00006985 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006986 // TODO: provide better source location info in DNLoc component.
6987 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00006988 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00006989 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00006990 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00006991 /*ADL*/ true, IsOverloaded(Fns),
6992 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006993 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00006994 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00006995 Context.DependentTy,
6996 OpLoc));
6997 }
6998
6999 // If this is the .* operator, which is not overloadable, just
7000 // create a built-in binary operator.
John McCalle3027922010-08-25 11:45:40 +00007001 if (Opc == BO_PtrMemD)
Douglas Gregore9899d92009-08-26 17:08:25 +00007002 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007003
Sebastian Redl6a96bf72009-11-18 23:10:33 +00007004 // If this is the assignment operator, we only perform overload resolution
7005 // if the left-hand side is a class or enumeration type. This is actually
7006 // a hack. The standard requires that we do overload resolution between the
7007 // various built-in candidates, but as DR507 points out, this can lead to
7008 // problems. So we do it this way, which pretty much follows what GCC does.
7009 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00007010 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00007011 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007012
Douglas Gregor084d8552009-03-13 23:49:33 +00007013 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007014 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007015
7016 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00007017 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007018
7019 // Add operator candidates that are member functions.
7020 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
7021
John McCall4c4c1df2010-01-26 03:27:55 +00007022 // Add candidates from ADL.
7023 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
7024 Args, 2,
7025 /*ExplicitTemplateArgs*/ 0,
7026 CandidateSet);
7027
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007028 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007029 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007030
7031 // Perform overload resolution.
7032 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007033 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00007034 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007035 // We found a built-in operator or an overloaded operator.
7036 FunctionDecl *FnDecl = Best->Function;
7037
7038 if (FnDecl) {
7039 // We matched an overloaded operator. Build a call to that
7040 // operator.
7041
7042 // Convert the arguments.
7043 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00007044 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00007045 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007046
John McCalldadc5752010-08-24 06:29:42 +00007047 ExprResult Arg1
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007048 = PerformCopyInitialization(
7049 InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007050 Context,
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007051 FnDecl->getParamDecl(0)),
7052 SourceLocation(),
7053 Owned(Args[1]));
7054 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007055 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007056
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007057 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007058 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007059 return ExprError();
7060
7061 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007062 } else {
7063 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007064 ExprResult Arg0
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007065 = PerformCopyInitialization(
7066 InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007067 Context,
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007068 FnDecl->getParamDecl(0)),
7069 SourceLocation(),
7070 Owned(Args[0]));
7071 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007072 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007073
John McCalldadc5752010-08-24 06:29:42 +00007074 ExprResult Arg1
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007075 = PerformCopyInitialization(
7076 InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007077 Context,
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007078 FnDecl->getParamDecl(1)),
7079 SourceLocation(),
7080 Owned(Args[1]));
7081 if (Arg1.isInvalid())
7082 return ExprError();
7083 Args[0] = LHS = Arg0.takeAs<Expr>();
7084 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007085 }
7086
John McCall4fa0d5f2010-05-06 18:15:07 +00007087 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7088
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007089 // Determine the result type
7090 QualType ResultTy
Douglas Gregor603d81b2010-07-13 08:18:22 +00007091 = FnDecl->getType()->getAs<FunctionType>()
7092 ->getCallResultType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007093
7094 // Build the actual expression node.
7095 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidisef1c1e52009-07-14 03:19:38 +00007096 OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007097 UsualUnaryConversions(FnExpr);
7098
John McCallb268a282010-08-23 23:25:46 +00007099 CXXOperatorCallExpr *TheCall =
7100 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
7101 Args, 2, ResultTy, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007102
John McCallb268a282010-08-23 23:25:46 +00007103 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007104 FnDecl))
7105 return ExprError();
7106
John McCallb268a282010-08-23 23:25:46 +00007107 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007108 } else {
7109 // We matched a built-in operator. Convert the arguments, then
7110 // break out so that we will build the appropriate built-in
7111 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00007112 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007113 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00007114 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007115 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007116 return ExprError();
7117
7118 break;
7119 }
7120 }
7121
Douglas Gregor66950a32009-09-30 21:46:01 +00007122 case OR_No_Viable_Function: {
7123 // C++ [over.match.oper]p9:
7124 // If the operator is the operator , [...] and there are no
7125 // viable functions, then the operator is assumed to be the
7126 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00007127 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00007128 break;
7129
Sebastian Redl027de2a2009-05-21 11:50:50 +00007130 // For class as left operand for assignment or compound assigment operator
7131 // do not fall through to handling in built-in, but report that no overloaded
7132 // assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00007133 ExprResult Result = ExprError();
Douglas Gregor66950a32009-09-30 21:46:01 +00007134 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00007135 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00007136 Diag(OpLoc, diag::err_ovl_no_viable_oper)
7137 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007138 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00007139 } else {
7140 // No viable function; try to create a built-in operation, which will
7141 // produce an error. Then, show the non-viable candidates.
7142 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00007143 }
Douglas Gregor66950a32009-09-30 21:46:01 +00007144 assert(Result.isInvalid() &&
7145 "C++ binary operator overloading is missing candidates!");
7146 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00007147 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7148 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00007149 return move(Result);
7150 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007151
7152 case OR_Ambiguous:
7153 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
7154 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007155 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007156 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7157 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007158 return ExprError();
7159
7160 case OR_Deleted:
7161 Diag(OpLoc, diag::err_ovl_deleted_oper)
7162 << Best->Function->isDeleted()
7163 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007164 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007165 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007166 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00007167 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007168
Douglas Gregor66950a32009-09-30 21:46:01 +00007169 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00007170 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007171}
7172
John McCalldadc5752010-08-24 06:29:42 +00007173ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00007174Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7175 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00007176 Expr *Base, Expr *Idx) {
7177 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00007178 DeclarationName OpName =
7179 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7180
7181 // If either side is type-dependent, create an appropriate dependent
7182 // expression.
7183 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7184
John McCall58cc69d2010-01-27 01:50:18 +00007185 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007186 // CHECKME: no 'operator' keyword?
7187 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7188 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00007189 UnresolvedLookupExpr *Fn
John McCall58cc69d2010-01-27 01:50:18 +00007190 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007191 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007192 /*ADL*/ true, /*Overloaded*/ false,
7193 UnresolvedSetIterator(),
7194 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00007195 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00007196
Sebastian Redladba46e2009-10-29 20:17:01 +00007197 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7198 Args, 2,
7199 Context.DependentTy,
7200 RLoc));
7201 }
7202
7203 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007204 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007205
7206 // Subscript can only be overloaded as a member function.
7207
7208 // Add operator candidates that are member functions.
7209 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7210
7211 // Add builtin operator candidates.
7212 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7213
7214 // Perform overload resolution.
7215 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007216 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00007217 case OR_Success: {
7218 // We found a built-in operator or an overloaded operator.
7219 FunctionDecl *FnDecl = Best->Function;
7220
7221 if (FnDecl) {
7222 // We matched an overloaded operator. Build a call to that
7223 // operator.
7224
John McCalla0296f72010-03-19 07:35:19 +00007225 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007226 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00007227
Sebastian Redladba46e2009-10-29 20:17:01 +00007228 // Convert the arguments.
7229 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007230 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007231 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00007232 return ExprError();
7233
Anders Carlssona68e51e2010-01-29 18:37:50 +00007234 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007235 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00007236 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007237 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00007238 FnDecl->getParamDecl(0)),
7239 SourceLocation(),
7240 Owned(Args[1]));
7241 if (InputInit.isInvalid())
7242 return ExprError();
7243
7244 Args[1] = InputInit.takeAs<Expr>();
7245
Sebastian Redladba46e2009-10-29 20:17:01 +00007246 // Determine the result type
7247 QualType ResultTy
Douglas Gregor603d81b2010-07-13 08:18:22 +00007248 = FnDecl->getType()->getAs<FunctionType>()
7249 ->getCallResultType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00007250
7251 // Build the actual expression node.
7252 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7253 LLoc);
7254 UsualUnaryConversions(FnExpr);
7255
John McCallb268a282010-08-23 23:25:46 +00007256 CXXOperatorCallExpr *TheCall =
7257 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7258 FnExpr, Args, 2,
7259 ResultTy, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007260
John McCallb268a282010-08-23 23:25:46 +00007261 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00007262 FnDecl))
7263 return ExprError();
7264
John McCallb268a282010-08-23 23:25:46 +00007265 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00007266 } else {
7267 // We matched a built-in operator. Convert the arguments, then
7268 // break out so that we will build the appropriate built-in
7269 // operator node.
7270 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007271 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00007272 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007273 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00007274 return ExprError();
7275
7276 break;
7277 }
7278 }
7279
7280 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00007281 if (CandidateSet.empty())
7282 Diag(LLoc, diag::err_ovl_no_oper)
7283 << Args[0]->getType() << /*subscript*/ 0
7284 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7285 else
7286 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7287 << Args[0]->getType()
7288 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007289 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7290 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00007291 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00007292 }
7293
7294 case OR_Ambiguous:
7295 Diag(LLoc, diag::err_ovl_ambiguous_oper)
7296 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007297 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7298 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007299 return ExprError();
7300
7301 case OR_Deleted:
7302 Diag(LLoc, diag::err_ovl_deleted_oper)
7303 << Best->Function->isDeleted() << "[]"
7304 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007305 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7306 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007307 return ExprError();
7308 }
7309
7310 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00007311 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007312}
7313
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007314/// BuildCallToMemberFunction - Build a call to a member
7315/// function. MemExpr is the expression that refers to the member
7316/// function (and includes the object parameter), Args/NumArgs are the
7317/// arguments to the function call (not including the object
7318/// parameter). The caller needs to validate that the member
7319/// expression refers to a member function or an overloaded member
7320/// function.
John McCalldadc5752010-08-24 06:29:42 +00007321ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00007322Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7323 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007324 unsigned NumArgs, SourceLocation RParenLoc) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007325 // Dig out the member expression. This holds both the object
7326 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00007327 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7328
John McCall10eae182009-11-30 22:42:35 +00007329 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007330 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00007331 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007332 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00007333 if (isa<MemberExpr>(NakedMemExpr)) {
7334 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00007335 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00007336 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007337 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00007338 } else {
7339 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007340 Qualifier = UnresExpr->getQualifier();
7341
John McCall6e9f8f62009-12-03 04:06:58 +00007342 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00007343
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007344 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00007345 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00007346
John McCall2d74de92009-12-01 22:10:20 +00007347 // FIXME: avoid copy.
7348 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7349 if (UnresExpr->hasExplicitTemplateArgs()) {
7350 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7351 TemplateArgs = &TemplateArgsBuffer;
7352 }
7353
John McCall10eae182009-11-30 22:42:35 +00007354 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7355 E = UnresExpr->decls_end(); I != E; ++I) {
7356
John McCall6e9f8f62009-12-03 04:06:58 +00007357 NamedDecl *Func = *I;
7358 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7359 if (isa<UsingShadowDecl>(Func))
7360 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7361
John McCall10eae182009-11-30 22:42:35 +00007362 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00007363 // If explicit template arguments were provided, we can't call a
7364 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00007365 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00007366 continue;
7367
John McCalla0296f72010-03-19 07:35:19 +00007368 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00007369 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007370 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007371 } else {
John McCall10eae182009-11-30 22:42:35 +00007372 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00007373 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007374 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007375 CandidateSet,
7376 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007377 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007378 }
Mike Stump11289f42009-09-09 15:08:12 +00007379
John McCall10eae182009-11-30 22:42:35 +00007380 DeclarationName DeclName = UnresExpr->getMemberName();
7381
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007382 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007383 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
7384 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007385 case OR_Success:
7386 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007387 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00007388 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007389 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007390 break;
7391
7392 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00007393 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007394 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007395 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007396 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007397 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007398 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007399
7400 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00007401 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007402 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007403 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007404 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007405 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007406
7407 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00007408 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00007409 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00007410 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007411 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007412 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007413 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007414 }
7415
John McCall16df1e52010-03-30 21:47:33 +00007416 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00007417
John McCall2d74de92009-12-01 22:10:20 +00007418 // If overload resolution picked a static member, build a
7419 // non-member call based on that function.
7420 if (Method->isStatic()) {
7421 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7422 Args, NumArgs, RParenLoc);
7423 }
7424
John McCall10eae182009-11-30 22:42:35 +00007425 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007426 }
7427
7428 assert(Method && "Member call to something that isn't a method?");
John McCallb268a282010-08-23 23:25:46 +00007429 CXXMemberCallExpr *TheCall =
7430 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
7431 Method->getCallResultType(),
7432 RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007433
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007434 // Check for a valid return type.
7435 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00007436 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00007437 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00007438
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007439 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00007440 // We only need to do this if there was actually an overload; otherwise
7441 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00007442 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00007443 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00007444 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7445 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00007446 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007447 MemExpr->setBase(ObjectArg);
7448
7449 // Convert the rest of the arguments
Douglas Gregorc8be9522010-05-04 18:18:31 +00007450 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00007451 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007452 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00007453 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007454
John McCallb268a282010-08-23 23:25:46 +00007455 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00007456 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00007457
John McCallb268a282010-08-23 23:25:46 +00007458 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007459}
7460
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007461/// BuildCallToObjectOfClassType - Build a call to an object of class
7462/// type (C++ [over.call.object]), which can end up invoking an
7463/// overloaded function call operator (@c operator()) or performing a
7464/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00007465ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00007466Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00007467 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007468 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007469 SourceLocation RParenLoc) {
7470 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007471 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00007472
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007473 // C++ [over.call.object]p1:
7474 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00007475 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007476 // candidate functions includes at least the function call
7477 // operators of T. The function call operators of T are obtained by
7478 // ordinary lookup of the name operator() in the context of
7479 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00007480 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00007481 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007482
7483 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00007484 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007485 << Object->getSourceRange()))
7486 return true;
7487
John McCall27b18f82009-11-17 02:14:36 +00007488 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7489 LookupQualifiedName(R, Record->getDecl());
7490 R.suppressDiagnostics();
7491
Douglas Gregorc473cbb2009-11-15 07:48:03 +00007492 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00007493 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007494 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00007495 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00007496 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00007497 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007498
Douglas Gregorab7897a2008-11-19 22:57:39 +00007499 // C++ [over.call.object]p2:
7500 // In addition, for each conversion function declared in T of the
7501 // form
7502 //
7503 // operator conversion-type-id () cv-qualifier;
7504 //
7505 // where cv-qualifier is the same cv-qualification as, or a
7506 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00007507 // denotes the type "pointer to function of (P1,...,Pn) returning
7508 // R", or the type "reference to pointer to function of
7509 // (P1,...,Pn) returning R", or the type "reference to function
7510 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00007511 // is also considered as a candidate function. Similarly,
7512 // surrogate call functions are added to the set of candidate
7513 // functions for each conversion function declared in an
7514 // accessible base class provided the function is not hidden
7515 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00007516 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00007517 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00007518 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00007519 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00007520 NamedDecl *D = *I;
7521 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7522 if (isa<UsingShadowDecl>(D))
7523 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7524
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007525 // Skip over templated conversion functions; they aren't
7526 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00007527 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007528 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00007529
John McCall6e9f8f62009-12-03 04:06:58 +00007530 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00007531
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007532 // Strip the reference type (if any) and then the pointer type (if
7533 // any) to get down to what might be a function type.
7534 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7535 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7536 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00007537
Douglas Gregor74ba25c2009-10-21 06:18:39 +00007538 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00007539 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00007540 Object->getType(), Args, NumArgs,
7541 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007542 }
Mike Stump11289f42009-09-09 15:08:12 +00007543
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007544 // Perform overload resolution.
7545 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007546 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
7547 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007548 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00007549 // Overload resolution succeeded; we'll build the appropriate call
7550 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007551 break;
7552
7553 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00007554 if (CandidateSet.empty())
7555 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7556 << Object->getType() << /*call*/ 1
7557 << Object->getSourceRange();
7558 else
7559 Diag(Object->getSourceRange().getBegin(),
7560 diag::err_ovl_no_viable_object_call)
7561 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007562 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007563 break;
7564
7565 case OR_Ambiguous:
7566 Diag(Object->getSourceRange().getBegin(),
7567 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00007568 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007569 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007570 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007571
7572 case OR_Deleted:
7573 Diag(Object->getSourceRange().getBegin(),
7574 diag::err_ovl_deleted_object_call)
7575 << Best->Function->isDeleted()
7576 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007577 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007578 break;
Mike Stump11289f42009-09-09 15:08:12 +00007579 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007580
Douglas Gregorb412e172010-07-25 18:17:45 +00007581 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007582 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007583
Douglas Gregorab7897a2008-11-19 22:57:39 +00007584 if (Best->Function == 0) {
7585 // Since there is no function declaration, this is one of the
7586 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00007587 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00007588 = cast<CXXConversionDecl>(
7589 Best->Conversions[0].UserDefined.ConversionFunction);
7590
John McCalla0296f72010-03-19 07:35:19 +00007591 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007592 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007593
Douglas Gregorab7897a2008-11-19 22:57:39 +00007594 // We selected one of the surrogate functions that converts the
7595 // object parameter to a function pointer. Perform the conversion
7596 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00007597
7598 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007599 // and then call it.
John McCall16df1e52010-03-30 21:47:33 +00007600 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7601 Conv);
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00007602
John McCallfaf5fb42010-08-26 23:41:50 +00007603 return ActOnCallExpr(S, CE, LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00007604 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00007605 }
7606
John McCalla0296f72010-03-19 07:35:19 +00007607 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007608 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00007609
Douglas Gregorab7897a2008-11-19 22:57:39 +00007610 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7611 // that calls this method, using Object for the implicit object
7612 // parameter and passing along the remaining arguments.
7613 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall9dd450b2009-09-21 23:43:11 +00007614 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007615
7616 unsigned NumArgsInProto = Proto->getNumArgs();
7617 unsigned NumArgsToCheck = NumArgs;
7618
7619 // Build the full argument list for the method call (the
7620 // implicit object parameter is placed at the beginning of the
7621 // list).
7622 Expr **MethodArgs;
7623 if (NumArgs < NumArgsInProto) {
7624 NumArgsToCheck = NumArgsInProto;
7625 MethodArgs = new Expr*[NumArgsInProto + 1];
7626 } else {
7627 MethodArgs = new Expr*[NumArgs + 1];
7628 }
7629 MethodArgs[0] = Object;
7630 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7631 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00007632
7633 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek5a201952009-02-07 01:47:29 +00007634 SourceLocation());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007635 UsualUnaryConversions(NewFn);
7636
7637 // Once we've built TheCall, all of the expressions are properly
7638 // owned.
Douglas Gregor603d81b2010-07-13 08:18:22 +00007639 QualType ResultTy = Method->getCallResultType();
John McCallb268a282010-08-23 23:25:46 +00007640 CXXOperatorCallExpr *TheCall =
7641 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
7642 MethodArgs, NumArgs + 1,
7643 ResultTy, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007644 delete [] MethodArgs;
7645
John McCallb268a282010-08-23 23:25:46 +00007646 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00007647 Method))
7648 return true;
7649
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007650 // We may have default arguments. If so, we need to allocate more
7651 // slots in the call for them.
7652 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00007653 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007654 else if (NumArgs > NumArgsInProto)
7655 NumArgsToCheck = NumArgsInProto;
7656
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007657 bool IsError = false;
7658
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007659 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007660 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007661 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007662 TheCall->setArg(0, Object);
7663
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007664
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007665 // Check the argument types.
7666 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007667 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007668 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007669 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00007670
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007671 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007672
John McCalldadc5752010-08-24 06:29:42 +00007673 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007674 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007675 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007676 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00007677 SourceLocation(), Arg);
Anders Carlsson7c5fe482010-01-29 18:43:53 +00007678
7679 IsError |= InputInit.isInvalid();
7680 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007681 } else {
John McCalldadc5752010-08-24 06:29:42 +00007682 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00007683 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7684 if (DefArg.isInvalid()) {
7685 IsError = true;
7686 break;
7687 }
7688
7689 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00007690 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007691
7692 TheCall->setArg(i + 1, Arg);
7693 }
7694
7695 // If this is a variadic call, handle args passed through "...".
7696 if (Proto->isVariadic()) {
7697 // Promote the arguments (C99 6.5.2.2p7).
7698 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7699 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00007700 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007701 TheCall->setArg(i + 1, Arg);
7702 }
7703 }
7704
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00007705 if (IsError) return true;
7706
John McCallb268a282010-08-23 23:25:46 +00007707 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00007708 return true;
7709
John McCalle172be52010-08-24 06:09:16 +00007710 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00007711}
7712
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007713/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00007714/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007715/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00007716ExprResult
John McCallb268a282010-08-23 23:25:46 +00007717Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007718 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00007719
John McCallbc077cf2010-02-08 23:07:23 +00007720 SourceLocation Loc = Base->getExprLoc();
7721
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007722 // C++ [over.ref]p1:
7723 //
7724 // [...] An expression x->m is interpreted as (x.operator->())->m
7725 // for a class object x of type T if T::operator->() exists and if
7726 // the operator is selected as the best match function by the
7727 // overload resolution mechanism (13.3).
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007728 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00007729 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00007730 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00007731
John McCallbc077cf2010-02-08 23:07:23 +00007732 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00007733 PDiag(diag::err_typecheck_incomplete_tag)
7734 << Base->getSourceRange()))
7735 return ExprError();
7736
John McCall27b18f82009-11-17 02:14:36 +00007737 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7738 LookupQualifiedName(R, BaseRecord->getDecl());
7739 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00007740
7741 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00007742 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00007743 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007744 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00007745 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007746
7747 // Perform overload resolution.
7748 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007749 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007750 case OR_Success:
7751 // Overload resolution succeeded; we'll build the call below.
7752 break;
7753
7754 case OR_No_Viable_Function:
7755 if (CandidateSet.empty())
7756 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00007757 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007758 else
7759 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00007760 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007761 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007762 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007763
7764 case OR_Ambiguous:
7765 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlsson78b54932009-09-10 23:18:36 +00007766 << "->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007767 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007768 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007769
7770 case OR_Deleted:
7771 Diag(OpLoc, diag::err_ovl_deleted_oper)
7772 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00007773 << "->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007774 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00007775 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007776 }
7777
John McCalla0296f72010-03-19 07:35:19 +00007778 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007779 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00007780
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007781 // Convert the object parameter.
7782 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007783 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7784 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00007785 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00007786
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007787 // Build the operator call.
Ted Kremenek5a201952009-02-07 01:47:29 +00007788 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7789 SourceLocation());
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007790 UsualUnaryConversions(FnExpr);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007791
Douglas Gregor603d81b2010-07-13 08:18:22 +00007792 QualType ResultTy = Method->getCallResultType();
John McCallb268a282010-08-23 23:25:46 +00007793 CXXOperatorCallExpr *TheCall =
7794 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7795 &Base, 1, ResultTy, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007796
John McCallb268a282010-08-23 23:25:46 +00007797 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007798 Method))
7799 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00007800 return Owned(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00007801}
7802
Douglas Gregorcd695e52008-11-10 20:40:00 +00007803/// FixOverloadedFunctionReference - E is an expression that refers to
7804/// a C++ overloaded function (possibly with some parentheses and
7805/// perhaps a '&' around it). We have resolved the overloaded function
7806/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007807/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00007808Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00007809 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00007810 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007811 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7812 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007813 if (SubExpr == PE->getSubExpr())
7814 return PE->Retain();
7815
7816 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7817 }
7818
7819 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00007820 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7821 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00007822 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00007823 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00007824 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00007825 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00007826 if (SubExpr == ICE->getSubExpr())
7827 return ICE->Retain();
7828
John McCallcf142162010-08-07 06:22:56 +00007829 return ImplicitCastExpr::Create(Context, ICE->getType(),
7830 ICE->getCastKind(),
7831 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00007832 ICE->getValueKind());
Douglas Gregor51c538b2009-11-20 19:42:02 +00007833 }
7834
7835 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +00007836 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00007837 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007838 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7839 if (Method->isStatic()) {
7840 // Do nothing: static member functions aren't any different
7841 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00007842 } else {
John McCalle66edc12009-11-24 19:00:30 +00007843 // Fix the sub expression, which really has to be an
7844 // UnresolvedLookupExpr holding an overloaded member function
7845 // or template.
John McCall16df1e52010-03-30 21:47:33 +00007846 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7847 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00007848 if (SubExpr == UnOp->getSubExpr())
7849 return UnOp->Retain();
Douglas Gregor51c538b2009-11-20 19:42:02 +00007850
John McCalld14a8642009-11-21 08:51:07 +00007851 assert(isa<DeclRefExpr>(SubExpr)
7852 && "fixed to something other than a decl ref");
7853 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7854 && "fixed to a member ref with no nested name qualifier");
7855
7856 // We have taken the address of a pointer to member
7857 // function. Perform the computation here so that we get the
7858 // appropriate pointer to member type.
7859 QualType ClassType
7860 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7861 QualType MemPtrType
7862 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7863
John McCalle3027922010-08-25 11:45:40 +00007864 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
John McCalld14a8642009-11-21 08:51:07 +00007865 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00007866 }
7867 }
John McCall16df1e52010-03-30 21:47:33 +00007868 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7869 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00007870 if (SubExpr == UnOp->getSubExpr())
7871 return UnOp->Retain();
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00007872
John McCalle3027922010-08-25 11:45:40 +00007873 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007874 Context.getPointerType(SubExpr->getType()),
7875 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00007876 }
John McCalld14a8642009-11-21 08:51:07 +00007877
7878 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00007879 // FIXME: avoid copy.
7880 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00007881 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00007882 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7883 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00007884 }
7885
John McCalld14a8642009-11-21 08:51:07 +00007886 return DeclRefExpr::Create(Context,
7887 ULE->getQualifier(),
7888 ULE->getQualifierRange(),
7889 Fn,
7890 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00007891 Fn->getType(),
7892 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00007893 }
7894
John McCall10eae182009-11-30 22:42:35 +00007895 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00007896 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00007897 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7898 if (MemExpr->hasExplicitTemplateArgs()) {
7899 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7900 TemplateArgs = &TemplateArgsBuffer;
7901 }
John McCall6b51f282009-11-23 01:53:49 +00007902
John McCall2d74de92009-12-01 22:10:20 +00007903 Expr *Base;
7904
7905 // If we're filling in
7906 if (MemExpr->isImplicitAccess()) {
7907 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7908 return DeclRefExpr::Create(Context,
7909 MemExpr->getQualifier(),
7910 MemExpr->getQualifierRange(),
7911 Fn,
7912 MemExpr->getMemberLoc(),
7913 Fn->getType(),
7914 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00007915 } else {
7916 SourceLocation Loc = MemExpr->getMemberLoc();
7917 if (MemExpr->getQualifier())
7918 Loc = MemExpr->getQualifierRange().getBegin();
7919 Base = new (Context) CXXThisExpr(Loc,
7920 MemExpr->getBaseType(),
7921 /*isImplicit=*/true);
7922 }
John McCall2d74de92009-12-01 22:10:20 +00007923 } else
7924 Base = MemExpr->getBase()->Retain();
7925
7926 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007927 MemExpr->isArrow(),
7928 MemExpr->getQualifier(),
7929 MemExpr->getQualifierRange(),
7930 Fn,
John McCall16df1e52010-03-30 21:47:33 +00007931 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007932 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00007933 TemplateArgs,
Douglas Gregor51c538b2009-11-20 19:42:02 +00007934 Fn->getType());
7935 }
7936
Douglas Gregor51c538b2009-11-20 19:42:02 +00007937 assert(false && "Invalid reference to overloaded function");
7938 return E->Retain();
Douglas Gregorcd695e52008-11-10 20:40:00 +00007939}
7940
John McCalldadc5752010-08-24 06:29:42 +00007941ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
7942 DeclAccessPair Found,
7943 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00007944 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00007945}
7946
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007947} // end namespace clang