blob: 25a3a2e9d099f794302d88e31c7f9085b18e0e27 [file] [log] [blame]
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
Douglas Gregore737f502010-08-12 20:07:10 +000014#include "clang/Sema/Sema.h"
15#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000017#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000018#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000019#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000020#include "clang/AST/CXXInheritance.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000021#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000022#include "clang/AST/ExprCXX.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000023#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000024#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000025#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000026#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000027#include <algorithm>
28
29namespace clang {
30
31/// GetConversionCategory - Retrieve the implicit conversion
32/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000033ImplicitConversionCategory
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000034GetConversionCategory(ImplicitConversionKind Kind) {
35 static const ImplicitConversionCategory
36 Category[(int)ICK_Num_Conversion_Kinds] = {
37 ICC_Identity,
38 ICC_Lvalue_Transformation,
39 ICC_Lvalue_Transformation,
40 ICC_Lvalue_Transformation,
Douglas Gregor43c79c22009-12-09 00:47:37 +000041 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000042 ICC_Qualification_Adjustment,
43 ICC_Promotion,
44 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000045 ICC_Promotion,
46 ICC_Conversion,
47 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000048 ICC_Conversion,
49 ICC_Conversion,
50 ICC_Conversion,
51 ICC_Conversion,
52 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000053 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000054 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +000055 ICC_Conversion,
56 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000057 ICC_Conversion
58 };
59 return Category[(int)Kind];
60}
61
62/// GetConversionRank - Retrieve the implicit conversion rank
63/// corresponding to the given implicit conversion kind.
64ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
65 static const ImplicitConversionRank
66 Rank[(int)ICK_Num_Conversion_Kinds] = {
67 ICR_Exact_Match,
68 ICR_Exact_Match,
69 ICR_Exact_Match,
70 ICR_Exact_Match,
71 ICR_Exact_Match,
Douglas Gregor43c79c22009-12-09 00:47:37 +000072 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000073 ICR_Promotion,
74 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +000075 ICR_Promotion,
76 ICR_Conversion,
77 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000078 ICR_Conversion,
79 ICR_Conversion,
80 ICR_Conversion,
81 ICR_Conversion,
82 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +000083 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +000084 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +000085 ICR_Conversion,
86 ICR_Conversion,
Chandler Carruth23a370f2010-02-25 07:20:54 +000087 ICR_Complex_Real_Conversion
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000088 };
89 return Rank[(int)Kind];
90}
91
92/// GetImplicitConversionName - Return the name of this kind of
93/// implicit conversion.
94const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopes2550d702009-12-23 17:49:57 +000095 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000096 "No conversion",
97 "Lvalue-to-rvalue",
98 "Array-to-pointer",
99 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000100 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000101 "Qualification",
102 "Integral promotion",
103 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000104 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000105 "Integral conversion",
106 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000107 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000108 "Floating-integral conversion",
109 "Pointer conversion",
110 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000111 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000112 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000113 "Derived-to-base conversion",
114 "Vector conversion",
115 "Vector splat",
116 "Complex-real conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000117 };
118 return Name[Kind];
119}
120
Douglas Gregor60d62c22008-10-31 16:23:19 +0000121/// StandardConversionSequence - Set the standard conversion
122/// sequence to the identity conversion.
123void StandardConversionSequence::setAsIdentityConversion() {
124 First = ICK_Identity;
125 Second = ICK_Identity;
126 Third = ICK_Identity;
Douglas Gregora9bff302010-02-28 18:30:25 +0000127 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000128 ReferenceBinding = false;
129 DirectBinding = false;
Sebastian Redl85002392009-03-29 22:46:24 +0000130 RRefBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000131 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000132}
133
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000134/// getRank - Retrieve the rank of this standard conversion sequence
135/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
136/// implicit conversions.
137ImplicitConversionRank StandardConversionSequence::getRank() const {
138 ImplicitConversionRank Rank = ICR_Exact_Match;
139 if (GetConversionRank(First) > Rank)
140 Rank = GetConversionRank(First);
141 if (GetConversionRank(Second) > Rank)
142 Rank = GetConversionRank(Second);
143 if (GetConversionRank(Third) > Rank)
144 Rank = GetConversionRank(Third);
145 return Rank;
146}
147
148/// isPointerConversionToBool - Determines whether this conversion is
149/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump1eb44332009-09-09 15:08:12 +0000150/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000151/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000152bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000153 // Note that FromType has not necessarily been transformed by the
154 // array-to-pointer or function-to-pointer implicit conversions, so
155 // check for their presence as well as checking whether FromType is
156 // a pointer.
Douglas Gregorad323a82010-01-27 03:51:04 +0000157 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000158 (getFromType()->isPointerType() ||
159 getFromType()->isObjCObjectPointerType() ||
160 getFromType()->isBlockPointerType() ||
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000161 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
162 return true;
163
164 return false;
165}
166
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000167/// isPointerConversionToVoidPointer - Determines whether this
168/// conversion is a conversion of a pointer to a void pointer. This is
169/// used as part of the ranking of standard conversion sequences (C++
170/// 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000171bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000172StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000173isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000174 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000175 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000176
177 // Note that FromType has not necessarily been transformed by the
178 // array-to-pointer implicit conversion, so check for its presence
179 // and redo the conversion to get a pointer.
180 if (First == ICK_Array_To_Pointer)
181 FromType = Context.getArrayDecayedType(FromType);
182
Douglas Gregor01919692009-12-13 21:37:05 +0000183 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000184 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000185 return ToPtrType->getPointeeType()->isVoidType();
186
187 return false;
188}
189
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000190/// DebugPrint - Print this standard conversion sequence to standard
191/// error. Useful for debugging overloading issues.
192void StandardConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000193 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000194 bool PrintedSomething = false;
195 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000196 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000197 PrintedSomething = true;
198 }
199
200 if (Second != ICK_Identity) {
201 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000202 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000203 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000204 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000205
206 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000207 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000208 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000209 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000210 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000211 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000212 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000213 PrintedSomething = true;
214 }
215
216 if (Third != ICK_Identity) {
217 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000218 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000219 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000220 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000221 PrintedSomething = true;
222 }
223
224 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000225 OS << "No conversions required";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000226 }
227}
228
229/// DebugPrint - Print this user-defined conversion sequence to standard
230/// error. Useful for debugging overloading issues.
231void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000232 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000233 if (Before.First || Before.Second || Before.Third) {
234 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000235 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000236 }
Benjamin Kramer900fc632010-04-17 09:33:03 +0000237 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000238 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000239 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000240 After.DebugPrint();
241 }
242}
243
244/// DebugPrint - Print this implicit conversion sequence to standard
245/// error. Useful for debugging overloading issues.
246void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000247 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000248 switch (ConversionKind) {
249 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000250 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000251 Standard.DebugPrint();
252 break;
253 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000254 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000255 UserDefined.DebugPrint();
256 break;
257 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000258 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000259 break;
John McCall1d318332010-01-12 00:44:57 +0000260 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000261 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000262 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000263 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000264 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000265 break;
266 }
267
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000268 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000269}
270
John McCall1d318332010-01-12 00:44:57 +0000271void AmbiguousConversionSequence::construct() {
272 new (&conversions()) ConversionSet();
273}
274
275void AmbiguousConversionSequence::destruct() {
276 conversions().~ConversionSet();
277}
278
279void
280AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
281 FromTypePtr = O.FromTypePtr;
282 ToTypePtr = O.ToTypePtr;
283 new (&conversions()) ConversionSet(O.conversions());
284}
285
Douglas Gregora9333192010-05-08 17:41:32 +0000286namespace {
287 // Structure used by OverloadCandidate::DeductionFailureInfo to store
288 // template parameter and template argument information.
289 struct DFIParamWithArguments {
290 TemplateParameter Param;
291 TemplateArgument FirstArg;
292 TemplateArgument SecondArg;
293 };
294}
295
296/// \brief Convert from Sema's representation of template deduction information
297/// to the form used in overload-candidate information.
298OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000299static MakeDeductionFailureInfo(ASTContext &Context,
300 Sema::TemplateDeductionResult TDK,
Douglas Gregorec20f462010-05-08 20:07:26 +0000301 Sema::TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000302 OverloadCandidate::DeductionFailureInfo Result;
303 Result.Result = static_cast<unsigned>(TDK);
304 Result.Data = 0;
305 switch (TDK) {
306 case Sema::TDK_Success:
307 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000308 case Sema::TDK_TooManyArguments:
309 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000310 break;
311
312 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000313 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000314 Result.Data = Info.Param.getOpaqueValue();
315 break;
316
Douglas Gregora9333192010-05-08 17:41:32 +0000317 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000318 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000319 // FIXME: Should allocate from normal heap so that we can free this later.
320 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000321 Saved->Param = Info.Param;
322 Saved->FirstArg = Info.FirstArg;
323 Saved->SecondArg = Info.SecondArg;
324 Result.Data = Saved;
325 break;
326 }
327
328 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000329 Result.Data = Info.take();
330 break;
331
Douglas Gregora9333192010-05-08 17:41:32 +0000332 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000333 case Sema::TDK_FailedOverloadResolution:
334 break;
335 }
336
337 return Result;
338}
John McCall1d318332010-01-12 00:44:57 +0000339
Douglas Gregora9333192010-05-08 17:41:32 +0000340void OverloadCandidate::DeductionFailureInfo::Destroy() {
341 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
342 case Sema::TDK_Success:
343 case Sema::TDK_InstantiationDepth:
344 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000345 case Sema::TDK_TooManyArguments:
346 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000347 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000348 break;
349
Douglas Gregora9333192010-05-08 17:41:32 +0000350 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000351 case Sema::TDK_Underqualified:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000352 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000353 Data = 0;
354 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000355
356 case Sema::TDK_SubstitutionFailure:
357 // FIXME: Destroy the template arugment list?
358 Data = 0;
359 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000360
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000361 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000362 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000363 case Sema::TDK_FailedOverloadResolution:
364 break;
365 }
366}
367
368TemplateParameter
369OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
370 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
371 case Sema::TDK_Success:
372 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000373 case Sema::TDK_TooManyArguments:
374 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000375 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000376 return TemplateParameter();
377
378 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000379 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000380 return TemplateParameter::getFromOpaqueValue(Data);
381
382 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000383 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000384 return static_cast<DFIParamWithArguments*>(Data)->Param;
385
386 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000387 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000388 case Sema::TDK_FailedOverloadResolution:
389 break;
390 }
391
392 return TemplateParameter();
393}
Douglas Gregorec20f462010-05-08 20:07:26 +0000394
395TemplateArgumentList *
396OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
397 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
398 case Sema::TDK_Success:
399 case Sema::TDK_InstantiationDepth:
400 case Sema::TDK_TooManyArguments:
401 case Sema::TDK_TooFewArguments:
402 case Sema::TDK_Incomplete:
403 case Sema::TDK_InvalidExplicitArguments:
404 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000405 case Sema::TDK_Underqualified:
Douglas Gregorec20f462010-05-08 20:07:26 +0000406 return 0;
407
408 case Sema::TDK_SubstitutionFailure:
409 return static_cast<TemplateArgumentList*>(Data);
410
411 // Unhandled
412 case Sema::TDK_NonDeducedMismatch:
413 case Sema::TDK_FailedOverloadResolution:
414 break;
415 }
416
417 return 0;
418}
419
Douglas Gregora9333192010-05-08 17:41:32 +0000420const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
421 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
422 case Sema::TDK_Success:
423 case Sema::TDK_InstantiationDepth:
424 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000425 case Sema::TDK_TooManyArguments:
426 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000427 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000428 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000429 return 0;
430
Douglas Gregora9333192010-05-08 17:41:32 +0000431 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000432 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000433 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
434
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000435 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000436 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000437 case Sema::TDK_FailedOverloadResolution:
438 break;
439 }
440
441 return 0;
442}
443
444const TemplateArgument *
445OverloadCandidate::DeductionFailureInfo::getSecondArg() {
446 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
447 case Sema::TDK_Success:
448 case Sema::TDK_InstantiationDepth:
449 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000450 case Sema::TDK_TooManyArguments:
451 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000452 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000453 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000454 return 0;
455
Douglas Gregora9333192010-05-08 17:41:32 +0000456 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000457 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000458 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
459
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000460 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000461 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000462 case Sema::TDK_FailedOverloadResolution:
463 break;
464 }
465
466 return 0;
467}
468
469void OverloadCandidateSet::clear() {
Douglas Gregora9333192010-05-08 17:41:32 +0000470 inherited::clear();
471 Functions.clear();
472}
473
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000474// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000475// overload of the declarations in Old. This routine returns false if
476// New and Old cannot be overloaded, e.g., if New has the same
477// signature as some function in Old (C++ 1.3.10) or if the Old
478// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000479// it does return false, MatchedDecl will point to the decl that New
480// cannot be overloaded with. This decl may be a UsingShadowDecl on
481// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000482//
483// Example: Given the following input:
484//
485// void f(int, float); // #1
486// void f(int, int); // #2
487// int f(int, int); // #3
488//
489// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000490// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000491//
John McCall51fa86f2009-12-02 08:47:38 +0000492// When we process #2, Old contains only the FunctionDecl for #1. By
493// comparing the parameter types, we see that #1 and #2 are overloaded
494// (since they have different signatures), so this routine returns
495// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000496//
John McCall51fa86f2009-12-02 08:47:38 +0000497// When we process #3, Old is an overload set containing #1 and #2. We
498// compare the signatures of #3 to #1 (they're overloaded, so we do
499// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
500// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000501// signature), IsOverload returns false and MatchedDecl will be set to
502// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000503//
504// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
505// into a class by a using declaration. The rules for whether to hide
506// shadow declarations ignore some properties which otherwise figure
507// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000508Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000509Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
510 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000511 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000512 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000513 NamedDecl *OldD = *I;
514
515 bool OldIsUsingDecl = false;
516 if (isa<UsingShadowDecl>(OldD)) {
517 OldIsUsingDecl = true;
518
519 // We can always introduce two using declarations into the same
520 // context, even if they have identical signatures.
521 if (NewIsUsingDecl) continue;
522
523 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
524 }
525
526 // If either declaration was introduced by a using declaration,
527 // we'll need to use slightly different rules for matching.
528 // Essentially, these rules are the normal rules, except that
529 // function templates hide function templates with different
530 // return types or template parameter lists.
531 bool UseMemberUsingDeclRules =
532 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
533
John McCall51fa86f2009-12-02 08:47:38 +0000534 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000535 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
536 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
537 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
538 continue;
539 }
540
John McCall871b2e72009-12-09 03:35:25 +0000541 Match = *I;
542 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000543 }
John McCall51fa86f2009-12-02 08:47:38 +0000544 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000545 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
546 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
547 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
548 continue;
549 }
550
John McCall871b2e72009-12-09 03:35:25 +0000551 Match = *I;
552 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000553 }
John McCall9f54ad42009-12-10 09:41:52 +0000554 } else if (isa<UsingDecl>(OldD) || isa<TagDecl>(OldD)) {
555 // We can overload with these, which can show up when doing
556 // redeclaration checks for UsingDecls.
557 assert(Old.getLookupKind() == LookupUsingDeclName);
558 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
559 // Optimistically assume that an unresolved using decl will
560 // overload; if it doesn't, we'll have to diagnose during
561 // template instantiation.
562 } else {
John McCall68263142009-11-18 22:49:29 +0000563 // (C++ 13p1):
564 // Only function declarations can be overloaded; object and type
565 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000566 Match = *I;
567 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000568 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000569 }
John McCall68263142009-11-18 22:49:29 +0000570
John McCall871b2e72009-12-09 03:35:25 +0000571 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000572}
573
John McCallad00b772010-06-16 08:42:20 +0000574bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
575 bool UseUsingDeclRules) {
John McCall7b492022010-08-12 07:09:11 +0000576 // If both of the functions are extern "C", then they are not
577 // overloads.
578 if (Old->isExternC() && New->isExternC())
579 return false;
580
John McCall68263142009-11-18 22:49:29 +0000581 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
582 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
583
584 // C++ [temp.fct]p2:
585 // A function template can be overloaded with other function templates
586 // and with normal (non-template) functions.
587 if ((OldTemplate == 0) != (NewTemplate == 0))
588 return true;
589
590 // Is the function New an overload of the function Old?
591 QualType OldQType = Context.getCanonicalType(Old->getType());
592 QualType NewQType = Context.getCanonicalType(New->getType());
593
594 // Compare the signatures (C++ 1.3.10) of the two functions to
595 // determine whether they are overloads. If we find any mismatch
596 // in the signature, they are overloads.
597
598 // If either of these functions is a K&R-style function (no
599 // prototype), then we consider them to have matching signatures.
600 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
601 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
602 return false;
603
604 FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
605 FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
606
607 // The signature of a function includes the types of its
608 // parameters (C++ 1.3.10), which includes the presence or absence
609 // of the ellipsis; see C++ DR 357).
610 if (OldQType != NewQType &&
611 (OldType->getNumArgs() != NewType->getNumArgs() ||
612 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000613 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000614 return true;
615
616 // C++ [temp.over.link]p4:
617 // The signature of a function template consists of its function
618 // signature, its return type and its template parameter list. The names
619 // of the template parameters are significant only for establishing the
620 // relationship between the template parameters and the rest of the
621 // signature.
622 //
623 // We check the return type and template parameter lists for function
624 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +0000625 //
626 // However, we don't consider either of these when deciding whether
627 // a member introduced by a shadow declaration is hidden.
628 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +0000629 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
630 OldTemplate->getTemplateParameters(),
631 false, TPL_TemplateMatch) ||
632 OldType->getResultType() != NewType->getResultType()))
633 return true;
634
635 // If the function is a class member, its signature includes the
636 // cv-qualifiers (if any) on the function itself.
637 //
638 // As part of this, also check whether one of the member functions
639 // is static, in which case they are not overloads (C++
640 // 13.1p2). While not part of the definition of the signature,
641 // this check is important to determine whether these functions
642 // can be overloaded.
643 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
644 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
645 if (OldMethod && NewMethod &&
646 !OldMethod->isStatic() && !NewMethod->isStatic() &&
647 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
648 return true;
649
650 // The signatures match; this is not an overload.
651 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000652}
653
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000654/// TryImplicitConversion - Attempt to perform an implicit conversion
655/// from the given expression (Expr) to the given type (ToType). This
656/// function returns an implicit conversion sequence that can be used
657/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000658///
659/// void f(float f);
660/// void g(int i) { f(i); }
661///
662/// this routine would produce an implicit conversion sequence to
663/// describe the initialization of f from i, which will be a standard
664/// conversion sequence containing an lvalue-to-rvalue conversion (C++
665/// 4.1) followed by a floating-integral conversion (C++ 4.9).
666//
667/// Note that this routine only determines how the conversion can be
668/// performed; it does not actually perform the conversion. As such,
669/// it will not produce any diagnostics if no conversion is available,
670/// but will instead return an implicit conversion sequence of kind
671/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000672///
673/// If @p SuppressUserConversions, then user-defined conversions are
674/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000675/// If @p AllowExplicit, then explicit user-defined conversions are
676/// permitted.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000677ImplicitConversionSequence
Anders Carlsson2974b5c2009-08-27 17:14:02 +0000678Sema::TryImplicitConversion(Expr* From, QualType ToType,
679 bool SuppressUserConversions,
Douglas Gregor74e386e2010-04-16 18:00:29 +0000680 bool AllowExplicit,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000681 bool InOverloadResolution) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000682 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +0000683 if (IsStandardConversion(From, ToType, InOverloadResolution, ICS.Standard)) {
John McCall1d318332010-01-12 00:44:57 +0000684 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +0000685 return ICS;
686 }
687
688 if (!getLangOptions().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +0000689 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +0000690 return ICS;
691 }
692
Douglas Gregor604eb652010-08-11 02:15:33 +0000693 // C++ [over.ics.user]p4:
694 // A conversion of an expression of class type to the same class
695 // type is given Exact Match rank, and a conversion of an
696 // expression of class type to a base class of that type is
697 // given Conversion rank, in spite of the fact that a copy/move
698 // constructor (i.e., a user-defined conversion function) is
699 // called for those cases.
700 QualType FromType = From->getType();
701 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
702 (Context.hasSameUnqualifiedType(FromType, ToType) ||
703 IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000704 ICS.setStandard();
705 ICS.Standard.setAsIdentityConversion();
706 ICS.Standard.setFromType(FromType);
707 ICS.Standard.setAllToTypes(ToType);
708
709 // We don't actually check at this point whether there is a valid
710 // copy/move constructor, since overloading just assumes that it
711 // exists. When we actually perform initialization, we'll find the
712 // appropriate constructor to copy the returned object, if needed.
713 ICS.Standard.CopyConstructor = 0;
Douglas Gregor604eb652010-08-11 02:15:33 +0000714
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000715 // Determine whether this is considered a derived-to-base conversion.
716 if (!Context.hasSameUnqualifiedType(FromType, ToType))
717 ICS.Standard.Second = ICK_Derived_To_Base;
Douglas Gregor604eb652010-08-11 02:15:33 +0000718
719 return ICS;
720 }
721
722 if (SuppressUserConversions) {
723 // We're not in the case above, so there is no conversion that
724 // we can perform.
725 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000726 return ICS;
727 }
728
729 // Attempt user-defined conversion.
John McCall5769d612010-02-08 23:07:23 +0000730 OverloadCandidateSet Conversions(From->getExprLoc());
731 OverloadingResult UserDefResult
732 = IsUserDefinedConversion(From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000733 AllowExplicit);
John McCall5769d612010-02-08 23:07:23 +0000734
735 if (UserDefResult == OR_Success) {
John McCall1d318332010-01-12 00:44:57 +0000736 ICS.setUserDefined();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000737 // C++ [over.ics.user]p4:
738 // A conversion of an expression of class type to the same class
739 // type is given Exact Match rank, and a conversion of an
740 // expression of class type to a base class of that type is
741 // given Conversion rank, in spite of the fact that a copy
742 // constructor (i.e., a user-defined conversion function) is
743 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000744 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000745 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000746 QualType FromCanon
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000747 = Context.getCanonicalType(From->getType().getUnqualifiedType());
748 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor9e9199d2009-12-22 00:34:07 +0000749 if (Constructor->isCopyConstructor() &&
Douglas Gregor0d6d12b2009-12-22 00:21:20 +0000750 (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000751 // Turn this into a "standard" conversion sequence, so that it
752 // gets ranked with standard conversion sequences.
John McCall1d318332010-01-12 00:44:57 +0000753 ICS.setStandard();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000754 ICS.Standard.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +0000755 ICS.Standard.setFromType(From->getType());
Douglas Gregorad323a82010-01-27 03:51:04 +0000756 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000757 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000758 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000759 ICS.Standard.Second = ICK_Derived_To_Base;
760 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000761 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000762
763 // C++ [over.best.ics]p4:
764 // However, when considering the argument of a user-defined
765 // conversion function that is a candidate by 13.3.1.3 when
766 // invoked for the copying of the temporary in the second step
767 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
768 // 13.3.1.6 in all cases, only standard conversion sequences and
769 // ellipsis conversion sequences are allowed.
John McCalladbb8f82010-01-13 09:16:55 +0000770 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCallb1bdc622010-02-25 01:37:24 +0000771 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCalladbb8f82010-01-13 09:16:55 +0000772 }
John McCallcefd3ad2010-01-13 22:30:33 +0000773 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall1d318332010-01-12 00:44:57 +0000774 ICS.setAmbiguous();
775 ICS.Ambiguous.setFromType(From->getType());
776 ICS.Ambiguous.setToType(ToType);
777 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
778 Cand != Conversions.end(); ++Cand)
779 if (Cand->Viable)
780 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000781 } else {
John McCallb1bdc622010-02-25 01:37:24 +0000782 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000783 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000784
785 return ICS;
786}
787
Douglas Gregor575c63a2010-04-16 22:27:05 +0000788/// PerformImplicitConversion - Perform an implicit conversion of the
789/// expression From to the type ToType. Returns true if there was an
790/// error, false otherwise. The expression From is replaced with the
791/// converted expression. Flavor is the kind of conversion we're
792/// performing, used in the error message. If @p AllowExplicit,
793/// explicit user-defined conversions are permitted.
794bool
795Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
796 AssignmentAction Action, bool AllowExplicit) {
797 ImplicitConversionSequence ICS;
798 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
799}
800
801bool
802Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
803 AssignmentAction Action, bool AllowExplicit,
804 ImplicitConversionSequence& ICS) {
805 ICS = TryImplicitConversion(From, ToType,
806 /*SuppressUserConversions=*/false,
807 AllowExplicit,
808 /*InOverloadResolution=*/false);
809 return PerformImplicitConversion(From, ToType, ICS, Action);
810}
811
Douglas Gregor43c79c22009-12-09 00:47:37 +0000812/// \brief Determine whether the conversion from FromType to ToType is a valid
813/// conversion that strips "noreturn" off the nested function type.
814static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
815 QualType ToType, QualType &ResultTy) {
816 if (Context.hasSameUnqualifiedType(FromType, ToType))
817 return false;
818
819 // Strip the noreturn off the type we're converting from; noreturn can
820 // safely be removed.
821 FromType = Context.getNoReturnType(FromType, false);
822 if (!Context.hasSameUnqualifiedType(FromType, ToType))
823 return false;
824
825 ResultTy = FromType;
826 return true;
827}
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000828
829/// \brief Determine whether the conversion from FromType to ToType is a valid
830/// vector conversion.
831///
832/// \param ICK Will be set to the vector conversion kind, if this is a vector
833/// conversion.
834static bool IsVectorConversion(ASTContext &Context, QualType FromType,
835 QualType ToType, ImplicitConversionKind &ICK) {
836 // We need at least one of these types to be a vector type to have a vector
837 // conversion.
838 if (!ToType->isVectorType() && !FromType->isVectorType())
839 return false;
840
841 // Identical types require no conversions.
842 if (Context.hasSameUnqualifiedType(FromType, ToType))
843 return false;
844
845 // There are no conversions between extended vector types, only identity.
846 if (ToType->isExtVectorType()) {
847 // There are no conversions between extended vector types other than the
848 // identity conversion.
849 if (FromType->isExtVectorType())
850 return false;
851
852 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +0000853 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000854 ICK = ICK_Vector_Splat;
855 return true;
856 }
857 }
Douglas Gregor255210e2010-08-06 10:14:59 +0000858
859 // We can perform the conversion between vector types in the following cases:
860 // 1)vector types are equivalent AltiVec and GCC vector types
861 // 2)lax vector conversions are permitted and the vector types are of the
862 // same size
863 if (ToType->isVectorType() && FromType->isVectorType()) {
864 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruthc45eb9c2010-08-08 05:02:51 +0000865 (Context.getLangOptions().LaxVectorConversions &&
866 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +0000867 ICK = ICK_Vector_Conversion;
868 return true;
869 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000870 }
Douglas Gregor255210e2010-08-06 10:14:59 +0000871
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000872 return false;
873}
Douglas Gregor43c79c22009-12-09 00:47:37 +0000874
Douglas Gregor60d62c22008-10-31 16:23:19 +0000875/// IsStandardConversion - Determines whether there is a standard
876/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
877/// expression From to the type ToType. Standard conversion sequences
878/// only consider non-class types; for conversions that involve class
879/// types, use TryImplicitConversion. If a conversion exists, SCS will
880/// contain the standard conversion sequence required to perform this
881/// conversion and this routine will return true. Otherwise, this
882/// routine will return false and the value of SCS is unspecified.
Mike Stump1eb44332009-09-09 15:08:12 +0000883bool
884Sema::IsStandardConversion(Expr* From, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +0000885 bool InOverloadResolution,
Mike Stump1eb44332009-09-09 15:08:12 +0000886 StandardConversionSequence &SCS) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000887 QualType FromType = From->getType();
888
Douglas Gregor60d62c22008-10-31 16:23:19 +0000889 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +0000890 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +0000891 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +0000892 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +0000893 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000894 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000895
Douglas Gregorf9201e02009-02-11 23:02:49 +0000896 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +0000897 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +0000898 if (FromType->isRecordType() || ToType->isRecordType()) {
899 if (getLangOptions().CPlusPlus)
900 return false;
901
Mike Stump1eb44332009-09-09 15:08:12 +0000902 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000903 }
904
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000905 // The first conversion can be an lvalue-to-rvalue conversion,
906 // array-to-pointer conversion, or function-to-pointer conversion
907 // (C++ 4p1).
908
Douglas Gregorad4e02f2010-04-29 18:24:40 +0000909 if (FromType == Context.OverloadTy) {
910 DeclAccessPair AccessPair;
911 if (FunctionDecl *Fn
912 = ResolveAddressOfOverloadedFunction(From, ToType, false,
913 AccessPair)) {
914 // We were able to resolve the address of the overloaded function,
915 // so we can convert to the type of that function.
916 FromType = Fn->getType();
917 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
918 if (!Method->isStatic()) {
919 Type *ClassType
920 = Context.getTypeDeclType(Method->getParent()).getTypePtr();
921 FromType = Context.getMemberPointerType(FromType, ClassType);
922 }
923 }
924
925 // If the "from" expression takes the address of the overloaded
926 // function, update the type of the resulting expression accordingly.
927 if (FromType->getAs<FunctionType>())
928 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
929 if (UnOp->getOpcode() == UnaryOperator::AddrOf)
930 FromType = Context.getPointerType(FromType);
931
932 // Check that we've computed the proper type after overload resolution.
933 assert(Context.hasSameType(FromType,
934 FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
935 } else {
936 return false;
937 }
938 }
Mike Stump1eb44332009-09-09 15:08:12 +0000939 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000940 // An lvalue (3.10) of a non-function, non-array type T can be
941 // converted to an rvalue.
942 Expr::isLvalueResult argIsLvalue = From->isLvalue(Context);
Mike Stump1eb44332009-09-09 15:08:12 +0000943 if (argIsLvalue == Expr::LV_Valid &&
Douglas Gregor904eed32008-11-10 20:40:00 +0000944 !FromType->isFunctionType() && !FromType->isArrayType() &&
Douglas Gregor063daf62009-03-13 18:40:31 +0000945 Context.getCanonicalType(FromType) != Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +0000946 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000947
948 // If T is a non-class type, the type of the rvalue is the
949 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +0000950 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
951 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000952 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000953 } else if (FromType->isArrayType()) {
954 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000955 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000956
957 // An lvalue or rvalue of type "array of N T" or "array of unknown
958 // bound of T" can be converted to an rvalue of type "pointer to
959 // T" (C++ 4.2p1).
960 FromType = Context.getArrayDecayedType(FromType);
961
962 if (IsStringLiteralToNonConstPointerConversion(From, ToType)) {
963 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +0000964 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000965
966 // For the purpose of ranking in overload resolution
967 // (13.3.3.1.1), this conversion is considered an
968 // array-to-pointer conversion followed by a qualification
969 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +0000970 SCS.Second = ICK_Identity;
971 SCS.Third = ICK_Qualification;
Douglas Gregorad323a82010-01-27 03:51:04 +0000972 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +0000973 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000974 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000975 } else if (FromType->isFunctionType() && argIsLvalue == Expr::LV_Valid) {
976 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +0000977 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000978
979 // An lvalue of function type T can be converted to an rvalue of
980 // type "pointer to T." The result is a pointer to the
981 // function. (C++ 4.3p1).
982 FromType = Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000983 } else {
984 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +0000985 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000986 }
Douglas Gregorad323a82010-01-27 03:51:04 +0000987 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000988
989 // The second conversion can be an integral promotion, floating
990 // point promotion, integral conversion, floating point conversion,
991 // floating-integral conversion, pointer conversion,
992 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +0000993 // For overloading in C, this can also be a "compatible-type"
994 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +0000995 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000996 ImplicitConversionKind SecondICK = ICK_Identity;
Douglas Gregorf9201e02009-02-11 23:02:49 +0000997 if (Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000998 // The unqualified versions of the types are the same: there's no
999 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001000 SCS.Second = ICK_Identity;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001001 } else if (IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001002 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001003 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001004 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001005 } else if (IsFloatingPointPromotion(FromType, ToType)) {
1006 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001007 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001008 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001009 } else if (IsComplexPromotion(FromType, ToType)) {
1010 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001011 SCS.Second = ICK_Complex_Promotion;
1012 FromType = ToType.getUnqualifiedType();
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001013 } else if (FromType->isIntegralOrEnumerationType() &&
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001014 ToType->isIntegralType(Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001015 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001016 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001017 FromType = ToType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001018 } else if (FromType->isComplexType() && ToType->isComplexType()) {
1019 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001020 SCS.Second = ICK_Complex_Conversion;
1021 FromType = ToType.getUnqualifiedType();
Chandler Carruth23a370f2010-02-25 07:20:54 +00001022 } else if ((FromType->isComplexType() && ToType->isArithmeticType()) ||
1023 (ToType->isComplexType() && FromType->isArithmeticType())) {
1024 // Complex-real conversions (C99 6.3.1.7)
1025 SCS.Second = ICK_Complex_Real;
1026 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001027 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001028 // Floating point conversions (C++ 4.8).
1029 SCS.Second = ICK_Floating_Conversion;
1030 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001031 } else if ((FromType->isRealFloatingType() &&
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001032 ToType->isIntegralType(Context) && !ToType->isBooleanType()) ||
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001033 (FromType->isIntegralOrEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001034 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001035 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001036 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001037 FromType = ToType.getUnqualifiedType();
Anders Carlsson08972922009-08-28 15:33:32 +00001038 } else if (IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1039 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001040 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001041 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001042 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregorce940492009-09-25 04:25:58 +00001043 } else if (IsMemberPointerConversion(From, FromType, ToType,
1044 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001045 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001046 SCS.Second = ICK_Pointer_Member;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001047 } else if (ToType->isBooleanType() &&
1048 (FromType->isArithmeticType() ||
1049 FromType->isEnumeralType() ||
Fariborz Jahanian1f7711d2009-12-11 21:23:13 +00001050 FromType->isAnyPointerType() ||
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001051 FromType->isBlockPointerType() ||
1052 FromType->isMemberPointerType() ||
Douglas Gregor00619622010-06-22 23:41:02 +00001053 FromType->isNullPtrType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001054 // Boolean conversions (C++ 4.12).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001055 SCS.Second = ICK_Boolean_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001056 FromType = Context.BoolTy;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001057 } else if (IsVectorConversion(Context, FromType, ToType, SecondICK)) {
1058 SCS.Second = SecondICK;
1059 FromType = ToType.getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00001060 } else if (!getLangOptions().CPlusPlus &&
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001061 Context.typesAreCompatible(ToType, FromType)) {
1062 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001063 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001064 FromType = ToType.getUnqualifiedType();
Douglas Gregor43c79c22009-12-09 00:47:37 +00001065 } else if (IsNoReturnConversion(Context, FromType, ToType, FromType)) {
1066 // Treat a conversion that strips "noreturn" as an identity conversion.
1067 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001068 } else {
1069 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001070 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001071 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001072 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001073
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001074 QualType CanonFrom;
1075 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001076 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor98cd5992008-10-21 23:43:52 +00001077 if (IsQualificationConversion(FromType, ToType)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001078 SCS.Third = ICK_Qualification;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001079 FromType = ToType;
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001080 CanonFrom = Context.getCanonicalType(FromType);
1081 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001082 } else {
1083 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001084 SCS.Third = ICK_Identity;
1085
Mike Stump1eb44332009-09-09 15:08:12 +00001086 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001087 // [...] Any difference in top-level cv-qualification is
1088 // subsumed by the initialization itself and does not constitute
1089 // a conversion. [...]
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001090 CanonFrom = Context.getCanonicalType(FromType);
Mike Stump1eb44332009-09-09 15:08:12 +00001091 CanonTo = Context.getCanonicalType(ToType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00001092 if (CanonFrom.getLocalUnqualifiedType()
1093 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001094 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1095 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001096 FromType = ToType;
1097 CanonFrom = CanonTo;
1098 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001099 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001100 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001101
1102 // If we have not converted the argument type to the parameter type,
1103 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001104 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001105 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001106
Douglas Gregor60d62c22008-10-31 16:23:19 +00001107 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001108}
1109
1110/// IsIntegralPromotion - Determines whether the conversion from the
1111/// expression From (whose potentially-adjusted type is FromType) to
1112/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1113/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001114bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001115 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001116 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001117 if (!To) {
1118 return false;
1119 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001120
1121 // An rvalue of type char, signed char, unsigned char, short int, or
1122 // unsigned short int can be converted to an rvalue of type int if
1123 // int can represent all the values of the source type; otherwise,
1124 // the source rvalue can be converted to an rvalue of type unsigned
1125 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001126 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1127 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001128 if (// We can promote any signed, promotable integer type to an int
1129 (FromType->isSignedIntegerType() ||
1130 // We can promote any unsigned integer type whose size is
1131 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001132 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001133 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001134 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001135 }
1136
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001137 return To->getKind() == BuiltinType::UInt;
1138 }
1139
1140 // An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2)
1141 // can be converted to an rvalue of the first of the following types
1142 // that can represent all the values of its underlying type: int,
1143 // unsigned int, long, or unsigned long (C++ 4.5p2).
John McCall842aef82009-12-09 09:09:27 +00001144
1145 // We pre-calculate the promotion type for enum types.
1146 if (const EnumType *FromEnumType = FromType->getAs<EnumType>())
1147 if (ToType->isIntegerType())
1148 return Context.hasSameUnqualifiedType(ToType,
1149 FromEnumType->getDecl()->getPromotionType());
1150
1151 if (FromType->isWideCharType() && ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001152 // Determine whether the type we're converting from is signed or
1153 // unsigned.
1154 bool FromIsSigned;
1155 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall842aef82009-12-09 09:09:27 +00001156
1157 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1158 FromIsSigned = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001159
1160 // The types we'll try to promote to, in the appropriate
1161 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001162 QualType PromoteTypes[6] = {
1163 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001164 Context.LongTy, Context.UnsignedLongTy ,
1165 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001166 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001167 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001168 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1169 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001170 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001171 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1172 // We found the type that we can promote to. If this is the
1173 // type we wanted, we have a promotion. Otherwise, no
1174 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001175 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001176 }
1177 }
1178 }
1179
1180 // An rvalue for an integral bit-field (9.6) can be converted to an
1181 // rvalue of type int if int can represent all the values of the
1182 // bit-field; otherwise, it can be converted to unsigned int if
1183 // unsigned int can represent all the values of the bit-field. If
1184 // the bit-field is larger yet, no integral promotion applies to
1185 // it. If the bit-field has an enumerated type, it is treated as any
1186 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001187 // FIXME: We should delay checking of bit-fields until we actually perform the
1188 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001189 using llvm::APSInt;
1190 if (From)
1191 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001192 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001193 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001194 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1195 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1196 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001197
Douglas Gregor86f19402008-12-20 23:49:58 +00001198 // Are we promoting to an int from a bitfield that fits in an int?
1199 if (BitWidth < ToSize ||
1200 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1201 return To->getKind() == BuiltinType::Int;
1202 }
Mike Stump1eb44332009-09-09 15:08:12 +00001203
Douglas Gregor86f19402008-12-20 23:49:58 +00001204 // Are we promoting to an unsigned int from an unsigned bitfield
1205 // that fits into an unsigned int?
1206 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1207 return To->getKind() == BuiltinType::UInt;
1208 }
Mike Stump1eb44332009-09-09 15:08:12 +00001209
Douglas Gregor86f19402008-12-20 23:49:58 +00001210 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001211 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001212 }
Mike Stump1eb44332009-09-09 15:08:12 +00001213
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001214 // An rvalue of type bool can be converted to an rvalue of type int,
1215 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001216 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001217 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001218 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001219
1220 return false;
1221}
1222
1223/// IsFloatingPointPromotion - Determines whether the conversion from
1224/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1225/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001226bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001227 /// An rvalue of type float can be converted to an rvalue of type
1228 /// double. (C++ 4.6p1).
John McCall183700f2009-09-21 23:43:11 +00001229 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1230 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001231 if (FromBuiltin->getKind() == BuiltinType::Float &&
1232 ToBuiltin->getKind() == BuiltinType::Double)
1233 return true;
1234
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001235 // C99 6.3.1.5p1:
1236 // When a float is promoted to double or long double, or a
1237 // double is promoted to long double [...].
1238 if (!getLangOptions().CPlusPlus &&
1239 (FromBuiltin->getKind() == BuiltinType::Float ||
1240 FromBuiltin->getKind() == BuiltinType::Double) &&
1241 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1242 return true;
1243 }
1244
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001245 return false;
1246}
1247
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001248/// \brief Determine if a conversion is a complex promotion.
1249///
1250/// A complex promotion is defined as a complex -> complex conversion
1251/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001252/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001253bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001254 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001255 if (!FromComplex)
1256 return false;
1257
John McCall183700f2009-09-21 23:43:11 +00001258 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001259 if (!ToComplex)
1260 return false;
1261
1262 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001263 ToComplex->getElementType()) ||
1264 IsIntegralPromotion(0, FromComplex->getElementType(),
1265 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001266}
1267
Douglas Gregorcb7de522008-11-26 23:31:11 +00001268/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1269/// the pointer type FromPtr to a pointer to type ToPointee, with the
1270/// same type qualifiers as FromPtr has on its pointee type. ToType,
1271/// if non-empty, will be a pointer to ToType that may or may not have
1272/// the right set of qualifiers on its pointee.
Mike Stump1eb44332009-09-09 15:08:12 +00001273static QualType
1274BuildSimilarlyQualifiedPointerType(const PointerType *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001275 QualType ToPointee, QualType ToType,
1276 ASTContext &Context) {
1277 QualType CanonFromPointee = Context.getCanonicalType(FromPtr->getPointeeType());
1278 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001279 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001280
1281 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001282 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001283 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001284 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001285 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001286
1287 // Build a pointer to ToPointee. It has the right qualifiers
1288 // already.
1289 return Context.getPointerType(ToPointee);
1290 }
1291
1292 // Just build a canonical type that has the right qualifiers.
John McCall0953e762009-09-24 19:53:00 +00001293 return Context.getPointerType(
Douglas Gregora4923eb2009-11-16 21:35:15 +00001294 Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(),
1295 Quals));
Douglas Gregorcb7de522008-11-26 23:31:11 +00001296}
1297
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001298/// BuildSimilarlyQualifiedObjCObjectPointerType - In a pointer conversion from
1299/// the FromType, which is an objective-c pointer, to ToType, which may or may
1300/// not have the right set of qualifiers.
1301static QualType
1302BuildSimilarlyQualifiedObjCObjectPointerType(QualType FromType,
1303 QualType ToType,
1304 ASTContext &Context) {
1305 QualType CanonFromType = Context.getCanonicalType(FromType);
1306 QualType CanonToType = Context.getCanonicalType(ToType);
1307 Qualifiers Quals = CanonFromType.getQualifiers();
1308
1309 // Exact qualifier match -> return the pointer type we're converting to.
1310 if (CanonToType.getLocalQualifiers() == Quals)
1311 return ToType;
1312
1313 // Just build a canonical type that has the right qualifiers.
1314 return Context.getQualifiedType(CanonToType.getLocalUnqualifiedType(), Quals);
1315}
1316
Mike Stump1eb44332009-09-09 15:08:12 +00001317static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001318 bool InOverloadResolution,
1319 ASTContext &Context) {
1320 // Handle value-dependent integral null pointer constants correctly.
1321 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1322 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001323 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001324 return !InOverloadResolution;
1325
Douglas Gregorce940492009-09-25 04:25:58 +00001326 return Expr->isNullPointerConstant(Context,
1327 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1328 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001329}
Mike Stump1eb44332009-09-09 15:08:12 +00001330
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001331/// IsPointerConversion - Determines whether the conversion of the
1332/// expression From, which has the (possibly adjusted) type FromType,
1333/// can be converted to the type ToType via a pointer conversion (C++
1334/// 4.10). If so, returns true and places the converted type (that
1335/// might differ from ToType in its cv-qualifiers at some level) into
1336/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001337///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001338/// This routine also supports conversions to and from block pointers
1339/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1340/// pointers to interfaces. FIXME: Once we've determined the
1341/// appropriate overloading rules for Objective-C, we may want to
1342/// split the Objective-C checks into a different routine; however,
1343/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001344/// conversions, so for now they live here. IncompatibleObjC will be
1345/// set if the conversion is an allowed Objective-C conversion that
1346/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001347bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001348 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001349 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001350 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001351 IncompatibleObjC = false;
Douglas Gregorc7887512008-12-19 19:13:09 +00001352 if (isObjCPointerConversion(FromType, ToType, ConvertedType, IncompatibleObjC))
1353 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001354
Mike Stump1eb44332009-09-09 15:08:12 +00001355 // Conversion from a null pointer constant to any Objective-C pointer type.
1356 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001357 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001358 ConvertedType = ToType;
1359 return true;
1360 }
1361
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001362 // Blocks: Block pointers can be converted to void*.
1363 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001364 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001365 ConvertedType = ToType;
1366 return true;
1367 }
1368 // Blocks: A null pointer constant can be converted to a block
1369 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001370 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001371 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001372 ConvertedType = ToType;
1373 return true;
1374 }
1375
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001376 // If the left-hand-side is nullptr_t, the right side can be a null
1377 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001378 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001379 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001380 ConvertedType = ToType;
1381 return true;
1382 }
1383
Ted Kremenek6217b802009-07-29 21:53:49 +00001384 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001385 if (!ToTypePtr)
1386 return false;
1387
1388 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001389 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001390 ConvertedType = ToType;
1391 return true;
1392 }
Sebastian Redl07779722008-10-31 14:43:28 +00001393
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001394 // Beyond this point, both types need to be pointers
1395 // , including objective-c pointers.
1396 QualType ToPointeeType = ToTypePtr->getPointeeType();
1397 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
1398 ConvertedType = BuildSimilarlyQualifiedObjCObjectPointerType(FromType,
1399 ToType, Context);
1400 return true;
1401
1402 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001403 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001404 if (!FromTypePtr)
1405 return false;
1406
1407 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001408
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00001409 // If the unqualified pointee types are the same, this can't be a
1410 // pointer conversion, so don't do all of the work below.
1411 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1412 return false;
1413
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001414 // An rvalue of type "pointer to cv T," where T is an object type,
1415 // can be converted to an rvalue of type "pointer to cv void" (C++
1416 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00001417 if (FromPointeeType->isIncompleteOrObjectType() &&
1418 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001419 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001420 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001421 ToType, Context);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001422 return true;
1423 }
1424
Douglas Gregorf9201e02009-02-11 23:02:49 +00001425 // When we're overloading in C, we allow a special kind of pointer
1426 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001427 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001428 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001429 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001430 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001431 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001432 return true;
1433 }
1434
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001435 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001436 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001437 // An rvalue of type "pointer to cv D," where D is a class type,
1438 // can be converted to an rvalue of type "pointer to cv B," where
1439 // B is a base class (clause 10) of D. If B is an inaccessible
1440 // (clause 11) or ambiguous (10.2) base class of D, a program that
1441 // necessitates this conversion is ill-formed. The result of the
1442 // conversion is a pointer to the base class sub-object of the
1443 // derived class object. The null pointer value is converted to
1444 // the null pointer value of the destination type.
1445 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001446 // Note that we do not check for ambiguity or inaccessibility
1447 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001448 if (getLangOptions().CPlusPlus &&
1449 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001450 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001451 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001452 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001453 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001454 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001455 ToType, Context);
1456 return true;
1457 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001458
Douglas Gregorc7887512008-12-19 19:13:09 +00001459 return false;
1460}
1461
1462/// isObjCPointerConversion - Determines whether this is an
1463/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1464/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001465bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001466 QualType& ConvertedType,
1467 bool &IncompatibleObjC) {
1468 if (!getLangOptions().ObjC1)
1469 return false;
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001470
Steve Naroff14108da2009-07-10 23:34:53 +00001471 // First, we handle all conversions on ObjC object pointer types.
John McCall183700f2009-09-21 23:43:11 +00001472 const ObjCObjectPointerType* ToObjCPtr = ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001473 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001474 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001475
Steve Naroff14108da2009-07-10 23:34:53 +00001476 if (ToObjCPtr && FromObjCPtr) {
Steve Naroffde2e22d2009-07-15 18:40:39 +00001477 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001478 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001479 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001480 ConvertedType = ToType;
1481 return true;
1482 }
1483 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001484 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001485 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001486 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001487 /*compare=*/false)) {
Steve Naroff14108da2009-07-10 23:34:53 +00001488 ConvertedType = ToType;
1489 return true;
1490 }
1491 // Objective C++: We're able to convert from a pointer to an
1492 // interface to a pointer to a different interface.
1493 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00001494 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1495 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1496 if (getLangOptions().CPlusPlus && LHS && RHS &&
1497 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1498 FromObjCPtr->getPointeeType()))
1499 return false;
Steve Naroff14108da2009-07-10 23:34:53 +00001500 ConvertedType = ToType;
1501 return true;
1502 }
1503
1504 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1505 // Okay: this is some kind of implicit downcast of Objective-C
1506 // interfaces, which is permitted. However, we're going to
1507 // complain about it.
1508 IncompatibleObjC = true;
1509 ConvertedType = FromType;
1510 return true;
1511 }
Mike Stump1eb44332009-09-09 15:08:12 +00001512 }
Steve Naroff14108da2009-07-10 23:34:53 +00001513 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001514 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001515 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001516 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001517 else if (const BlockPointerType *ToBlockPtr =
1518 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00001519 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001520 // to a block pointer type.
1521 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1522 ConvertedType = ToType;
1523 return true;
1524 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001525 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001526 }
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001527 else if (FromType->getAs<BlockPointerType>() &&
1528 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1529 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00001530 // pointer to any object.
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001531 ConvertedType = ToType;
1532 return true;
1533 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001534 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001535 return false;
1536
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001537 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001538 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001539 FromPointeeType = FromCPtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001540 else if (const BlockPointerType *FromBlockPtr = FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001541 FromPointeeType = FromBlockPtr->getPointeeType();
1542 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001543 return false;
1544
Douglas Gregorc7887512008-12-19 19:13:09 +00001545 // If we have pointers to pointers, recursively check whether this
1546 // is an Objective-C conversion.
1547 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1548 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1549 IncompatibleObjC)) {
1550 // We always complain about this conversion.
1551 IncompatibleObjC = true;
1552 ConvertedType = ToType;
1553 return true;
1554 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001555 // Allow conversion of pointee being objective-c pointer to another one;
1556 // as in I* to id.
1557 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1558 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1559 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1560 IncompatibleObjC)) {
1561 ConvertedType = ToType;
1562 return true;
1563 }
1564
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001565 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001566 // differences in the argument and result types are in Objective-C
1567 // pointer conversions. If so, we permit the conversion (but
1568 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001569 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001570 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001571 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001572 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001573 if (FromFunctionType && ToFunctionType) {
1574 // If the function types are exactly the same, this isn't an
1575 // Objective-C pointer conversion.
1576 if (Context.getCanonicalType(FromPointeeType)
1577 == Context.getCanonicalType(ToPointeeType))
1578 return false;
1579
1580 // Perform the quick checks that will tell us whether these
1581 // function types are obviously different.
1582 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1583 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1584 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1585 return false;
1586
1587 bool HasObjCConversion = false;
1588 if (Context.getCanonicalType(FromFunctionType->getResultType())
1589 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1590 // Okay, the types match exactly. Nothing to do.
1591 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1592 ToFunctionType->getResultType(),
1593 ConvertedType, IncompatibleObjC)) {
1594 // Okay, we have an Objective-C pointer conversion.
1595 HasObjCConversion = true;
1596 } else {
1597 // Function types are too different. Abort.
1598 return false;
1599 }
Mike Stump1eb44332009-09-09 15:08:12 +00001600
Douglas Gregorc7887512008-12-19 19:13:09 +00001601 // Check argument types.
1602 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1603 ArgIdx != NumArgs; ++ArgIdx) {
1604 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1605 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1606 if (Context.getCanonicalType(FromArgType)
1607 == Context.getCanonicalType(ToArgType)) {
1608 // Okay, the types match exactly. Nothing to do.
1609 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1610 ConvertedType, IncompatibleObjC)) {
1611 // Okay, we have an Objective-C pointer conversion.
1612 HasObjCConversion = true;
1613 } else {
1614 // Argument types are too different. Abort.
1615 return false;
1616 }
1617 }
1618
1619 if (HasObjCConversion) {
1620 // We had an Objective-C conversion. Allow this pointer
1621 // conversion, but complain about it.
1622 ConvertedType = ToType;
1623 IncompatibleObjC = true;
1624 return true;
1625 }
1626 }
1627
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001628 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001629}
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001630
1631/// FunctionArgTypesAreEqual - This routine checks two function proto types
1632/// for equlity of their argument types. Caller has already checked that
1633/// they have same number of arguments. This routine assumes that Objective-C
1634/// pointer types which only differ in their protocol qualifiers are equal.
1635bool Sema::FunctionArgTypesAreEqual(FunctionProtoType* OldType,
1636 FunctionProtoType* NewType){
1637 if (!getLangOptions().ObjC1)
1638 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1639 NewType->arg_type_begin());
1640
1641 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1642 N = NewType->arg_type_begin(),
1643 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1644 QualType ToType = (*O);
1645 QualType FromType = (*N);
1646 if (ToType != FromType) {
1647 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1648 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00001649 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1650 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1651 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1652 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001653 continue;
1654 }
John McCallc12c5bb2010-05-15 11:32:37 +00001655 else if (const ObjCObjectPointerType *PTTo =
1656 ToType->getAs<ObjCObjectPointerType>()) {
1657 if (const ObjCObjectPointerType *PTFr =
1658 FromType->getAs<ObjCObjectPointerType>())
1659 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1660 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00001661 }
1662 return false;
1663 }
1664 }
1665 return true;
1666}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001667
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001668/// CheckPointerConversion - Check the pointer conversion from the
1669/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00001670/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001671/// conversions for which IsPointerConversion has already returned
1672/// true. It returns true and produces a diagnostic if there was an
1673/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00001674bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001675 CastExpr::CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001676 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001677 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001678 QualType FromType = From->getType();
1679
Douglas Gregord7a95972010-06-08 17:35:15 +00001680 if (CXXBoolLiteralExpr* LitBool
1681 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
1682 if (LitBool->getValue() == false)
1683 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1684 << ToType;
1685
Ted Kremenek6217b802009-07-29 21:53:49 +00001686 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1687 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001688 QualType FromPointeeType = FromPtrType->getPointeeType(),
1689 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00001690
Douglas Gregor5fccd362010-03-03 23:55:11 +00001691 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1692 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001693 // We must have a derived-to-base conversion. Check an
1694 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00001695 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1696 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00001697 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001698 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00001699 return true;
1700
1701 // The conversion was successful.
1702 Kind = CastExpr::CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001703 }
1704 }
Mike Stump1eb44332009-09-09 15:08:12 +00001705 if (const ObjCObjectPointerType *FromPtrType =
John McCall183700f2009-09-21 23:43:11 +00001706 FromType->getAs<ObjCObjectPointerType>())
Mike Stump1eb44332009-09-09 15:08:12 +00001707 if (const ObjCObjectPointerType *ToPtrType =
John McCall183700f2009-09-21 23:43:11 +00001708 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00001709 // Objective-C++ conversions are always okay.
1710 // FIXME: We should have a different class of conversions for the
1711 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00001712 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00001713 return false;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001714
Steve Naroff14108da2009-07-10 23:34:53 +00001715 }
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001716 return false;
1717}
1718
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001719/// IsMemberPointerConversion - Determines whether the conversion of the
1720/// expression From, which has the (possibly adjusted) type FromType, can be
1721/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1722/// If so, returns true and places the converted type (that might differ from
1723/// ToType in its cv-qualifiers at some level) into ConvertedType.
1724bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregorce940492009-09-25 04:25:58 +00001725 QualType ToType,
1726 bool InOverloadResolution,
1727 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00001728 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001729 if (!ToTypePtr)
1730 return false;
1731
1732 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00001733 if (From->isNullPointerConstant(Context,
1734 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1735 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001736 ConvertedType = ToType;
1737 return true;
1738 }
1739
1740 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00001741 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001742 if (!FromTypePtr)
1743 return false;
1744
1745 // A pointer to member of B can be converted to a pointer to member of D,
1746 // where D is derived from B (C++ 4.11p2).
1747 QualType FromClass(FromTypePtr->getClass(), 0);
1748 QualType ToClass(ToTypePtr->getClass(), 0);
1749 // FIXME: What happens when these are dependent? Is this function even called?
1750
1751 if (IsDerivedFrom(ToClass, FromClass)) {
1752 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1753 ToClass.getTypePtr());
1754 return true;
1755 }
1756
1757 return false;
1758}
Douglas Gregor43c79c22009-12-09 00:47:37 +00001759
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001760/// CheckMemberPointerConversion - Check the member pointer conversion from the
1761/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00001762/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001763/// for which IsMemberPointerConversion has already returned true. It returns
1764/// true and produces a diagnostic if there was an error, or returns false
1765/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00001766bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001767 CastExpr::CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00001768 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00001769 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001770 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001771 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001772 if (!FromPtrType) {
1773 // This must be a null pointer to member pointer conversion
Douglas Gregorce940492009-09-25 04:25:58 +00001774 assert(From->isNullPointerConstant(Context,
1775 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001776 "Expr must be null pointer constant!");
1777 Kind = CastExpr::CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001778 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001779 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001780
Ted Kremenek6217b802009-07-29 21:53:49 +00001781 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00001782 assert(ToPtrType && "No member pointer cast has a target type "
1783 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001784
Sebastian Redl21593ac2009-01-28 18:33:18 +00001785 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1786 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001787
Sebastian Redl21593ac2009-01-28 18:33:18 +00001788 // FIXME: What about dependent types?
1789 assert(FromClass->isRecordType() && "Pointer into non-class.");
1790 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001791
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001792 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00001793 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00001794 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1795 assert(DerivationOkay &&
1796 "Should not have been called if derivation isn't OK.");
1797 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001798
Sebastian Redl21593ac2009-01-28 18:33:18 +00001799 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1800 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001801 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1802 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1803 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1804 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001805 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00001806
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001807 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00001808 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1809 << FromClass << ToClass << QualType(VBase, 0)
1810 << From->getSourceRange();
1811 return true;
1812 }
1813
John McCall6b2accb2010-02-10 09:31:12 +00001814 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00001815 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1816 Paths.front(),
1817 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00001818
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001819 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00001820 BuildBasePathArray(Paths, BasePath);
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00001821 Kind = CastExpr::CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001822 return false;
1823}
1824
Douglas Gregor98cd5992008-10-21 23:43:52 +00001825/// IsQualificationConversion - Determines whether the conversion from
1826/// an rvalue of type FromType to ToType is a qualification conversion
1827/// (C++ 4.4).
Mike Stump1eb44332009-09-09 15:08:12 +00001828bool
1829Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001830 FromType = Context.getCanonicalType(FromType);
1831 ToType = Context.getCanonicalType(ToType);
1832
1833 // If FromType and ToType are the same type, this is not a
1834 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00001835 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00001836 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00001837
Douglas Gregor98cd5992008-10-21 23:43:52 +00001838 // (C++ 4.4p4):
1839 // A conversion can add cv-qualifiers at levels other than the first
1840 // in multi-level pointers, subject to the following rules: [...]
1841 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001842 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00001843 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00001844 // Within each iteration of the loop, we check the qualifiers to
1845 // determine if this still looks like a qualification
1846 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00001847 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00001848 // until there are no more pointers or pointers-to-members left to
1849 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00001850 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00001851
1852 // -- for every j > 0, if const is in cv 1,j then const is in cv
1853 // 2,j, and similarly for volatile.
Douglas Gregor9b6e2d22008-10-22 00:38:21 +00001854 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor98cd5992008-10-21 23:43:52 +00001855 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001856
Douglas Gregor98cd5992008-10-21 23:43:52 +00001857 // -- if the cv 1,j and cv 2,j are different, then const is in
1858 // every cv for 0 < k < j.
1859 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00001860 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00001861 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00001862
Douglas Gregor98cd5992008-10-21 23:43:52 +00001863 // Keep track of whether all prior cv-qualifiers in the "to" type
1864 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00001865 PreviousToQualsIncludeConst
Douglas Gregor98cd5992008-10-21 23:43:52 +00001866 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregor57373262008-10-22 14:17:15 +00001867 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00001868
1869 // We are left with FromType and ToType being the pointee types
1870 // after unwrapping the original FromType and ToType the same number
1871 // of types. If we unwrapped any pointers, and if FromType and
1872 // ToType have the same unqualified type (since we checked
1873 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001874 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00001875}
1876
Douglas Gregor734d9862009-01-30 23:27:23 +00001877/// Determines whether there is a user-defined conversion sequence
1878/// (C++ [over.ics.user]) that converts expression From to the type
1879/// ToType. If such a conversion exists, User will contain the
1880/// user-defined conversion sequence that performs such a conversion
1881/// and this routine will return true. Otherwise, this routine returns
1882/// false and User is unspecified.
1883///
Douglas Gregor734d9862009-01-30 23:27:23 +00001884/// \param AllowExplicit true if the conversion should consider C++0x
1885/// "explicit" conversion functions as well as non-explicit conversion
1886/// functions (C++0x [class.conv.fct]p2).
Douglas Gregor20093b42009-12-09 23:02:17 +00001887OverloadingResult Sema::IsUserDefinedConversion(Expr *From, QualType ToType,
1888 UserDefinedConversionSequence& User,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001889 OverloadCandidateSet& CandidateSet,
1890 bool AllowExplicit) {
1891 // Whether we will only visit constructors.
1892 bool ConstructorsOnly = false;
1893
1894 // If the type we are conversion to is a class type, enumerate its
1895 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00001896 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001897 // C++ [over.match.ctor]p1:
1898 // When objects of class type are direct-initialized (8.5), or
1899 // copy-initialized from an expression of the same or a
1900 // derived class type (8.5), overload resolution selects the
1901 // constructor. [...] For copy-initialization, the candidate
1902 // functions are all the converting constructors (12.3.1) of
1903 // that class. The argument list is the expression-list within
1904 // the parentheses of the initializer.
1905 if (Context.hasSameUnqualifiedType(ToType, From->getType()) ||
1906 (From->getType()->getAs<RecordType>() &&
1907 IsDerivedFrom(From->getType(), ToType)))
1908 ConstructorsOnly = true;
1909
Douglas Gregor393896f2009-11-05 13:06:35 +00001910 if (RequireCompleteType(From->getLocStart(), ToType, PDiag())) {
1911 // We're not going to find any constructors.
1912 } else if (CXXRecordDecl *ToRecordDecl
1913 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001914 DeclContext::lookup_iterator Con, ConEnd;
Douglas Gregore5eee5a2010-07-02 23:12:18 +00001915 for (llvm::tie(Con, ConEnd) = LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001916 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00001917 NamedDecl *D = *Con;
1918 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
1919
Douglas Gregordec06662009-08-21 18:42:58 +00001920 // Find the constructor (which may be a template).
1921 CXXConstructorDecl *Constructor = 0;
1922 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00001923 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00001924 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00001925 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00001926 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
1927 else
John McCall9aa472c2010-03-19 07:35:19 +00001928 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregor66724ea2009-11-14 01:20:54 +00001929
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00001930 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00001931 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00001932 if (ConstructorTmpl)
John McCall9aa472c2010-03-19 07:35:19 +00001933 AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001934 /*ExplicitArgs*/ 0,
John McCalld5532b62009-11-23 01:53:49 +00001935 &From, 1, CandidateSet,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001936 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00001937 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00001938 // Allow one user-defined conversion when user specifies a
1939 // From->ToType conversion via an static cast (c-style, etc).
John McCall9aa472c2010-03-19 07:35:19 +00001940 AddOverloadCandidate(Constructor, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001941 &From, 1, CandidateSet,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001942 /*SuppressUserConversions=*/!ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00001943 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00001944 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001945 }
1946 }
1947
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001948 // Enumerate conversion functions, if we're allowed to.
1949 if (ConstructorsOnly) {
Mike Stump1eb44332009-09-09 15:08:12 +00001950 } else if (RequireCompleteType(From->getLocStart(), From->getType(),
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001951 PDiag(0) << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00001952 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00001953 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00001954 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001955 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001956 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
1957 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00001958 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00001959 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00001960 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00001961 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00001962 DeclAccessPair FoundDecl = I.getPair();
1963 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00001964 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
1965 if (isa<UsingShadowDecl>(D))
1966 D = cast<UsingShadowDecl>(D)->getTargetDecl();
1967
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001968 CXXConversionDecl *Conv;
1969 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00001970 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
1971 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001972 else
John McCall32daa422010-03-31 01:36:47 +00001973 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001974
1975 if (AllowExplicit || !Conv->isExplicit()) {
1976 if (ConvTemplate)
John McCall9aa472c2010-03-19 07:35:19 +00001977 AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00001978 ActingContext, From, ToType,
1979 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001980 else
John McCall9aa472c2010-03-19 07:35:19 +00001981 AddConversionCandidate(Conv, FoundDecl, ActingContext,
John McCall86820f52010-01-26 01:37:31 +00001982 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00001983 }
1984 }
1985 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00001986 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00001987
1988 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00001989 switch (BestViableFunction(CandidateSet, From->getLocStart(), Best)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001990 case OR_Success:
1991 // Record the standard conversion we used and the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00001992 if (CXXConstructorDecl *Constructor
Douglas Gregor60d62c22008-10-31 16:23:19 +00001993 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
1994 // C++ [over.ics.user]p1:
1995 // If the user-defined conversion is specified by a
1996 // constructor (12.3.1), the initial standard conversion
1997 // sequence converts the source type to the type required by
1998 // the argument of the constructor.
1999 //
Douglas Gregor60d62c22008-10-31 16:23:19 +00002000 QualType ThisType = Constructor->getThisType(Context);
John McCall1d318332010-01-12 00:44:57 +00002001 if (Best->Conversions[0].isEllipsis())
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002002 User.EllipsisConversion = true;
2003 else {
2004 User.Before = Best->Conversions[0].Standard;
2005 User.EllipsisConversion = false;
2006 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002007 User.ConversionFunction = Constructor;
2008 User.After.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +00002009 User.After.setFromType(
2010 ThisType->getAs<PointerType>()->getPointeeType());
Douglas Gregorad323a82010-01-27 03:51:04 +00002011 User.After.setAllToTypes(ToType);
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002012 return OR_Success;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002013 } else if (CXXConversionDecl *Conversion
2014 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2015 // C++ [over.ics.user]p1:
2016 //
2017 // [...] If the user-defined conversion is specified by a
2018 // conversion function (12.3.2), the initial standard
2019 // conversion sequence converts the source type to the
2020 // implicit object parameter of the conversion function.
2021 User.Before = Best->Conversions[0].Standard;
2022 User.ConversionFunction = Conversion;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002023 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002024
2025 // C++ [over.ics.user]p2:
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002026 // The second standard conversion sequence converts the
2027 // result of the user-defined conversion to the target type
2028 // for the sequence. Since an implicit conversion sequence
2029 // is an initialization, the special rules for
2030 // initialization by user-defined conversion apply when
2031 // selecting the best user-defined conversion for a
2032 // user-defined conversion sequence (see 13.3.3 and
2033 // 13.3.3.1).
2034 User.After = Best->FinalConversion;
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002035 return OR_Success;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002036 } else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002037 assert(false && "Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002038 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002039 }
Mike Stump1eb44332009-09-09 15:08:12 +00002040
Douglas Gregor60d62c22008-10-31 16:23:19 +00002041 case OR_No_Viable_Function:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002042 return OR_No_Viable_Function;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00002043 case OR_Deleted:
Douglas Gregor60d62c22008-10-31 16:23:19 +00002044 // No conversion here! We're done.
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002045 return OR_Deleted;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002046
2047 case OR_Ambiguous:
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002048 return OR_Ambiguous;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002049 }
2050
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002051 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002052}
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002053
2054bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002055Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002056 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00002057 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002058 OverloadingResult OvResult =
2059 IsUserDefinedConversion(From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002060 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002061 if (OvResult == OR_Ambiguous)
2062 Diag(From->getSourceRange().getBegin(),
2063 diag::err_typecheck_ambiguous_condition)
2064 << From->getType() << ToType << From->getSourceRange();
2065 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2066 Diag(From->getSourceRange().getBegin(),
2067 diag::err_typecheck_nonviable_condition)
2068 << From->getType() << ToType << From->getSourceRange();
2069 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002070 return false;
John McCallcbce6062010-01-12 07:18:19 +00002071 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &From, 1);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002072 return true;
2073}
Douglas Gregor60d62c22008-10-31 16:23:19 +00002074
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002075/// CompareImplicitConversionSequences - Compare two implicit
2076/// conversion sequences to determine whether one is better than the
2077/// other or if they are indistinguishable (C++ 13.3.3.2).
Mike Stump1eb44332009-09-09 15:08:12 +00002078ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002079Sema::CompareImplicitConversionSequences(const ImplicitConversionSequence& ICS1,
2080 const ImplicitConversionSequence& ICS2)
2081{
2082 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2083 // conversion sequences (as defined in 13.3.3.1)
2084 // -- a standard conversion sequence (13.3.3.1.1) is a better
2085 // conversion sequence than a user-defined conversion sequence or
2086 // an ellipsis conversion sequence, and
2087 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2088 // conversion sequence than an ellipsis conversion sequence
2089 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002090 //
John McCall1d318332010-01-12 00:44:57 +00002091 // C++0x [over.best.ics]p10:
2092 // For the purpose of ranking implicit conversion sequences as
2093 // described in 13.3.3.2, the ambiguous conversion sequence is
2094 // treated as a user-defined sequence that is indistinguishable
2095 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002096 if (ICS1.getKindRank() < ICS2.getKindRank())
2097 return ImplicitConversionSequence::Better;
2098 else if (ICS2.getKindRank() < ICS1.getKindRank())
2099 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002100
Benjamin Kramerb6eee072010-04-18 12:05:54 +00002101 // The following checks require both conversion sequences to be of
2102 // the same kind.
2103 if (ICS1.getKind() != ICS2.getKind())
2104 return ImplicitConversionSequence::Indistinguishable;
2105
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002106 // Two implicit conversion sequences of the same form are
2107 // indistinguishable conversion sequences unless one of the
2108 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00002109 if (ICS1.isStandard())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002110 return CompareStandardConversionSequences(ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00002111 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002112 // User-defined conversion sequence U1 is a better conversion
2113 // sequence than another user-defined conversion sequence U2 if
2114 // they contain the same user-defined conversion function or
2115 // constructor and if the second standard conversion sequence of
2116 // U1 is better than the second standard conversion sequence of
2117 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002118 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002119 ICS2.UserDefined.ConversionFunction)
2120 return CompareStandardConversionSequences(ICS1.UserDefined.After,
2121 ICS2.UserDefined.After);
2122 }
2123
2124 return ImplicitConversionSequence::Indistinguishable;
2125}
2126
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002127static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2128 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2129 Qualifiers Quals;
2130 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2131 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2132 }
2133
2134 return Context.hasSameUnqualifiedType(T1, T2);
2135}
2136
Douglas Gregorad323a82010-01-27 03:51:04 +00002137// Per 13.3.3.2p3, compare the given standard conversion sequences to
2138// determine if one is a proper subset of the other.
2139static ImplicitConversionSequence::CompareKind
2140compareStandardConversionSubsets(ASTContext &Context,
2141 const StandardConversionSequence& SCS1,
2142 const StandardConversionSequence& SCS2) {
2143 ImplicitConversionSequence::CompareKind Result
2144 = ImplicitConversionSequence::Indistinguishable;
2145
Douglas Gregorae65f4b2010-05-23 22:10:15 +00002146 // the identity conversion sequence is considered to be a subsequence of
2147 // any non-identity conversion sequence
2148 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2149 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2150 return ImplicitConversionSequence::Better;
2151 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2152 return ImplicitConversionSequence::Worse;
2153 }
2154
Douglas Gregorad323a82010-01-27 03:51:04 +00002155 if (SCS1.Second != SCS2.Second) {
2156 if (SCS1.Second == ICK_Identity)
2157 Result = ImplicitConversionSequence::Better;
2158 else if (SCS2.Second == ICK_Identity)
2159 Result = ImplicitConversionSequence::Worse;
2160 else
2161 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002162 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00002163 return ImplicitConversionSequence::Indistinguishable;
2164
2165 if (SCS1.Third == SCS2.Third) {
2166 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2167 : ImplicitConversionSequence::Indistinguishable;
2168 }
2169
2170 if (SCS1.Third == ICK_Identity)
2171 return Result == ImplicitConversionSequence::Worse
2172 ? ImplicitConversionSequence::Indistinguishable
2173 : ImplicitConversionSequence::Better;
2174
2175 if (SCS2.Third == ICK_Identity)
2176 return Result == ImplicitConversionSequence::Better
2177 ? ImplicitConversionSequence::Indistinguishable
2178 : ImplicitConversionSequence::Worse;
2179
2180 return ImplicitConversionSequence::Indistinguishable;
2181}
2182
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002183/// CompareStandardConversionSequences - Compare two standard
2184/// conversion sequences to determine whether one is better than the
2185/// other or if they are indistinguishable (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002186ImplicitConversionSequence::CompareKind
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002187Sema::CompareStandardConversionSequences(const StandardConversionSequence& SCS1,
2188 const StandardConversionSequence& SCS2)
2189{
2190 // Standard conversion sequence S1 is a better conversion sequence
2191 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2192
2193 // -- S1 is a proper subsequence of S2 (comparing the conversion
2194 // sequences in the canonical form defined by 13.3.3.1.1,
2195 // excluding any Lvalue Transformation; the identity conversion
2196 // sequence is considered to be a subsequence of any
2197 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00002198 if (ImplicitConversionSequence::CompareKind CK
2199 = compareStandardConversionSubsets(Context, SCS1, SCS2))
2200 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002201
2202 // -- the rank of S1 is better than the rank of S2 (by the rules
2203 // defined below), or, if not that,
2204 ImplicitConversionRank Rank1 = SCS1.getRank();
2205 ImplicitConversionRank Rank2 = SCS2.getRank();
2206 if (Rank1 < Rank2)
2207 return ImplicitConversionSequence::Better;
2208 else if (Rank2 < Rank1)
2209 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002210
Douglas Gregor57373262008-10-22 14:17:15 +00002211 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2212 // are indistinguishable unless one of the following rules
2213 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00002214
Douglas Gregor57373262008-10-22 14:17:15 +00002215 // A conversion that is not a conversion of a pointer, or
2216 // pointer to member, to bool is better than another conversion
2217 // that is such a conversion.
2218 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2219 return SCS2.isPointerConversionToBool()
2220 ? ImplicitConversionSequence::Better
2221 : ImplicitConversionSequence::Worse;
2222
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002223 // C++ [over.ics.rank]p4b2:
2224 //
2225 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002226 // conversion of B* to A* is better than conversion of B* to
2227 // void*, and conversion of A* to void* is better than conversion
2228 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00002229 bool SCS1ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002230 = SCS1.isPointerConversionToVoidPointer(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002231 bool SCS2ConvertsToVoid
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002232 = SCS2.isPointerConversionToVoidPointer(Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002233 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2234 // Exactly one of the conversion sequences is a conversion to
2235 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002236 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2237 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002238 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2239 // Neither conversion sequence converts to a void pointer; compare
2240 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002241 if (ImplicitConversionSequence::CompareKind DerivedCK
2242 = CompareDerivedToBaseConversions(SCS1, SCS2))
2243 return DerivedCK;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002244 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2245 // Both conversion sequences are conversions to void
2246 // pointers. Compare the source types to determine if there's an
2247 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00002248 QualType FromType1 = SCS1.getFromType();
2249 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002250
2251 // Adjust the types we're converting from via the array-to-pointer
2252 // conversion, if we need to.
2253 if (SCS1.First == ICK_Array_To_Pointer)
2254 FromType1 = Context.getArrayDecayedType(FromType1);
2255 if (SCS2.First == ICK_Array_To_Pointer)
2256 FromType2 = Context.getArrayDecayedType(FromType2);
2257
Douglas Gregor01919692009-12-13 21:37:05 +00002258 QualType FromPointee1
2259 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2260 QualType FromPointee2
2261 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002262
Douglas Gregor01919692009-12-13 21:37:05 +00002263 if (IsDerivedFrom(FromPointee2, FromPointee1))
2264 return ImplicitConversionSequence::Better;
2265 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2266 return ImplicitConversionSequence::Worse;
2267
2268 // Objective-C++: If one interface is more specific than the
2269 // other, it is the better one.
John McCallc12c5bb2010-05-15 11:32:37 +00002270 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2271 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor01919692009-12-13 21:37:05 +00002272 if (FromIface1 && FromIface1) {
2273 if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2274 return ImplicitConversionSequence::Better;
2275 else if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2276 return ImplicitConversionSequence::Worse;
2277 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002278 }
Douglas Gregor57373262008-10-22 14:17:15 +00002279
2280 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2281 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00002282 if (ImplicitConversionSequence::CompareKind QualCK
Douglas Gregor57373262008-10-22 14:17:15 +00002283 = CompareQualificationConversions(SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002284 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00002285
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002286 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002287 // C++0x [over.ics.rank]p3b4:
2288 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2289 // implicit object parameter of a non-static member function declared
2290 // without a ref-qualifier, and S1 binds an rvalue reference to an
2291 // rvalue and S2 binds an lvalue reference.
Sebastian Redla9845802009-03-29 15:27:50 +00002292 // FIXME: We don't know if we're dealing with the implicit object parameter,
2293 // or if the member function in this case has a ref qualifier.
2294 // (Of course, we don't have ref qualifiers yet.)
2295 if (SCS1.RRefBinding != SCS2.RRefBinding)
2296 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2297 : ImplicitConversionSequence::Worse;
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002298
2299 // C++ [over.ics.rank]p3b4:
2300 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2301 // which the references refer are the same type except for
2302 // top-level cv-qualifiers, and the type to which the reference
2303 // initialized by S2 refers is more cv-qualified than the type
2304 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00002305 QualType T1 = SCS1.getToType(2);
2306 QualType T2 = SCS2.getToType(2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002307 T1 = Context.getCanonicalType(T1);
2308 T2 = Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002309 Qualifiers T1Quals, T2Quals;
2310 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2311 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2312 if (UnqualT1 == UnqualT2) {
2313 // If the type is an array type, promote the element qualifiers to the type
2314 // for comparison.
2315 if (isa<ArrayType>(T1) && T1Quals)
2316 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2317 if (isa<ArrayType>(T2) && T2Quals)
2318 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002319 if (T2.isMoreQualifiedThan(T1))
2320 return ImplicitConversionSequence::Better;
2321 else if (T1.isMoreQualifiedThan(T2))
2322 return ImplicitConversionSequence::Worse;
2323 }
2324 }
Douglas Gregor57373262008-10-22 14:17:15 +00002325
2326 return ImplicitConversionSequence::Indistinguishable;
2327}
2328
2329/// CompareQualificationConversions - Compares two standard conversion
2330/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00002331/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2332ImplicitConversionSequence::CompareKind
Douglas Gregor57373262008-10-22 14:17:15 +00002333Sema::CompareQualificationConversions(const StandardConversionSequence& SCS1,
Mike Stump1eb44332009-09-09 15:08:12 +00002334 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00002335 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00002336 // -- S1 and S2 differ only in their qualification conversion and
2337 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2338 // cv-qualification signature of type T1 is a proper subset of
2339 // the cv-qualification signature of type T2, and S1 is not the
2340 // deprecated string literal array-to-pointer conversion (4.2).
2341 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2342 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2343 return ImplicitConversionSequence::Indistinguishable;
2344
2345 // FIXME: the example in the standard doesn't use a qualification
2346 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00002347 QualType T1 = SCS1.getToType(2);
2348 QualType T2 = SCS2.getToType(2);
Douglas Gregor57373262008-10-22 14:17:15 +00002349 T1 = Context.getCanonicalType(T1);
2350 T2 = Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002351 Qualifiers T1Quals, T2Quals;
2352 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2353 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00002354
2355 // If the types are the same, we won't learn anything by unwrapped
2356 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00002357 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00002358 return ImplicitConversionSequence::Indistinguishable;
2359
Chandler Carruth28e318c2009-12-29 07:16:59 +00002360 // If the type is an array type, promote the element qualifiers to the type
2361 // for comparison.
2362 if (isa<ArrayType>(T1) && T1Quals)
2363 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2364 if (isa<ArrayType>(T2) && T2Quals)
2365 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2366
Mike Stump1eb44332009-09-09 15:08:12 +00002367 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00002368 = ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002369 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00002370 // Within each iteration of the loop, we check the qualifiers to
2371 // determine if this still looks like a qualification
2372 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002373 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00002374 // until there are no more pointers or pointers-to-members left
2375 // to unwrap. This essentially mimics what
2376 // IsQualificationConversion does, but here we're checking for a
2377 // strict subset of qualifiers.
2378 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2379 // The qualifiers are the same, so this doesn't tell us anything
2380 // about how the sequences rank.
2381 ;
2382 else if (T2.isMoreQualifiedThan(T1)) {
2383 // T1 has fewer qualifiers, so it could be the better sequence.
2384 if (Result == ImplicitConversionSequence::Worse)
2385 // Neither has qualifiers that are a subset of the other's
2386 // qualifiers.
2387 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002388
Douglas Gregor57373262008-10-22 14:17:15 +00002389 Result = ImplicitConversionSequence::Better;
2390 } else if (T1.isMoreQualifiedThan(T2)) {
2391 // T2 has fewer qualifiers, so it could be the better sequence.
2392 if (Result == ImplicitConversionSequence::Better)
2393 // Neither has qualifiers that are a subset of the other's
2394 // qualifiers.
2395 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00002396
Douglas Gregor57373262008-10-22 14:17:15 +00002397 Result = ImplicitConversionSequence::Worse;
2398 } else {
2399 // Qualifiers are disjoint.
2400 return ImplicitConversionSequence::Indistinguishable;
2401 }
2402
2403 // If the types after this point are equivalent, we're done.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002404 if (Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00002405 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002406 }
2407
Douglas Gregor57373262008-10-22 14:17:15 +00002408 // Check that the winning standard conversion sequence isn't using
2409 // the deprecated string literal array to pointer conversion.
2410 switch (Result) {
2411 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00002412 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002413 Result = ImplicitConversionSequence::Indistinguishable;
2414 break;
2415
2416 case ImplicitConversionSequence::Indistinguishable:
2417 break;
2418
2419 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00002420 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00002421 Result = ImplicitConversionSequence::Indistinguishable;
2422 break;
2423 }
2424
2425 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002426}
2427
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002428/// CompareDerivedToBaseConversions - Compares two standard conversion
2429/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00002430/// various kinds of derived-to-base conversions (C++
2431/// [over.ics.rank]p4b3). As part of these checks, we also look at
2432/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002433ImplicitConversionSequence::CompareKind
2434Sema::CompareDerivedToBaseConversions(const StandardConversionSequence& SCS1,
2435 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00002436 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002437 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00002438 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00002439 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002440
2441 // Adjust the types we're converting from via the array-to-pointer
2442 // conversion, if we need to.
2443 if (SCS1.First == ICK_Array_To_Pointer)
2444 FromType1 = Context.getArrayDecayedType(FromType1);
2445 if (SCS2.First == ICK_Array_To_Pointer)
2446 FromType2 = Context.getArrayDecayedType(FromType2);
2447
2448 // Canonicalize all of the types.
2449 FromType1 = Context.getCanonicalType(FromType1);
2450 ToType1 = Context.getCanonicalType(ToType1);
2451 FromType2 = Context.getCanonicalType(FromType2);
2452 ToType2 = Context.getCanonicalType(ToType2);
2453
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002454 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002455 //
2456 // If class B is derived directly or indirectly from class A and
2457 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00002458 //
2459 // For Objective-C, we let A, B, and C also be Objective-C
2460 // interfaces.
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002461
2462 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00002463 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00002464 SCS2.Second == ICK_Pointer_Conversion &&
2465 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2466 FromType1->isPointerType() && FromType2->isPointerType() &&
2467 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002468 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002469 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00002470 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00002471 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002472 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002473 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002474 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00002475 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002476
John McCallc12c5bb2010-05-15 11:32:37 +00002477 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2478 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2479 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2480 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00002481
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002482 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002483 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2484 if (IsDerivedFrom(ToPointee1, ToPointee2))
2485 return ImplicitConversionSequence::Better;
2486 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2487 return ImplicitConversionSequence::Worse;
Douglas Gregorcb7de522008-11-26 23:31:11 +00002488
2489 if (ToIface1 && ToIface2) {
2490 if (Context.canAssignObjCInterfaces(ToIface2, ToIface1))
2491 return ImplicitConversionSequence::Better;
2492 else if (Context.canAssignObjCInterfaces(ToIface1, ToIface2))
2493 return ImplicitConversionSequence::Worse;
2494 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002495 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002496
2497 // -- conversion of B* to A* is better than conversion of C* to A*,
2498 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
2499 if (IsDerivedFrom(FromPointee2, FromPointee1))
2500 return ImplicitConversionSequence::Better;
2501 else if (IsDerivedFrom(FromPointee1, FromPointee2))
2502 return ImplicitConversionSequence::Worse;
Mike Stump1eb44332009-09-09 15:08:12 +00002503
Douglas Gregorcb7de522008-11-26 23:31:11 +00002504 if (FromIface1 && FromIface2) {
2505 if (Context.canAssignObjCInterfaces(FromIface1, FromIface2))
2506 return ImplicitConversionSequence::Better;
2507 else if (Context.canAssignObjCInterfaces(FromIface2, FromIface1))
2508 return ImplicitConversionSequence::Worse;
2509 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002510 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002511 }
2512
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002513 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002514 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2515 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2516 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2517 const MemberPointerType * FromMemPointer1 =
2518 FromType1->getAs<MemberPointerType>();
2519 const MemberPointerType * ToMemPointer1 =
2520 ToType1->getAs<MemberPointerType>();
2521 const MemberPointerType * FromMemPointer2 =
2522 FromType2->getAs<MemberPointerType>();
2523 const MemberPointerType * ToMemPointer2 =
2524 ToType2->getAs<MemberPointerType>();
2525 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2526 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2527 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2528 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2529 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2530 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2531 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2532 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00002533 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00002534 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
2535 if (IsDerivedFrom(ToPointee1, ToPointee2))
2536 return ImplicitConversionSequence::Worse;
2537 else if (IsDerivedFrom(ToPointee2, ToPointee1))
2538 return ImplicitConversionSequence::Better;
2539 }
2540 // conversion of B::* to C::* is better than conversion of A::* to C::*
2541 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
2542 if (IsDerivedFrom(FromPointee1, FromPointee2))
2543 return ImplicitConversionSequence::Better;
2544 else if (IsDerivedFrom(FromPointee2, FromPointee1))
2545 return ImplicitConversionSequence::Worse;
2546 }
2547 }
2548
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002549 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002550 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00002551 // -- binding of an expression of type C to a reference of type
2552 // B& is better than binding an expression of type C to a
2553 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002554 if (Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2555 !Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002556 if (IsDerivedFrom(ToType1, ToType2))
2557 return ImplicitConversionSequence::Better;
2558 else if (IsDerivedFrom(ToType2, ToType1))
2559 return ImplicitConversionSequence::Worse;
2560 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002561
Douglas Gregor225c41e2008-11-03 19:09:14 +00002562 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00002563 // -- binding of an expression of type B to a reference of type
2564 // A& is better than binding an expression of type C to a
2565 // reference of type A&,
Douglas Gregora4923eb2009-11-16 21:35:15 +00002566 if (!Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2567 Context.hasSameUnqualifiedType(ToType1, ToType2)) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00002568 if (IsDerivedFrom(FromType2, FromType1))
2569 return ImplicitConversionSequence::Better;
2570 else if (IsDerivedFrom(FromType1, FromType2))
2571 return ImplicitConversionSequence::Worse;
2572 }
2573 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002574
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002575 return ImplicitConversionSequence::Indistinguishable;
2576}
2577
Douglas Gregorabe183d2010-04-13 16:31:36 +00002578/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2579/// determine whether they are reference-related,
2580/// reference-compatible, reference-compatible with added
2581/// qualification, or incompatible, for use in C++ initialization by
2582/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2583/// type, and the first type (T1) is the pointee type of the reference
2584/// type being initialized.
2585Sema::ReferenceCompareResult
2586Sema::CompareReferenceRelationship(SourceLocation Loc,
2587 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00002588 bool &DerivedToBase,
2589 bool &ObjCConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002590 assert(!OrigT1->isReferenceType() &&
2591 "T1 must be the pointee type of the reference type");
2592 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2593
2594 QualType T1 = Context.getCanonicalType(OrigT1);
2595 QualType T2 = Context.getCanonicalType(OrigT2);
2596 Qualifiers T1Quals, T2Quals;
2597 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2598 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2599
2600 // C++ [dcl.init.ref]p4:
2601 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2602 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2603 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00002604 DerivedToBase = false;
2605 ObjCConversion = false;
2606 if (UnqualT1 == UnqualT2) {
2607 // Nothing to do.
2608 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00002609 IsDerivedFrom(UnqualT2, UnqualT1))
2610 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00002611 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2612 UnqualT2->isObjCObjectOrInterfaceType() &&
2613 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2614 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002615 else
2616 return Ref_Incompatible;
2617
2618 // At this point, we know that T1 and T2 are reference-related (at
2619 // least).
2620
2621 // If the type is an array type, promote the element qualifiers to the type
2622 // for comparison.
2623 if (isa<ArrayType>(T1) && T1Quals)
2624 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2625 if (isa<ArrayType>(T2) && T2Quals)
2626 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2627
2628 // C++ [dcl.init.ref]p4:
2629 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2630 // reference-related to T2 and cv1 is the same cv-qualification
2631 // as, or greater cv-qualification than, cv2. For purposes of
2632 // overload resolution, cases for which cv1 is greater
2633 // cv-qualification than cv2 are identified as
2634 // reference-compatible with added qualification (see 13.3.3.2).
2635 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2636 return Ref_Compatible;
2637 else if (T1.isMoreQualifiedThan(T2))
2638 return Ref_Compatible_With_Added_Qualification;
2639 else
2640 return Ref_Related;
2641}
2642
Douglas Gregor604eb652010-08-11 02:15:33 +00002643/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00002644/// with DeclType. Return true if something definite is found.
2645static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00002646FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2647 QualType DeclType, SourceLocation DeclLoc,
2648 Expr *Init, QualType T2, bool AllowRvalues,
2649 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00002650 assert(T2->isRecordType() && "Can only find conversions of record types.");
2651 CXXRecordDecl *T2RecordDecl
2652 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2653
Douglas Gregor604eb652010-08-11 02:15:33 +00002654 QualType ToType
2655 = AllowRvalues? DeclType->getAs<ReferenceType>()->getPointeeType()
2656 : DeclType;
2657
Sebastian Redl4680bf22010-06-30 18:13:39 +00002658 OverloadCandidateSet CandidateSet(DeclLoc);
2659 const UnresolvedSetImpl *Conversions
2660 = T2RecordDecl->getVisibleConversionFunctions();
2661 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2662 E = Conversions->end(); I != E; ++I) {
2663 NamedDecl *D = *I;
2664 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2665 if (isa<UsingShadowDecl>(D))
2666 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2667
2668 FunctionTemplateDecl *ConvTemplate
2669 = dyn_cast<FunctionTemplateDecl>(D);
2670 CXXConversionDecl *Conv;
2671 if (ConvTemplate)
2672 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2673 else
2674 Conv = cast<CXXConversionDecl>(D);
2675
Douglas Gregor604eb652010-08-11 02:15:33 +00002676 // If this is an explicit conversion, and we're not allowed to consider
2677 // explicit conversions, skip it.
2678 if (!AllowExplicit && Conv->isExplicit())
2679 continue;
2680
2681 if (AllowRvalues) {
2682 bool DerivedToBase = false;
2683 bool ObjCConversion = false;
2684 if (!ConvTemplate &&
2685 S.CompareReferenceRelationship(DeclLoc,
2686 Conv->getConversionType().getNonReferenceType().getUnqualifiedType(),
2687 DeclType.getNonReferenceType().getUnqualifiedType(),
2688 DerivedToBase, ObjCConversion)
2689 == Sema::Ref_Incompatible)
2690 continue;
2691 } else {
2692 // If the conversion function doesn't return a reference type,
2693 // it can't be considered for this conversion. An rvalue reference
2694 // is only acceptable if its referencee is a function type.
2695
2696 const ReferenceType *RefType =
2697 Conv->getConversionType()->getAs<ReferenceType>();
2698 if (!RefType ||
2699 (!RefType->isLValueReferenceType() &&
2700 !RefType->getPointeeType()->isFunctionType()))
2701 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002702 }
Douglas Gregor604eb652010-08-11 02:15:33 +00002703
2704 if (ConvTemplate)
2705 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2706 Init, ToType, CandidateSet);
2707 else
2708 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2709 ToType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00002710 }
2711
2712 OverloadCandidateSet::iterator Best;
2713 switch (S.BestViableFunction(CandidateSet, DeclLoc, Best)) {
2714 case OR_Success:
2715 // C++ [over.ics.ref]p1:
2716 //
2717 // [...] If the parameter binds directly to the result of
2718 // applying a conversion function to the argument
2719 // expression, the implicit conversion sequence is a
2720 // user-defined conversion sequence (13.3.3.1.2), with the
2721 // second standard conversion sequence either an identity
2722 // conversion or, if the conversion function returns an
2723 // entity of a type that is a derived class of the parameter
2724 // type, a derived-to-base Conversion.
2725 if (!Best->FinalConversion.DirectBinding)
2726 return false;
2727
2728 ICS.setUserDefined();
2729 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2730 ICS.UserDefined.After = Best->FinalConversion;
2731 ICS.UserDefined.ConversionFunction = Best->Function;
2732 ICS.UserDefined.EllipsisConversion = false;
2733 assert(ICS.UserDefined.After.ReferenceBinding &&
2734 ICS.UserDefined.After.DirectBinding &&
2735 "Expected a direct reference binding!");
2736 return true;
2737
2738 case OR_Ambiguous:
2739 ICS.setAmbiguous();
2740 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2741 Cand != CandidateSet.end(); ++Cand)
2742 if (Cand->Viable)
2743 ICS.Ambiguous.addConversion(Cand->Function);
2744 return true;
2745
2746 case OR_No_Viable_Function:
2747 case OR_Deleted:
2748 // There was no suitable conversion, or we found a deleted
2749 // conversion; continue with other checks.
2750 return false;
2751 }
Eric Christopher1c3d5022010-06-30 18:36:32 +00002752
2753 return false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002754}
2755
Douglas Gregorabe183d2010-04-13 16:31:36 +00002756/// \brief Compute an implicit conversion sequence for reference
2757/// initialization.
2758static ImplicitConversionSequence
2759TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2760 SourceLocation DeclLoc,
2761 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00002762 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002763 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2764
2765 // Most paths end in a failed conversion.
2766 ImplicitConversionSequence ICS;
2767 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2768
2769 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2770 QualType T2 = Init->getType();
2771
2772 // If the initializer is the address of an overloaded function, try
2773 // to resolve the overloaded function. If all goes well, T2 is the
2774 // type of the resulting function.
2775 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2776 DeclAccessPair Found;
2777 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2778 false, Found))
2779 T2 = Fn->getType();
2780 }
2781
2782 // Compute some basic properties of the types and the initializer.
2783 bool isRValRef = DeclType->isRValueReferenceType();
2784 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00002785 bool ObjCConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002786 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002787 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00002788 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
2789 ObjCConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002790
Douglas Gregorabe183d2010-04-13 16:31:36 +00002791
Sebastian Redl4680bf22010-06-30 18:13:39 +00002792 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00002793 // A reference to type "cv1 T1" is initialized by an expression
2794 // of type "cv2 T2" as follows:
2795
Sebastian Redl4680bf22010-06-30 18:13:39 +00002796 // -- If reference is an lvalue reference and the initializer expression
2797 // The next bullet point (T1 is a function) is pretty much equivalent to this
2798 // one, so it's handled here.
2799 if (!isRValRef || T1->isFunctionType()) {
2800 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2801 // reference-compatible with "cv2 T2," or
2802 //
2803 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2804 if (InitCategory.isLValue() &&
2805 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002806 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00002807 // When a parameter of reference type binds directly (8.5.3)
2808 // to an argument expression, the implicit conversion sequence
2809 // is the identity conversion, unless the argument expression
2810 // has a type that is a derived class of the parameter type,
2811 // in which case the implicit conversion sequence is a
2812 // derived-to-base Conversion (13.3.3.1).
2813 ICS.setStandard();
2814 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00002815 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2816 : ObjCConversion? ICK_Compatible_Conversion
2817 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002818 ICS.Standard.Third = ICK_Identity;
2819 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2820 ICS.Standard.setToType(0, T2);
2821 ICS.Standard.setToType(1, T1);
2822 ICS.Standard.setToType(2, T1);
2823 ICS.Standard.ReferenceBinding = true;
2824 ICS.Standard.DirectBinding = true;
2825 ICS.Standard.RRefBinding = isRValRef;
2826 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002827
Sebastian Redl4680bf22010-06-30 18:13:39 +00002828 // Nothing more to do: the inaccessibility/ambiguity check for
2829 // derived-to-base conversions is suppressed when we're
2830 // computing the implicit conversion sequence (C++
2831 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00002832 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00002833 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00002834
Sebastian Redl4680bf22010-06-30 18:13:39 +00002835 // -- has a class type (i.e., T2 is a class type), where T1 is
2836 // not reference-related to T2, and can be implicitly
2837 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2838 // is reference-compatible with "cv3 T3" 92) (this
2839 // conversion is selected by enumerating the applicable
2840 // conversion functions (13.3.1.6) and choosing the best
2841 // one through overload resolution (13.3)),
2842 if (!SuppressUserConversions && T2->isRecordType() &&
2843 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2844 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00002845 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2846 Init, T2, /*AllowRvalues=*/false,
2847 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00002848 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002849 }
2850 }
2851
Sebastian Redl4680bf22010-06-30 18:13:39 +00002852 // -- Otherwise, the reference shall be an lvalue reference to a
2853 // non-volatile const type (i.e., cv1 shall be const), or the reference
2854 // shall be an rvalue reference and the initializer expression shall be
2855 // an rvalue or have a function type.
Douglas Gregor66821b52010-04-18 09:22:00 +00002856 //
2857 // We actually handle one oddity of C++ [over.ics.ref] at this
2858 // point, which is that, due to p2 (which short-circuits reference
2859 // binding by only attempting a simple conversion for non-direct
2860 // bindings) and p3's strange wording, we allow a const volatile
2861 // reference to bind to an rvalue. Hence the check for the presence
2862 // of "const" rather than checking for "const" being the only
2863 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00002864 // This is also the point where rvalue references and lvalue inits no longer
2865 // go together.
2866 if ((!isRValRef && !T1.isConstQualified()) ||
2867 (isRValRef && InitCategory.isLValue()))
Douglas Gregorabe183d2010-04-13 16:31:36 +00002868 return ICS;
2869
Sebastian Redl4680bf22010-06-30 18:13:39 +00002870 // -- If T1 is a function type, then
2871 // -- if T2 is the same type as T1, the reference is bound to the
2872 // initializer expression lvalue;
2873 // -- if T2 is a class type and the initializer expression can be
2874 // implicitly converted to an lvalue of type T1 [...], the
2875 // reference is bound to the function lvalue that is the result
2876 // of the conversion;
2877 // This is the same as for the lvalue case above, so it was handled there.
2878 // -- otherwise, the program is ill-formed.
2879 // This is the one difference to the lvalue case.
2880 if (T1->isFunctionType())
2881 return ICS;
2882
2883 // -- Otherwise, if T2 is a class type and
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002884 // -- the initializer expression is an rvalue and "cv1 T1"
2885 // is reference-compatible with "cv2 T2," or
Douglas Gregorabe183d2010-04-13 16:31:36 +00002886 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002887 // -- T1 is not reference-related to T2 and the initializer
2888 // expression can be implicitly converted to an rvalue
2889 // of type "cv3 T3" (this conversion is selected by
2890 // enumerating the applicable conversion functions
2891 // (13.3.1.6) and choosing the best one through overload
2892 // resolution (13.3)),
Douglas Gregorabe183d2010-04-13 16:31:36 +00002893 //
Douglas Gregor9dc58bb2010-04-18 08:46:23 +00002894 // then the reference is bound to the initializer
2895 // expression rvalue in the first case and to the object
2896 // that is the result of the conversion in the second case
2897 // (or, in either case, to the appropriate base class
2898 // subobject of the object).
Douglas Gregor604eb652010-08-11 02:15:33 +00002899 if (T2->isRecordType()) {
2900 // First case: "cv1 T1" is reference-compatible with "cv2 T2". This is a
2901 // direct binding in C++0x but not in C++03.
2902 if (InitCategory.isRValue() &&
2903 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
2904 ICS.setStandard();
2905 ICS.Standard.First = ICK_Identity;
2906 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2907 : ObjCConversion? ICK_Compatible_Conversion
2908 : ICK_Identity;
2909 ICS.Standard.Third = ICK_Identity;
2910 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2911 ICS.Standard.setToType(0, T2);
2912 ICS.Standard.setToType(1, T1);
2913 ICS.Standard.setToType(2, T1);
2914 ICS.Standard.ReferenceBinding = true;
2915 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
2916 ICS.Standard.RRefBinding = isRValRef;
2917 ICS.Standard.CopyConstructor = 0;
2918 return ICS;
2919 }
2920
2921 // Second case: not reference-related.
2922 if (RefRelationship == Sema::Ref_Incompatible &&
2923 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2924 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2925 Init, T2, /*AllowRvalues=*/true,
2926 AllowExplicit))
2927 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00002928 }
Douglas Gregor604eb652010-08-11 02:15:33 +00002929
Douglas Gregorabe183d2010-04-13 16:31:36 +00002930 // -- Otherwise, a temporary of type "cv1 T1" is created and
2931 // initialized from the initializer expression using the
2932 // rules for a non-reference copy initialization (8.5). The
2933 // reference is then bound to the temporary. If T1 is
2934 // reference-related to T2, cv1 must be the same
2935 // cv-qualification as, or greater cv-qualification than,
2936 // cv2; otherwise, the program is ill-formed.
2937 if (RefRelationship == Sema::Ref_Related) {
2938 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
2939 // we would be reference-compatible or reference-compatible with
2940 // added qualification. But that wasn't the case, so the reference
2941 // initialization fails.
2942 return ICS;
2943 }
2944
2945 // If at least one of the types is a class type, the types are not
2946 // related, and we aren't allowed any user conversions, the
2947 // reference binding fails. This case is important for breaking
2948 // recursion, since TryImplicitConversion below will attempt to
2949 // create a temporary through the use of a copy constructor.
2950 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
2951 (T1->isRecordType() || T2->isRecordType()))
2952 return ICS;
2953
2954 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00002955 // When a parameter of reference type is not bound directly to
2956 // an argument expression, the conversion sequence is the one
2957 // required to convert the argument expression to the
2958 // underlying type of the reference according to
2959 // 13.3.3.1. Conceptually, this conversion sequence corresponds
2960 // to copy-initializing a temporary of the underlying type with
2961 // the argument expression. Any difference in top-level
2962 // cv-qualification is subsumed by the initialization itself
2963 // and does not constitute a conversion.
2964 ICS = S.TryImplicitConversion(Init, T1, SuppressUserConversions,
2965 /*AllowExplicit=*/false,
Douglas Gregorabe183d2010-04-13 16:31:36 +00002966 /*InOverloadResolution=*/false);
2967
2968 // Of course, that's still a reference binding.
2969 if (ICS.isStandard()) {
2970 ICS.Standard.ReferenceBinding = true;
2971 ICS.Standard.RRefBinding = isRValRef;
2972 } else if (ICS.isUserDefined()) {
2973 ICS.UserDefined.After.ReferenceBinding = true;
2974 ICS.UserDefined.After.RRefBinding = isRValRef;
2975 }
2976 return ICS;
2977}
2978
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002979/// TryCopyInitialization - Try to copy-initialize a value of type
2980/// ToType from the expression From. Return the implicit conversion
2981/// sequence required to pass this argument, which may be a bad
2982/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00002983/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00002984/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00002985static ImplicitConversionSequence
2986TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregorb7f9e6a2010-04-16 17:53:55 +00002987 bool SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00002988 bool InOverloadResolution) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00002989 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00002990 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00002991 /*FIXME:*/From->getLocStart(),
2992 SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00002993 /*AllowExplicit=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00002994
Douglas Gregor74eb6582010-04-16 17:51:22 +00002995 return S.TryImplicitConversion(From, ToType,
2996 SuppressUserConversions,
2997 /*AllowExplicit=*/false,
Douglas Gregor74eb6582010-04-16 17:51:22 +00002998 InOverloadResolution);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002999}
3000
Douglas Gregor96176b32008-11-18 23:14:02 +00003001/// TryObjectArgumentInitialization - Try to initialize the object
3002/// parameter of the given member function (@c Method) from the
3003/// expression @p From.
3004ImplicitConversionSequence
John McCall651f3ee2010-01-14 03:28:57 +00003005Sema::TryObjectArgumentInitialization(QualType OrigFromType,
John McCall701c89e2009-12-03 04:06:58 +00003006 CXXMethodDecl *Method,
3007 CXXRecordDecl *ActingContext) {
3008 QualType ClassType = Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00003009 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3010 // const volatile object.
3011 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3012 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
3013 QualType ImplicitParamType = Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00003014
3015 // Set up the conversion sequence as a "bad" conversion, to allow us
3016 // to exit early.
3017 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00003018
3019 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00003020 QualType FromType = OrigFromType;
Ted Kremenek6217b802009-07-29 21:53:49 +00003021 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssona552f7c2009-05-01 18:34:30 +00003022 FromType = PT->getPointeeType();
3023
3024 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00003025
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00003026 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor96176b32008-11-18 23:14:02 +00003027 // where X is the class of which the function is a member
3028 // (C++ [over.match.funcs]p4). However, when finding an implicit
3029 // conversion sequence for the argument, we are not allowed to
Mike Stump1eb44332009-09-09 15:08:12 +00003030 // create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00003031 // (C++ [over.match.funcs]p5). We perform a simplified version of
3032 // reference binding here, that allows class rvalues to bind to
3033 // non-constant references.
3034
3035 // First check the qualifiers. We don't care about lvalue-vs-rvalue
3036 // with the implicit object parameter (C++ [over.match.funcs]p5).
3037 QualType FromTypeCanon = Context.getCanonicalType(FromType);
Douglas Gregora4923eb2009-11-16 21:35:15 +00003038 if (ImplicitParamType.getCVRQualifiers()
3039 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00003040 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00003041 ICS.setBad(BadConversionSequence::bad_qualifiers,
3042 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003043 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003044 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003045
3046 // Check that we have either the same type or a derived type. It
3047 // affects the conversion rank.
3048 QualType ClassTypeCanon = Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00003049 ImplicitConversionKind SecondKind;
3050 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3051 SecondKind = ICK_Identity;
3052 } else if (IsDerivedFrom(FromType, ClassType))
3053 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00003054 else {
John McCallb1bdc622010-02-25 01:37:24 +00003055 ICS.setBad(BadConversionSequence::unrelated_class,
3056 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003057 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003058 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003059
3060 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00003061 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00003062 ICS.Standard.setAsIdentityConversion();
3063 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00003064 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003065 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003066 ICS.Standard.ReferenceBinding = true;
3067 ICS.Standard.DirectBinding = true;
Sebastian Redl85002392009-03-29 22:46:24 +00003068 ICS.Standard.RRefBinding = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003069 return ICS;
3070}
3071
3072/// PerformObjectArgumentInitialization - Perform initialization of
3073/// the implicit object parameter for the given Method with the given
3074/// expression.
3075bool
Douglas Gregor5fccd362010-03-03 23:55:11 +00003076Sema::PerformObjectArgumentInitialization(Expr *&From,
3077 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00003078 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00003079 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003080 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00003081 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00003082 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00003083
Ted Kremenek6217b802009-07-29 21:53:49 +00003084 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003085 FromRecordType = PT->getPointeeType();
3086 DestType = Method->getThisType(Context);
3087 } else {
3088 FromRecordType = From->getType();
3089 DestType = ImplicitParamRecordType;
3090 }
3091
John McCall701c89e2009-12-03 04:06:58 +00003092 // Note that we always use the true parent context when performing
3093 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003094 ImplicitConversionSequence ICS
John McCall701c89e2009-12-03 04:06:58 +00003095 = TryObjectArgumentInitialization(From->getType(), Method,
3096 Method->getParent());
John McCall1d318332010-01-12 00:44:57 +00003097 if (ICS.isBad())
Douglas Gregor96176b32008-11-18 23:14:02 +00003098 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00003099 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00003100 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00003101
Douglas Gregor5fccd362010-03-03 23:55:11 +00003102 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall6bb80172010-03-30 21:47:33 +00003103 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor96176b32008-11-18 23:14:02 +00003104
Douglas Gregor5fccd362010-03-03 23:55:11 +00003105 if (!Context.hasSameType(From->getType(), DestType))
Anders Carlssonf1b48b72010-04-24 16:57:13 +00003106 ImpCastExprToType(From, DestType, CastExpr::CK_NoOp,
Sebastian Redl906082e2010-07-20 04:20:21 +00003107 From->getType()->isPointerType() ?
3108 ImplicitCastExpr::RValue : ImplicitCastExpr::LValue);
Douglas Gregor96176b32008-11-18 23:14:02 +00003109 return false;
3110}
3111
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003112/// TryContextuallyConvertToBool - Attempt to contextually convert the
3113/// expression From to bool (C++0x [conv]p3).
3114ImplicitConversionSequence Sema::TryContextuallyConvertToBool(Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00003115 // FIXME: This is pretty broken.
Mike Stump1eb44332009-09-09 15:08:12 +00003116 return TryImplicitConversion(From, Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00003117 // FIXME: Are these flags correct?
3118 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00003119 /*AllowExplicit=*/true,
Anders Carlsson08972922009-08-28 15:33:32 +00003120 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003121}
3122
3123/// PerformContextuallyConvertToBool - Perform a contextual conversion
3124/// of the expression From to bool (C++0x [conv]p3).
3125bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
3126 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(From);
John McCall1d318332010-01-12 00:44:57 +00003127 if (!ICS.isBad())
3128 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003129
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00003130 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00003131 return Diag(From->getSourceRange().getBegin(),
3132 diag::err_typecheck_bool_condition)
3133 << From->getType() << From->getSourceRange();
3134 return true;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003135}
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003136
3137/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3138/// expression From to 'id'.
3139ImplicitConversionSequence Sema::TryContextuallyConvertToObjCId(Expr *From) {
John McCallc12c5bb2010-05-15 11:32:37 +00003140 QualType Ty = Context.getObjCIdType();
3141 return TryImplicitConversion(From, Ty,
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003142 // FIXME: Are these flags correct?
3143 /*SuppressUserConversions=*/false,
3144 /*AllowExplicit=*/true,
3145 /*InOverloadResolution=*/false);
3146}
3147
3148/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3149/// of the expression From to 'id'.
3150bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCallc12c5bb2010-05-15 11:32:37 +00003151 QualType Ty = Context.getObjCIdType();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00003152 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(From);
3153 if (!ICS.isBad())
3154 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3155 return true;
3156}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00003157
Douglas Gregorc30614b2010-06-29 23:17:37 +00003158/// \brief Attempt to convert the given expression to an integral or
3159/// enumeration type.
3160///
3161/// This routine will attempt to convert an expression of class type to an
3162/// integral or enumeration type, if that class type only has a single
3163/// conversion to an integral or enumeration type.
3164///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003165/// \param Loc The source location of the construct that requires the
3166/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00003167///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003168/// \param FromE The expression we're converting from.
3169///
3170/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3171/// have integral or enumeration type.
3172///
3173/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3174/// incomplete class type.
3175///
3176/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3177/// explicit conversion function (because no implicit conversion functions
3178/// were available). This is a recovery mode.
3179///
3180/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3181/// showing which conversion was picked.
3182///
3183/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3184/// conversion function that could convert to integral or enumeration type.
3185///
3186/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3187/// usable conversion function.
3188///
3189/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3190/// function, which may be an extension in this case.
3191///
3192/// \returns The expression, converted to an integral or enumeration type if
3193/// successful.
Douglas Gregorc30614b2010-06-29 23:17:37 +00003194Sema::OwningExprResult
3195Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, ExprArg FromE,
3196 const PartialDiagnostic &NotIntDiag,
3197 const PartialDiagnostic &IncompleteDiag,
3198 const PartialDiagnostic &ExplicitConvDiag,
3199 const PartialDiagnostic &ExplicitConvNote,
3200 const PartialDiagnostic &AmbigDiag,
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003201 const PartialDiagnostic &AmbigNote,
3202 const PartialDiagnostic &ConvDiag) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00003203 Expr *From = static_cast<Expr *>(FromE.get());
3204
3205 // We can't perform any more checking for type-dependent expressions.
3206 if (From->isTypeDependent())
3207 return move(FromE);
3208
3209 // If the expression already has integral or enumeration type, we're golden.
3210 QualType T = From->getType();
3211 if (T->isIntegralOrEnumerationType())
3212 return move(FromE);
3213
3214 // FIXME: Check for missing '()' if T is a function type?
3215
3216 // If we don't have a class type in C++, there's no way we can get an
3217 // expression of integral or enumeration type.
3218 const RecordType *RecordTy = T->getAs<RecordType>();
3219 if (!RecordTy || !getLangOptions().CPlusPlus) {
3220 Diag(Loc, NotIntDiag)
3221 << T << From->getSourceRange();
Douglas Gregoracb0bd82010-06-29 23:25:20 +00003222 return move(FromE);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003223 }
3224
3225 // We must have a complete class type.
3226 if (RequireCompleteType(Loc, T, IncompleteDiag))
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003227 return move(FromE);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003228
3229 // Look for a conversion to an integral or enumeration type.
3230 UnresolvedSet<4> ViableConversions;
3231 UnresolvedSet<4> ExplicitConversions;
3232 const UnresolvedSetImpl *Conversions
3233 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3234
3235 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3236 E = Conversions->end();
3237 I != E;
3238 ++I) {
3239 if (CXXConversionDecl *Conversion
3240 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3241 if (Conversion->getConversionType().getNonReferenceType()
3242 ->isIntegralOrEnumerationType()) {
3243 if (Conversion->isExplicit())
3244 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3245 else
3246 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3247 }
3248 }
3249
3250 switch (ViableConversions.size()) {
3251 case 0:
3252 if (ExplicitConversions.size() == 1) {
3253 DeclAccessPair Found = ExplicitConversions[0];
3254 CXXConversionDecl *Conversion
3255 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3256
3257 // The user probably meant to invoke the given explicit
3258 // conversion; use it.
3259 QualType ConvTy
3260 = Conversion->getConversionType().getNonReferenceType();
3261 std::string TypeStr;
3262 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3263
3264 Diag(Loc, ExplicitConvDiag)
3265 << T << ConvTy
3266 << FixItHint::CreateInsertion(From->getLocStart(),
3267 "static_cast<" + TypeStr + ">(")
3268 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3269 ")");
3270 Diag(Conversion->getLocation(), ExplicitConvNote)
3271 << ConvTy->isEnumeralType() << ConvTy;
3272
3273 // If we aren't in a SFINAE context, build a call to the
3274 // explicit conversion function.
3275 if (isSFINAEContext())
3276 return ExprError();
3277
3278 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
3279 From = BuildCXXMemberCallExpr(FromE.takeAs<Expr>(), Found, Conversion);
3280 FromE = Owned(From);
3281 }
3282
3283 // We'll complain below about a non-integral condition type.
3284 break;
3285
3286 case 1: {
3287 // Apply this conversion.
3288 DeclAccessPair Found = ViableConversions[0];
3289 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor6bc574d2010-06-30 00:20:43 +00003290
3291 CXXConversionDecl *Conversion
3292 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3293 QualType ConvTy
3294 = Conversion->getConversionType().getNonReferenceType();
3295 if (ConvDiag.getDiagID()) {
3296 if (isSFINAEContext())
3297 return ExprError();
3298
3299 Diag(Loc, ConvDiag)
3300 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3301 }
3302
Douglas Gregorc30614b2010-06-29 23:17:37 +00003303 From = BuildCXXMemberCallExpr(FromE.takeAs<Expr>(), Found,
3304 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
3305 FromE = Owned(From);
3306 break;
3307 }
3308
3309 default:
3310 Diag(Loc, AmbigDiag)
3311 << T << From->getSourceRange();
3312 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3313 CXXConversionDecl *Conv
3314 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3315 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3316 Diag(Conv->getLocation(), AmbigNote)
3317 << ConvTy->isEnumeralType() << ConvTy;
3318 }
Douglas Gregoracb0bd82010-06-29 23:25:20 +00003319 return move(FromE);
Douglas Gregorc30614b2010-06-29 23:17:37 +00003320 }
3321
Douglas Gregoracb0bd82010-06-29 23:25:20 +00003322 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorc30614b2010-06-29 23:17:37 +00003323 Diag(Loc, NotIntDiag)
3324 << From->getType() << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00003325
3326 return move(FromE);
3327}
3328
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003329/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00003330/// candidate functions, using the given function call arguments. If
3331/// @p SuppressUserConversions, then don't allow user-defined
3332/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003333///
3334/// \para PartialOverloading true if we are performing "partial" overloading
3335/// based on an incomplete set of function arguments. This feature is used by
3336/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00003337void
3338Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00003339 DeclAccessPair FoundDecl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003340 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00003341 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00003342 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003343 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00003344 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003345 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003346 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00003347 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregore53060f2009-06-25 22:08:12 +00003348 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00003349
Douglas Gregor88a35142008-12-22 05:46:06 +00003350 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003351 if (!isa<CXXConstructorDecl>(Method)) {
3352 // If we get here, it's because we're calling a member function
3353 // that is named without a member access expression (e.g.,
3354 // "this->f") that was either written explicitly or created
3355 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00003356 // function, e.g., X::f(). We use an empty type for the implied
3357 // object argument (C++ [over.call.func]p3), and the acting context
3358 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00003359 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall701c89e2009-12-03 04:06:58 +00003360 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003361 SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003362 return;
3363 }
3364 // We treat a constructor like a non-member function, since its object
3365 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00003366 }
3367
Douglas Gregorfd476482009-11-13 23:59:09 +00003368 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00003369 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00003370
Douglas Gregor7edfb692009-11-23 12:27:39 +00003371 // Overload resolution is always an unevaluated context.
3372 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3373
Douglas Gregor66724ea2009-11-14 01:20:54 +00003374 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3375 // C++ [class.copy]p3:
3376 // A member function template is never instantiated to perform the copy
3377 // of a class object to an object of its class type.
3378 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3379 if (NumArgs == 1 &&
3380 Constructor->isCopyConstructorLikeSpecialization() &&
Douglas Gregor12116062010-02-21 18:30:38 +00003381 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3382 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00003383 return;
3384 }
3385
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003386 // Add this candidate
3387 CandidateSet.push_back(OverloadCandidate());
3388 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003389 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003390 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00003391 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003392 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003393 Candidate.IgnoreObjectArgument = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003394
3395 unsigned NumArgsInProto = Proto->getNumArgs();
3396
3397 // (C++ 13.3.2p2): A candidate function having fewer than m
3398 // parameters is viable only if it has an ellipsis in its parameter
3399 // list (8.3.5).
Douglas Gregor5bd1a112009-09-23 14:56:09 +00003400 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3401 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003402 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003403 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003404 return;
3405 }
3406
3407 // (C++ 13.3.2p2): A candidate function having more than m parameters
3408 // is viable only if the (m+1)st parameter has a default argument
3409 // (8.3.6). For the purposes of overload resolution, the
3410 // parameter list is truncated on the right, so that there are
3411 // exactly m parameters.
3412 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00003413 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003414 // Not enough arguments.
3415 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003416 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003417 return;
3418 }
3419
3420 // Determine the implicit conversion sequences for each of the
3421 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003422 Candidate.Conversions.resize(NumArgs);
3423 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3424 if (ArgIdx < NumArgsInProto) {
3425 // (C++ 13.3.2p3): for F to be a viable function, there shall
3426 // exist for each argument an implicit conversion sequence
3427 // (13.3.3.1) that converts that argument to the corresponding
3428 // parameter of F.
3429 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003430 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003431 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00003432 SuppressUserConversions,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003433 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003434 if (Candidate.Conversions[ArgIdx].isBad()) {
3435 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003436 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00003437 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00003438 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003439 } else {
3440 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3441 // argument for which there is no corresponding parameter is
3442 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003443 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003444 }
3445 }
3446}
3447
Douglas Gregor063daf62009-03-13 18:40:31 +00003448/// \brief Add all of the function declarations in the given function set to
3449/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00003450void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00003451 Expr **Args, unsigned NumArgs,
3452 OverloadCandidateSet& CandidateSet,
3453 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00003454 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00003455 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3456 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003457 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003458 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003459 cast<CXXMethodDecl>(FD)->getParent(),
3460 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003461 CandidateSet, SuppressUserConversions);
3462 else
John McCall9aa472c2010-03-19 07:35:19 +00003463 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00003464 SuppressUserConversions);
3465 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003466 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00003467 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3468 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00003469 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00003470 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00003471 /*FIXME: explicit args */ 0,
John McCall701c89e2009-12-03 04:06:58 +00003472 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00003473 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00003474 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00003475 else
John McCall9aa472c2010-03-19 07:35:19 +00003476 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCalld5532b62009-11-23 01:53:49 +00003477 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00003478 Args, NumArgs, CandidateSet,
3479 SuppressUserConversions);
3480 }
Douglas Gregor364e0212009-06-27 21:05:07 +00003481 }
Douglas Gregor063daf62009-03-13 18:40:31 +00003482}
3483
John McCall314be4e2009-11-17 07:50:12 +00003484/// AddMethodCandidate - Adds a named decl (which is some kind of
3485/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00003486void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003487 QualType ObjectType,
John McCall314be4e2009-11-17 07:50:12 +00003488 Expr **Args, unsigned NumArgs,
3489 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003490 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00003491 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00003492 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00003493
3494 if (isa<UsingShadowDecl>(Decl))
3495 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3496
3497 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3498 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3499 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00003500 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3501 /*ExplicitArgs*/ 0,
John McCall701c89e2009-12-03 04:06:58 +00003502 ObjectType, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00003503 CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003504 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003505 } else {
John McCall9aa472c2010-03-19 07:35:19 +00003506 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall701c89e2009-12-03 04:06:58 +00003507 ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003508 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00003509 }
3510}
3511
Douglas Gregor96176b32008-11-18 23:14:02 +00003512/// AddMethodCandidate - Adds the given C++ member function to the set
3513/// of candidate functions, using the given function call arguments
3514/// and the object argument (@c Object). For example, in a call
3515/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3516/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3517/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00003518/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00003519void
John McCall9aa472c2010-03-19 07:35:19 +00003520Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003521 CXXRecordDecl *ActingContext, QualType ObjectType,
3522 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00003523 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003524 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00003525 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00003526 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00003527 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00003528 assert(!isa<CXXConstructorDecl>(Method) &&
3529 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00003530
Douglas Gregor3f396022009-09-28 04:47:19 +00003531 if (!CandidateSet.isNewCandidate(Method))
3532 return;
3533
Douglas Gregor7edfb692009-11-23 12:27:39 +00003534 // Overload resolution is always an unevaluated context.
3535 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3536
Douglas Gregor96176b32008-11-18 23:14:02 +00003537 // Add this candidate
3538 CandidateSet.push_back(OverloadCandidate());
3539 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003540 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00003541 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003542 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003543 Candidate.IgnoreObjectArgument = false;
Douglas Gregor96176b32008-11-18 23:14:02 +00003544
3545 unsigned NumArgsInProto = Proto->getNumArgs();
3546
3547 // (C++ 13.3.2p2): A candidate function having fewer than m
3548 // parameters is viable only if it has an ellipsis in its parameter
3549 // list (8.3.5).
3550 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3551 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003552 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003553 return;
3554 }
3555
3556 // (C++ 13.3.2p2): A candidate function having more than m parameters
3557 // is viable only if the (m+1)st parameter has a default argument
3558 // (8.3.6). For the purposes of overload resolution, the
3559 // parameter list is truncated on the right, so that there are
3560 // exactly m parameters.
3561 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3562 if (NumArgs < MinRequiredArgs) {
3563 // Not enough arguments.
3564 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003565 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00003566 return;
3567 }
3568
3569 Candidate.Viable = true;
3570 Candidate.Conversions.resize(NumArgs + 1);
3571
John McCall701c89e2009-12-03 04:06:58 +00003572 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00003573 // The implicit object argument is ignored.
3574 Candidate.IgnoreObjectArgument = true;
3575 else {
3576 // Determine the implicit conversion sequence for the object
3577 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00003578 Candidate.Conversions[0]
3579 = TryObjectArgumentInitialization(ObjectType, Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00003580 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00003581 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003582 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00003583 return;
3584 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003585 }
3586
3587 // Determine the implicit conversion sequences for each of the
3588 // arguments.
3589 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3590 if (ArgIdx < NumArgsInProto) {
3591 // (C++ 13.3.2p3): for F to be a viable function, there shall
3592 // exist for each argument an implicit conversion sequence
3593 // (13.3.3.1) that converts that argument to the corresponding
3594 // parameter of F.
3595 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003596 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003597 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003598 SuppressUserConversions,
Anders Carlsson08972922009-08-28 15:33:32 +00003599 /*InOverloadResolution=*/true);
John McCall1d318332010-01-12 00:44:57 +00003600 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00003601 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003602 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00003603 break;
3604 }
3605 } else {
3606 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3607 // argument for which there is no corresponding parameter is
3608 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003609 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00003610 }
3611 }
3612}
Douglas Gregora9333192010-05-08 17:41:32 +00003613
Douglas Gregor6b906862009-08-21 00:16:32 +00003614/// \brief Add a C++ member function template as a candidate to the candidate
3615/// set, using template argument deduction to produce an appropriate member
3616/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003617void
Douglas Gregor6b906862009-08-21 00:16:32 +00003618Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00003619 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003620 CXXRecordDecl *ActingContext,
John McCalld5532b62009-11-23 01:53:49 +00003621 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00003622 QualType ObjectType,
3623 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003624 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003625 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003626 if (!CandidateSet.isNewCandidate(MethodTmpl))
3627 return;
3628
Douglas Gregor6b906862009-08-21 00:16:32 +00003629 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003630 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00003631 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003632 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00003633 // candidate functions in the usual way.113) A given name can refer to one
3634 // or more function templates and also to a set of overloaded non-template
3635 // functions. In such a case, the candidate functions generated from each
3636 // function template are combined with the set of non-template candidate
3637 // functions.
John McCall5769d612010-02-08 23:07:23 +00003638 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00003639 FunctionDecl *Specialization = 0;
3640 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003641 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00003642 Args, NumArgs, Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003643 CandidateSet.push_back(OverloadCandidate());
3644 OverloadCandidate &Candidate = CandidateSet.back();
3645 Candidate.FoundDecl = FoundDecl;
3646 Candidate.Function = MethodTmpl->getTemplatedDecl();
3647 Candidate.Viable = false;
3648 Candidate.FailureKind = ovl_fail_bad_deduction;
3649 Candidate.IsSurrogate = false;
3650 Candidate.IgnoreObjectArgument = false;
3651 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3652 Info);
3653 return;
3654 }
Mike Stump1eb44332009-09-09 15:08:12 +00003655
Douglas Gregor6b906862009-08-21 00:16:32 +00003656 // Add the function template specialization produced by template argument
3657 // deduction as a candidate.
3658 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00003659 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00003660 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00003661 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00003662 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003663 CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00003664}
3665
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003666/// \brief Add a C++ function template specialization as a candidate
3667/// in the candidate set, using template argument deduction to produce
3668/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00003669void
Douglas Gregore53060f2009-06-25 22:08:12 +00003670Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003671 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00003672 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00003673 Expr **Args, unsigned NumArgs,
3674 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003675 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003676 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3677 return;
3678
Douglas Gregore53060f2009-06-25 22:08:12 +00003679 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00003680 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00003681 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00003682 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00003683 // candidate functions in the usual way.113) A given name can refer to one
3684 // or more function templates and also to a set of overloaded non-template
3685 // functions. In such a case, the candidate functions generated from each
3686 // function template are combined with the set of non-template candidate
3687 // functions.
John McCall5769d612010-02-08 23:07:23 +00003688 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00003689 FunctionDecl *Specialization = 0;
3690 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00003691 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00003692 Args, NumArgs, Specialization, Info)) {
John McCall578b69b2009-12-16 08:11:27 +00003693 CandidateSet.push_back(OverloadCandidate());
3694 OverloadCandidate &Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003695 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00003696 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3697 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003698 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00003699 Candidate.IsSurrogate = false;
3700 Candidate.IgnoreObjectArgument = false;
Douglas Gregorff5adac2010-05-08 20:18:54 +00003701 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3702 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00003703 return;
3704 }
Mike Stump1eb44332009-09-09 15:08:12 +00003705
Douglas Gregore53060f2009-06-25 22:08:12 +00003706 // Add the function template specialization produced by template argument
3707 // deduction as a candidate.
3708 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003709 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00003710 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00003711}
Mike Stump1eb44332009-09-09 15:08:12 +00003712
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003713/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00003714/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003715/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00003716/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003717/// (which may or may not be the same type as the type that the
3718/// conversion function produces).
3719void
3720Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003721 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003722 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003723 Expr *From, QualType ToType,
3724 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003725 assert(!Conversion->getDescribedFunctionTemplate() &&
3726 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003727 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00003728 if (!CandidateSet.isNewCandidate(Conversion))
3729 return;
3730
Douglas Gregor7edfb692009-11-23 12:27:39 +00003731 // Overload resolution is always an unevaluated context.
3732 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3733
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003734 // Add this candidate
3735 CandidateSet.push_back(OverloadCandidate());
3736 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003737 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003738 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003739 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00003740 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003741 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003742 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00003743 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003744 Candidate.Viable = true;
3745 Candidate.Conversions.resize(1);
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003746
Douglas Gregorbca39322010-08-19 15:37:02 +00003747 // C++ [over.match.funcs]p4:
3748 // For conversion functions, the function is considered to be a member of
3749 // the class of the implicit implied object argument for the purpose of
3750 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003751 //
3752 // Determine the implicit conversion sequence for the implicit
3753 // object parameter.
3754 QualType ImplicitParamType = From->getType();
3755 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
3756 ImplicitParamType = FromPtrType->getPointeeType();
3757 CXXRecordDecl *ConversionContext
3758 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
3759
3760 Candidate.Conversions[0]
3761 = TryObjectArgumentInitialization(From->getType(), Conversion,
3762 ConversionContext);
3763
John McCall1d318332010-01-12 00:44:57 +00003764 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003765 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003766 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003767 return;
3768 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00003769
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003770 // We won't go through a user-define type conversion function to convert a
3771 // derived to base as such conversions are given Conversion Rank. They only
3772 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3773 QualType FromCanon
3774 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3775 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3776 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3777 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003778 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00003779 return;
3780 }
3781
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003782 // To determine what the conversion from the result of calling the
3783 // conversion function to the type we're eventually trying to
3784 // convert to (ToType), we need to synthesize a call to the
3785 // conversion function and attempt copy initialization from it. This
3786 // makes sure that we get the right semantics with respect to
3787 // lvalues/rvalues and the type. Fortunately, we can allocate this
3788 // call on the stack and we don't need its arguments to be
3789 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00003790 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003791 From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00003792 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
3793 Context.getPointerType(Conversion->getType()),
Eli Friedman73c39ab2009-10-20 08:27:19 +00003794 CastExpr::CK_FunctionToPointerDecay,
John McCallf871d0c2010-08-07 06:22:56 +00003795 &ConversionRef, ImplicitCastExpr::RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00003796
3797 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00003798 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3799 // allocator).
Mike Stump1eb44332009-09-09 15:08:12 +00003800 CallExpr Call(Context, &ConversionFn, 0, 0,
Douglas Gregor63982352010-07-13 18:40:04 +00003801 Conversion->getConversionType().getNonLValueExprType(Context),
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00003802 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00003803 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00003804 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00003805 /*SuppressUserConversions=*/true,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003806 /*InOverloadResolution=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00003807
John McCall1d318332010-01-12 00:44:57 +00003808 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003809 case ImplicitConversionSequence::StandardConversion:
3810 Candidate.FinalConversion = ICS.Standard;
Douglas Gregorc520c842010-04-12 23:42:09 +00003811
3812 // C++ [over.ics.user]p3:
3813 // If the user-defined conversion is specified by a specialization of a
3814 // conversion function template, the second standard conversion sequence
3815 // shall have exact match rank.
3816 if (Conversion->getPrimaryTemplate() &&
3817 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
3818 Candidate.Viable = false;
3819 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
3820 }
3821
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003822 break;
3823
3824 case ImplicitConversionSequence::BadConversion:
3825 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00003826 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003827 break;
3828
3829 default:
Mike Stump1eb44332009-09-09 15:08:12 +00003830 assert(false &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00003831 "Can only end up with a standard conversion sequence or failure");
3832 }
3833}
3834
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003835/// \brief Adds a conversion function template specialization
3836/// candidate to the overload set, using template argument deduction
3837/// to deduce the template arguments of the conversion function
3838/// template from the type that we are converting to (C++
3839/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00003840void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003841Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00003842 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003843 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003844 Expr *From, QualType ToType,
3845 OverloadCandidateSet &CandidateSet) {
3846 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
3847 "Only conversion function templates permitted here");
3848
Douglas Gregor3f396022009-09-28 04:47:19 +00003849 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3850 return;
3851
John McCall5769d612010-02-08 23:07:23 +00003852 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003853 CXXConversionDecl *Specialization = 0;
3854 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00003855 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003856 Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00003857 CandidateSet.push_back(OverloadCandidate());
3858 OverloadCandidate &Candidate = CandidateSet.back();
3859 Candidate.FoundDecl = FoundDecl;
3860 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3861 Candidate.Viable = false;
3862 Candidate.FailureKind = ovl_fail_bad_deduction;
3863 Candidate.IsSurrogate = false;
3864 Candidate.IgnoreObjectArgument = false;
3865 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3866 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003867 return;
3868 }
Mike Stump1eb44332009-09-09 15:08:12 +00003869
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003870 // Add the conversion function template specialization produced by
3871 // template argument deduction as a candidate.
3872 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00003873 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00003874 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00003875}
3876
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003877/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
3878/// converts the given @c Object to a function pointer via the
3879/// conversion function @c Conversion, and then attempts to call it
3880/// with the given arguments (C++ [over.call.object]p2-4). Proto is
3881/// the type of function that we'll eventually be calling.
3882void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00003883 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00003884 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00003885 const FunctionProtoType *Proto,
John McCall701c89e2009-12-03 04:06:58 +00003886 QualType ObjectType,
3887 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003888 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00003889 if (!CandidateSet.isNewCandidate(Conversion))
3890 return;
3891
Douglas Gregor7edfb692009-11-23 12:27:39 +00003892 // Overload resolution is always an unevaluated context.
3893 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
3894
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003895 CandidateSet.push_back(OverloadCandidate());
3896 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00003897 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003898 Candidate.Function = 0;
3899 Candidate.Surrogate = Conversion;
3900 Candidate.Viable = true;
3901 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00003902 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003903 Candidate.Conversions.resize(NumArgs + 1);
3904
3905 // Determine the implicit conversion sequence for the implicit
3906 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00003907 ImplicitConversionSequence ObjectInit
John McCall701c89e2009-12-03 04:06:58 +00003908 = TryObjectArgumentInitialization(ObjectType, Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00003909 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003910 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003911 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00003912 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003913 return;
3914 }
3915
3916 // The first conversion is actually a user-defined conversion whose
3917 // first conversion is ObjectInit's standard conversion (which is
3918 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00003919 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003920 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00003921 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003922 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Mike Stump1eb44332009-09-09 15:08:12 +00003923 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003924 = Candidate.Conversions[0].UserDefined.Before;
3925 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
3926
Mike Stump1eb44332009-09-09 15:08:12 +00003927 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003928 unsigned NumArgsInProto = Proto->getNumArgs();
3929
3930 // (C++ 13.3.2p2): A candidate function having fewer than m
3931 // parameters is viable only if it has an ellipsis in its parameter
3932 // list (8.3.5).
3933 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3934 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003935 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003936 return;
3937 }
3938
3939 // Function types don't have any default arguments, so just check if
3940 // we have enough arguments.
3941 if (NumArgs < NumArgsInProto) {
3942 // Not enough arguments.
3943 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003944 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003945 return;
3946 }
3947
3948 // Determine the implicit conversion sequences for each of the
3949 // arguments.
3950 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3951 if (ArgIdx < NumArgsInProto) {
3952 // (C++ 13.3.2p3): for F to be a viable function, there shall
3953 // exist for each argument an implicit conversion sequence
3954 // (13.3.3.1) that converts that argument to the corresponding
3955 // parameter of F.
3956 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00003957 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00003958 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00003959 /*SuppressUserConversions=*/false,
Anders Carlsson7b361b52009-08-27 17:37:39 +00003960 /*InOverloadResolution=*/false);
John McCall1d318332010-01-12 00:44:57 +00003961 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003962 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00003963 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003964 break;
3965 }
3966 } else {
3967 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3968 // argument for which there is no corresponding parameter is
3969 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00003970 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00003971 }
3972 }
3973}
3974
Douglas Gregor063daf62009-03-13 18:40:31 +00003975/// \brief Add overload candidates for overloaded operators that are
3976/// member functions.
3977///
3978/// Add the overloaded operator candidates that are member functions
3979/// for the operator Op that was used in an operator expression such
3980/// as "x Op y". , Args/NumArgs provides the operator arguments, and
3981/// CandidateSet will store the added overload candidates. (C++
3982/// [over.match.oper]).
3983void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
3984 SourceLocation OpLoc,
3985 Expr **Args, unsigned NumArgs,
3986 OverloadCandidateSet& CandidateSet,
3987 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00003988 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
3989
3990 // C++ [over.match.oper]p3:
3991 // For a unary operator @ with an operand of a type whose
3992 // cv-unqualified version is T1, and for a binary operator @ with
3993 // a left operand of a type whose cv-unqualified version is T1 and
3994 // a right operand of a type whose cv-unqualified version is T2,
3995 // three sets of candidate functions, designated member
3996 // candidates, non-member candidates and built-in candidates, are
3997 // constructed as follows:
3998 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00003999
4000 // -- If T1 is a class type, the set of member candidates is the
4001 // result of the qualified lookup of T1::operator@
4002 // (13.3.1.1.1); otherwise, the set of member candidates is
4003 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00004004 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004005 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00004006 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004007 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004008
John McCalla24dc2e2009-11-17 02:14:36 +00004009 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4010 LookupQualifiedName(Operators, T1Rec->getDecl());
4011 Operators.suppressDiagnostics();
4012
Mike Stump1eb44332009-09-09 15:08:12 +00004013 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00004014 OperEnd = Operators.end();
4015 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00004016 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00004017 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall701c89e2009-12-03 04:06:58 +00004018 Args + 1, NumArgs - 1, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00004019 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00004020 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004021}
4022
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004023/// AddBuiltinCandidate - Add a candidate for a built-in
4024/// operator. ResultTy and ParamTys are the result and parameter types
4025/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004026/// arguments being passed to the candidate. IsAssignmentOperator
4027/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004028/// operator. NumContextualBoolArguments is the number of arguments
4029/// (at the beginning of the argument list) that will be contextually
4030/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00004031void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004032 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004033 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004034 bool IsAssignmentOperator,
4035 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00004036 // Overload resolution is always an unevaluated context.
4037 EnterExpressionEvaluationContext Unevaluated(*this, Action::Unevaluated);
4038
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004039 // Add this candidate
4040 CandidateSet.push_back(OverloadCandidate());
4041 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004042 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004043 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00004044 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004045 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004046 Candidate.BuiltinTypes.ResultTy = ResultTy;
4047 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4048 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4049
4050 // Determine the implicit conversion sequences for each of the
4051 // arguments.
4052 Candidate.Viable = true;
4053 Candidate.Conversions.resize(NumArgs);
4054 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004055 // C++ [over.match.oper]p4:
4056 // For the built-in assignment operators, conversions of the
4057 // left operand are restricted as follows:
4058 // -- no temporaries are introduced to hold the left operand, and
4059 // -- no user-defined conversions are applied to the left
4060 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00004061 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004062 //
4063 // We block these conversions by turning off user-defined
4064 // conversions, since that is the only way that initialization of
4065 // a reference to a non-class type can occur from something that
4066 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004067 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00004068 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004069 "Contextual conversion to bool requires bool type");
4070 Candidate.Conversions[ArgIdx] = TryContextuallyConvertToBool(Args[ArgIdx]);
4071 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00004072 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004073 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00004074 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson7b361b52009-08-27 17:37:39 +00004075 /*InOverloadResolution=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004076 }
John McCall1d318332010-01-12 00:44:57 +00004077 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004078 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004079 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00004080 break;
4081 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004082 }
4083}
4084
4085/// BuiltinCandidateTypeSet - A set of types that will be used for the
4086/// candidate operator functions for built-in operators (C++
4087/// [over.built]). The types are separated into pointer types and
4088/// enumeration types.
4089class BuiltinCandidateTypeSet {
4090 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004091 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004092
4093 /// PointerTypes - The set of pointer types that will be used in the
4094 /// built-in candidates.
4095 TypeSet PointerTypes;
4096
Sebastian Redl78eb8742009-04-19 21:53:20 +00004097 /// MemberPointerTypes - The set of member pointer types that will be
4098 /// used in the built-in candidates.
4099 TypeSet MemberPointerTypes;
4100
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004101 /// EnumerationTypes - The set of enumeration types that will be
4102 /// used in the built-in candidates.
4103 TypeSet EnumerationTypes;
4104
Douglas Gregor26bcf672010-05-19 03:21:00 +00004105 /// \brief The set of vector types that will be used in the built-in
4106 /// candidates.
4107 TypeSet VectorTypes;
4108
Douglas Gregor5842ba92009-08-24 15:23:48 +00004109 /// Sema - The semantic analysis instance where we are building the
4110 /// candidate type set.
4111 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00004112
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004113 /// Context - The AST context in which we will build the type sets.
4114 ASTContext &Context;
4115
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004116 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4117 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00004118 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004119
4120public:
4121 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004122 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004123
Mike Stump1eb44332009-09-09 15:08:12 +00004124 BuiltinCandidateTypeSet(Sema &SemaRef)
Douglas Gregor5842ba92009-08-24 15:23:48 +00004125 : SemaRef(SemaRef), Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004126
Douglas Gregor573d9c32009-10-21 23:19:44 +00004127 void AddTypesConvertedFrom(QualType Ty,
4128 SourceLocation Loc,
4129 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004130 bool AllowExplicitConversions,
4131 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004132
4133 /// pointer_begin - First pointer type found;
4134 iterator pointer_begin() { return PointerTypes.begin(); }
4135
Sebastian Redl78eb8742009-04-19 21:53:20 +00004136 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004137 iterator pointer_end() { return PointerTypes.end(); }
4138
Sebastian Redl78eb8742009-04-19 21:53:20 +00004139 /// member_pointer_begin - First member pointer type found;
4140 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4141
4142 /// member_pointer_end - Past the last member pointer type found;
4143 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4144
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004145 /// enumeration_begin - First enumeration type found;
4146 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4147
Sebastian Redl78eb8742009-04-19 21:53:20 +00004148 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004149 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004150
4151 iterator vector_begin() { return VectorTypes.begin(); }
4152 iterator vector_end() { return VectorTypes.end(); }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004153};
4154
Sebastian Redl78eb8742009-04-19 21:53:20 +00004155/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004156/// the set of pointer types along with any more-qualified variants of
4157/// that type. For example, if @p Ty is "int const *", this routine
4158/// will add "int const *", "int const volatile *", "int const
4159/// restrict *", and "int const volatile restrict *" to the set of
4160/// pointer types. Returns true if the add of @p Ty itself succeeded,
4161/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00004162///
4163/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004164bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00004165BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4166 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00004167
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004168 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00004169 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004170 return false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004171
4172 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00004173 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004174 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004175 if (!PointerTy) {
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004176 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004177 PointeeTy = PTy->getPointeeType();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004178 buildObjCPtr = true;
4179 }
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004180 else
4181 assert(false && "type was not a pointer type!");
4182 }
4183 else
4184 PointeeTy = PointerTy->getPointeeType();
4185
Sebastian Redla9efada2009-11-18 20:39:26 +00004186 // Don't add qualified variants of arrays. For one, they're not allowed
4187 // (the qualifier would sink to the element type), and for another, the
4188 // only overload situation where it matters is subscript or pointer +- int,
4189 // and those shouldn't have qualifier variants anyway.
4190 if (PointeeTy->isArrayType())
4191 return true;
John McCall0953e762009-09-24 19:53:00 +00004192 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00004193 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00004194 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004195 bool hasVolatile = VisibleQuals.hasVolatile();
4196 bool hasRestrict = VisibleQuals.hasRestrict();
4197
John McCall0953e762009-09-24 19:53:00 +00004198 // Iterate through all strict supersets of BaseCVR.
4199 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4200 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004201 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4202 // in the types.
4203 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4204 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00004205 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00004206 if (!buildObjCPtr)
4207 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4208 else
4209 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004210 }
4211
4212 return true;
4213}
4214
Sebastian Redl78eb8742009-04-19 21:53:20 +00004215/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4216/// to 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 McCall0953e762009-09-24 19:53:00 +00004222///
4223/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00004224bool
4225BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4226 QualType Ty) {
4227 // Insert this type.
4228 if (!MemberPointerTypes.insert(Ty))
4229 return false;
4230
John McCall0953e762009-09-24 19:53:00 +00004231 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4232 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00004233
John McCall0953e762009-09-24 19:53:00 +00004234 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00004235 // Don't add qualified variants of arrays. For one, they're not allowed
4236 // (the qualifier would sink to the element type), and for another, the
4237 // only overload situation where it matters is subscript or pointer +- int,
4238 // and those shouldn't have qualifier variants anyway.
4239 if (PointeeTy->isArrayType())
4240 return true;
John McCall0953e762009-09-24 19:53:00 +00004241 const Type *ClassTy = PointerTy->getClass();
4242
4243 // Iterate through all strict supersets of the pointee type's CVR
4244 // qualifiers.
4245 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4246 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4247 if ((CVR | BaseCVR) != CVR) continue;
4248
4249 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
4250 MemberPointerTypes.insert(Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00004251 }
4252
4253 return true;
4254}
4255
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004256/// AddTypesConvertedFrom - Add each of the types to which the type @p
4257/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00004258/// primarily interested in pointer types and enumeration types. We also
4259/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004260/// AllowUserConversions is true if we should look at the conversion
4261/// functions of a class type, and AllowExplicitConversions if we
4262/// should also include the explicit conversion functions of a class
4263/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00004264void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004265BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004266 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004267 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004268 bool AllowExplicitConversions,
4269 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004270 // Only deal with canonical types.
4271 Ty = Context.getCanonicalType(Ty);
4272
4273 // Look through reference types; they aren't part of the type of an
4274 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00004275 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004276 Ty = RefTy->getPointeeType();
4277
4278 // We don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00004279 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004280
Sebastian Redla65b5512009-11-05 16:36:20 +00004281 // If we're dealing with an array type, decay to the pointer.
4282 if (Ty->isArrayType())
4283 Ty = SemaRef.Context.getArrayDecayedType(Ty);
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00004284 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4285 PointerTypes.insert(Ty);
4286 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004287 // Insert our type, and its more-qualified variants, into the set
4288 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004289 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004290 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00004291 } else if (Ty->isMemberPointerType()) {
4292 // Member pointers are far easier, since the pointee can't be converted.
4293 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4294 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004295 } else if (Ty->isEnumeralType()) {
Chris Lattnere37b94c2009-03-29 00:04:01 +00004296 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004297 } else if (Ty->isVectorType()) {
4298 VectorTypes.insert(Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004299 } else if (AllowUserConversions) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004300 if (const RecordType *TyRec = Ty->getAs<RecordType>()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00004301 if (SemaRef.RequireCompleteType(Loc, Ty, 0)) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00004302 // No conversion functions in incomplete types.
4303 return;
4304 }
Mike Stump1eb44332009-09-09 15:08:12 +00004305
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004306 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCalleec51cf2010-01-20 00:46:10 +00004307 const UnresolvedSetImpl *Conversions
Fariborz Jahanianca4fb042009-10-07 17:26:09 +00004308 = ClassDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00004309 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004310 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00004311 NamedDecl *D = I.getDecl();
4312 if (isa<UsingShadowDecl>(D))
4313 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004314
Mike Stump1eb44332009-09-09 15:08:12 +00004315 // Skip conversion function templates; they don't tell us anything
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004316 // about which builtin types we can convert to.
John McCall32daa422010-03-31 01:36:47 +00004317 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004318 continue;
4319
John McCall32daa422010-03-31 01:36:47 +00004320 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004321 if (AllowExplicitConversions || !Conv->isExplicit()) {
Douglas Gregor573d9c32009-10-21 23:19:44 +00004322 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004323 VisibleQuals);
4324 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004325 }
4326 }
4327 }
4328}
4329
Douglas Gregor19b7b152009-08-24 13:43:27 +00004330/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4331/// the volatile- and non-volatile-qualified assignment operators for the
4332/// given type to the candidate set.
4333static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4334 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00004335 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004336 unsigned NumArgs,
4337 OverloadCandidateSet &CandidateSet) {
4338 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00004339
Douglas Gregor19b7b152009-08-24 13:43:27 +00004340 // T& operator=(T&, T)
4341 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4342 ParamTypes[1] = T;
4343 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4344 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00004345
Douglas Gregor19b7b152009-08-24 13:43:27 +00004346 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4347 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00004348 ParamTypes[0]
4349 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00004350 ParamTypes[1] = T;
4351 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00004352 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00004353 }
4354}
Mike Stump1eb44332009-09-09 15:08:12 +00004355
Sebastian Redl9994a342009-10-25 17:03:50 +00004356/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4357/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004358static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4359 Qualifiers VRQuals;
4360 const RecordType *TyRec;
4361 if (const MemberPointerType *RHSMPType =
4362 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00004363 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004364 else
4365 TyRec = ArgExpr->getType()->getAs<RecordType>();
4366 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00004367 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004368 VRQuals.addVolatile();
4369 VRQuals.addRestrict();
4370 return VRQuals;
4371 }
4372
4373 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00004374 if (!ClassDecl->hasDefinition())
4375 return VRQuals;
4376
John McCalleec51cf2010-01-20 00:46:10 +00004377 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00004378 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004379
John McCalleec51cf2010-01-20 00:46:10 +00004380 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00004381 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00004382 NamedDecl *D = I.getDecl();
4383 if (isa<UsingShadowDecl>(D))
4384 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4385 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004386 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4387 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4388 CanTy = ResTypeRef->getPointeeType();
4389 // Need to go down the pointer/mempointer chain and add qualifiers
4390 // as see them.
4391 bool done = false;
4392 while (!done) {
4393 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4394 CanTy = ResTypePtr->getPointeeType();
4395 else if (const MemberPointerType *ResTypeMPtr =
4396 CanTy->getAs<MemberPointerType>())
4397 CanTy = ResTypeMPtr->getPointeeType();
4398 else
4399 done = true;
4400 if (CanTy.isVolatileQualified())
4401 VRQuals.addVolatile();
4402 if (CanTy.isRestrictQualified())
4403 VRQuals.addRestrict();
4404 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4405 return VRQuals;
4406 }
4407 }
4408 }
4409 return VRQuals;
4410}
4411
Douglas Gregor74253732008-11-19 15:42:04 +00004412/// AddBuiltinOperatorCandidates - Add the appropriate built-in
4413/// operator overloads to the candidate set (C++ [over.built]), based
4414/// on the operator @p Op and the arguments given. For example, if the
4415/// operator is a binary '+', this routine might add "int
4416/// operator+(int, int)" to cover integer addition.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004417void
Mike Stump1eb44332009-09-09 15:08:12 +00004418Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
Douglas Gregor573d9c32009-10-21 23:19:44 +00004419 SourceLocation OpLoc,
Douglas Gregor74253732008-11-19 15:42:04 +00004420 Expr **Args, unsigned NumArgs,
4421 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004422 // The set of "promoted arithmetic types", which are the arithmetic
4423 // types are that preserved by promotion (C++ [over.built]p2). Note
4424 // that the first few of these types are the promoted integral
4425 // types; these types need to be first.
4426 // FIXME: What about complex?
4427 const unsigned FirstIntegralType = 0;
4428 const unsigned LastIntegralType = 13;
Mike Stump1eb44332009-09-09 15:08:12 +00004429 const unsigned FirstPromotedIntegralType = 7,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004430 LastPromotedIntegralType = 13;
4431 const unsigned FirstPromotedArithmeticType = 7,
4432 LastPromotedArithmeticType = 16;
4433 const unsigned NumArithmeticTypes = 16;
4434 QualType ArithmeticTypes[NumArithmeticTypes] = {
Mike Stump1eb44332009-09-09 15:08:12 +00004435 Context.BoolTy, Context.CharTy, Context.WCharTy,
4436// FIXME: Context.Char16Ty, Context.Char32Ty,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004437 Context.SignedCharTy, Context.ShortTy,
4438 Context.UnsignedCharTy, Context.UnsignedShortTy,
4439 Context.IntTy, Context.LongTy, Context.LongLongTy,
4440 Context.UnsignedIntTy, Context.UnsignedLongTy, Context.UnsignedLongLongTy,
4441 Context.FloatTy, Context.DoubleTy, Context.LongDoubleTy
4442 };
Douglas Gregor652371a2009-10-21 22:01:30 +00004443 assert(ArithmeticTypes[FirstPromotedIntegralType] == Context.IntTy &&
4444 "Invalid first promoted integral type");
4445 assert(ArithmeticTypes[LastPromotedIntegralType - 1]
4446 == Context.UnsignedLongLongTy &&
4447 "Invalid last promoted integral type");
4448 assert(ArithmeticTypes[FirstPromotedArithmeticType] == Context.IntTy &&
4449 "Invalid first promoted arithmetic type");
4450 assert(ArithmeticTypes[LastPromotedArithmeticType - 1]
4451 == Context.LongDoubleTy &&
4452 "Invalid last promoted arithmetic type");
4453
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004454 // Find all of the types that the arguments can convert to, but only
4455 // if the operator we're looking at has built-in operator candidates
4456 // that make use of these types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004457 Qualifiers VisibleTypeConversionsQuals;
4458 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004459 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4460 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
4461
Douglas Gregor5842ba92009-08-24 15:23:48 +00004462 BuiltinCandidateTypeSet CandidateTypes(*this);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004463 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4464 CandidateTypes.AddTypesConvertedFrom(Args[ArgIdx]->getType(),
4465 OpLoc,
4466 true,
4467 (Op == OO_Exclaim ||
4468 Op == OO_AmpAmp ||
4469 Op == OO_PipePipe),
4470 VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004471
4472 bool isComparison = false;
4473 switch (Op) {
4474 case OO_None:
4475 case NUM_OVERLOADED_OPERATORS:
4476 assert(false && "Expected an overloaded operator");
4477 break;
4478
Douglas Gregor74253732008-11-19 15:42:04 +00004479 case OO_Star: // '*' is either unary or binary
Mike Stump1eb44332009-09-09 15:08:12 +00004480 if (NumArgs == 1)
Douglas Gregor74253732008-11-19 15:42:04 +00004481 goto UnaryStar;
4482 else
4483 goto BinaryStar;
4484 break;
4485
4486 case OO_Plus: // '+' is either unary or binary
4487 if (NumArgs == 1)
4488 goto UnaryPlus;
4489 else
4490 goto BinaryPlus;
4491 break;
4492
4493 case OO_Minus: // '-' is either unary or binary
4494 if (NumArgs == 1)
4495 goto UnaryMinus;
4496 else
4497 goto BinaryMinus;
4498 break;
4499
4500 case OO_Amp: // '&' is either unary or binary
4501 if (NumArgs == 1)
4502 goto UnaryAmp;
4503 else
4504 goto BinaryAmp;
4505
4506 case OO_PlusPlus:
4507 case OO_MinusMinus:
4508 // C++ [over.built]p3:
4509 //
4510 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4511 // is either volatile or empty, there exist candidate operator
4512 // functions of the form
4513 //
4514 // VQ T& operator++(VQ T&);
4515 // T operator++(VQ T&, int);
4516 //
4517 // C++ [over.built]p4:
4518 //
4519 // For every pair (T, VQ), where T is an arithmetic type other
4520 // than bool, and VQ is either volatile or empty, there exist
4521 // candidate operator functions of the form
4522 //
4523 // VQ T& operator--(VQ T&);
4524 // T operator--(VQ T&, int);
Mike Stump1eb44332009-09-09 15:08:12 +00004525 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
Douglas Gregor74253732008-11-19 15:42:04 +00004526 Arith < NumArithmeticTypes; ++Arith) {
4527 QualType ArithTy = ArithmeticTypes[Arith];
Mike Stump1eb44332009-09-09 15:08:12 +00004528 QualType ParamTypes[2]
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004529 = { Context.getLValueReferenceType(ArithTy), Context.IntTy };
Douglas Gregor74253732008-11-19 15:42:04 +00004530
4531 // Non-volatile version.
4532 if (NumArgs == 1)
4533 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4534 else
4535 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004536 // heuristic to reduce number of builtin candidates in the set.
4537 // Add volatile version only if there are conversions to a volatile type.
4538 if (VisibleTypeConversionsQuals.hasVolatile()) {
4539 // Volatile version
4540 ParamTypes[0]
4541 = Context.getLValueReferenceType(Context.getVolatileType(ArithTy));
4542 if (NumArgs == 1)
4543 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4544 else
4545 AddBuiltinCandidate(ArithTy, ParamTypes, Args, 2, CandidateSet);
4546 }
Douglas Gregor74253732008-11-19 15:42:04 +00004547 }
4548
4549 // C++ [over.built]p5:
4550 //
4551 // For every pair (T, VQ), where T is a cv-qualified or
4552 // cv-unqualified object type, and VQ is either volatile or
4553 // empty, there exist candidate operator functions of the form
4554 //
4555 // T*VQ& operator++(T*VQ&);
4556 // T*VQ& operator--(T*VQ&);
4557 // T* operator++(T*VQ&, int);
4558 // T* operator--(T*VQ&, int);
4559 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4560 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4561 // Skip pointer types that aren't pointers to object types.
Eli Friedman13578692010-08-05 02:49:48 +00004562 if (!(*Ptr)->getPointeeType()->isIncompleteOrObjectType())
Douglas Gregor74253732008-11-19 15:42:04 +00004563 continue;
4564
Mike Stump1eb44332009-09-09 15:08:12 +00004565 QualType ParamTypes[2] = {
4566 Context.getLValueReferenceType(*Ptr), Context.IntTy
Douglas Gregor74253732008-11-19 15:42:04 +00004567 };
Mike Stump1eb44332009-09-09 15:08:12 +00004568
Douglas Gregor74253732008-11-19 15:42:04 +00004569 // Without volatile
4570 if (NumArgs == 1)
4571 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4572 else
4573 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4574
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00004575 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4576 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00004577 // With volatile
John McCall0953e762009-09-24 19:53:00 +00004578 ParamTypes[0]
4579 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor74253732008-11-19 15:42:04 +00004580 if (NumArgs == 1)
4581 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4582 else
4583 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4584 }
4585 }
4586 break;
4587
4588 UnaryStar:
4589 // C++ [over.built]p6:
4590 // For every cv-qualified or cv-unqualified object type T, there
4591 // exist candidate operator functions of the form
4592 //
4593 // T& operator*(T*);
4594 //
4595 // C++ [over.built]p7:
4596 // For every function type T, there exist candidate operator
4597 // functions of the form
4598 // T& operator*(T*);
4599 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4600 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4601 QualType ParamTy = *Ptr;
Ted Kremenek6217b802009-07-29 21:53:49 +00004602 QualType PointeeTy = ParamTy->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004603 AddBuiltinCandidate(Context.getLValueReferenceType(PointeeTy),
Douglas Gregor74253732008-11-19 15:42:04 +00004604 &ParamTy, Args, 1, CandidateSet);
4605 }
4606 break;
4607
4608 UnaryPlus:
4609 // C++ [over.built]p8:
4610 // For every type T, there exist candidate operator functions of
4611 // the form
4612 //
4613 // T* operator+(T*);
4614 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4615 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4616 QualType ParamTy = *Ptr;
4617 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4618 }
Mike Stump1eb44332009-09-09 15:08:12 +00004619
Douglas Gregor74253732008-11-19 15:42:04 +00004620 // Fall through
4621
4622 UnaryMinus:
4623 // C++ [over.built]p9:
4624 // For every promoted arithmetic type T, there exist candidate
4625 // operator functions of the form
4626 //
4627 // T operator+(T);
4628 // T operator-(T);
Mike Stump1eb44332009-09-09 15:08:12 +00004629 for (unsigned Arith = FirstPromotedArithmeticType;
Douglas Gregor74253732008-11-19 15:42:04 +00004630 Arith < LastPromotedArithmeticType; ++Arith) {
4631 QualType ArithTy = ArithmeticTypes[Arith];
4632 AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4633 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004634
4635 // Extension: We also add these operators for vector types.
4636 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4637 VecEnd = CandidateTypes.vector_end();
4638 Vec != VecEnd; ++Vec) {
4639 QualType VecTy = *Vec;
4640 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4641 }
Douglas Gregor74253732008-11-19 15:42:04 +00004642 break;
4643
4644 case OO_Tilde:
4645 // C++ [over.built]p10:
4646 // For every promoted integral type T, there exist candidate
4647 // operator functions of the form
4648 //
4649 // T operator~(T);
Mike Stump1eb44332009-09-09 15:08:12 +00004650 for (unsigned Int = FirstPromotedIntegralType;
Douglas Gregor74253732008-11-19 15:42:04 +00004651 Int < LastPromotedIntegralType; ++Int) {
4652 QualType IntTy = ArithmeticTypes[Int];
4653 AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4654 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004655
4656 // Extension: We also add this operator for vector types.
4657 for (BuiltinCandidateTypeSet::iterator Vec = CandidateTypes.vector_begin(),
4658 VecEnd = CandidateTypes.vector_end();
4659 Vec != VecEnd; ++Vec) {
4660 QualType VecTy = *Vec;
4661 AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4662 }
Douglas Gregor74253732008-11-19 15:42:04 +00004663 break;
4664
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004665 case OO_New:
4666 case OO_Delete:
4667 case OO_Array_New:
4668 case OO_Array_Delete:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004669 case OO_Call:
Douglas Gregor74253732008-11-19 15:42:04 +00004670 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004671 break;
4672
4673 case OO_Comma:
Douglas Gregor74253732008-11-19 15:42:04 +00004674 UnaryAmp:
4675 case OO_Arrow:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004676 // C++ [over.match.oper]p3:
4677 // -- For the operator ',', the unary operator '&', or the
4678 // operator '->', the built-in candidates set is empty.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004679 break;
4680
Douglas Gregor19b7b152009-08-24 13:43:27 +00004681 case OO_EqualEqual:
4682 case OO_ExclaimEqual:
4683 // C++ [over.match.oper]p16:
Mike Stump1eb44332009-09-09 15:08:12 +00004684 // For every pointer to member type T, there exist candidate operator
4685 // functions of the form
Douglas Gregor19b7b152009-08-24 13:43:27 +00004686 //
4687 // bool operator==(T,T);
4688 // bool operator!=(T,T);
Mike Stump1eb44332009-09-09 15:08:12 +00004689 for (BuiltinCandidateTypeSet::iterator
Douglas Gregor19b7b152009-08-24 13:43:27 +00004690 MemPtr = CandidateTypes.member_pointer_begin(),
4691 MemPtrEnd = CandidateTypes.member_pointer_end();
4692 MemPtr != MemPtrEnd;
4693 ++MemPtr) {
4694 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4695 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4696 }
Mike Stump1eb44332009-09-09 15:08:12 +00004697
Douglas Gregor19b7b152009-08-24 13:43:27 +00004698 // Fall through
Mike Stump1eb44332009-09-09 15:08:12 +00004699
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004700 case OO_Less:
4701 case OO_Greater:
4702 case OO_LessEqual:
4703 case OO_GreaterEqual:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004704 // C++ [over.built]p15:
4705 //
4706 // For every pointer or enumeration type T, there exist
4707 // candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004708 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004709 // bool operator<(T, T);
4710 // bool operator>(T, T);
4711 // bool operator<=(T, T);
4712 // bool operator>=(T, T);
4713 // bool operator==(T, T);
4714 // bool operator!=(T, T);
4715 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4716 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4717 QualType ParamTypes[2] = { *Ptr, *Ptr };
4718 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4719 }
Mike Stump1eb44332009-09-09 15:08:12 +00004720 for (BuiltinCandidateTypeSet::iterator Enum
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004721 = CandidateTypes.enumeration_begin();
4722 Enum != CandidateTypes.enumeration_end(); ++Enum) {
4723 QualType ParamTypes[2] = { *Enum, *Enum };
4724 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet);
4725 }
4726
4727 // Fall through.
4728 isComparison = true;
4729
Douglas Gregor74253732008-11-19 15:42:04 +00004730 BinaryPlus:
4731 BinaryMinus:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004732 if (!isComparison) {
4733 // We didn't fall through, so we must have OO_Plus or OO_Minus.
4734
4735 // C++ [over.built]p13:
4736 //
4737 // For every cv-qualified or cv-unqualified object type T
4738 // there exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00004739 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004740 // T* operator+(T*, ptrdiff_t);
4741 // T& operator[](T*, ptrdiff_t); [BELOW]
4742 // T* operator-(T*, ptrdiff_t);
4743 // T* operator+(ptrdiff_t, T*);
4744 // T& operator[](ptrdiff_t, T*); [BELOW]
4745 //
4746 // C++ [over.built]p14:
4747 //
4748 // For every T, where T is a pointer to object type, there
4749 // exist candidate operator functions of the form
4750 //
4751 // ptrdiff_t operator-(T, T);
Mike Stump1eb44332009-09-09 15:08:12 +00004752 for (BuiltinCandidateTypeSet::iterator Ptr
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004753 = CandidateTypes.pointer_begin();
4754 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4755 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
4756
4757 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
4758 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4759
4760 if (Op == OO_Plus) {
4761 // T* operator+(ptrdiff_t, T*);
4762 ParamTypes[0] = ParamTypes[1];
4763 ParamTypes[1] = *Ptr;
4764 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
4765 } else {
4766 // ptrdiff_t operator-(T, T);
4767 ParamTypes[1] = *Ptr;
4768 AddBuiltinCandidate(Context.getPointerDiffType(), ParamTypes,
4769 Args, 2, CandidateSet);
4770 }
4771 }
4772 }
4773 // Fall through
4774
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004775 case OO_Slash:
Douglas Gregor74253732008-11-19 15:42:04 +00004776 BinaryStar:
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004777 Conditional:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004778 // C++ [over.built]p12:
4779 //
4780 // For every pair of promoted arithmetic types L and R, there
4781 // exist candidate operator functions of the form
4782 //
4783 // LR operator*(L, R);
4784 // LR operator/(L, R);
4785 // LR operator+(L, R);
4786 // LR operator-(L, R);
4787 // bool operator<(L, R);
4788 // bool operator>(L, R);
4789 // bool operator<=(L, R);
4790 // bool operator>=(L, R);
4791 // bool operator==(L, R);
4792 // bool operator!=(L, R);
4793 //
4794 // where LR is the result of the usual arithmetic conversions
4795 // between types L and R.
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004796 //
4797 // C++ [over.built]p24:
4798 //
4799 // For every pair of promoted arithmetic types L and R, there exist
4800 // candidate operator functions of the form
4801 //
4802 // LR operator?(bool, L, R);
4803 //
4804 // where LR is the result of the usual arithmetic conversions
4805 // between types L and R.
4806 // Our candidates ignore the first parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00004807 for (unsigned Left = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004808 Left < LastPromotedArithmeticType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004809 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004810 Right < LastPromotedArithmeticType; ++Right) {
4811 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
Eli Friedmana95d7572009-08-19 07:44:53 +00004812 QualType Result
4813 = isComparison
4814 ? Context.BoolTy
4815 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004816 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4817 }
4818 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004819
4820 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
4821 // conditional operator for vector types.
4822 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4823 Vec1End = CandidateTypes.vector_end();
4824 Vec1 != Vec1End; ++Vec1)
4825 for (BuiltinCandidateTypeSet::iterator
4826 Vec2 = CandidateTypes.vector_begin(),
4827 Vec2End = CandidateTypes.vector_end();
4828 Vec2 != Vec2End; ++Vec2) {
4829 QualType LandR[2] = { *Vec1, *Vec2 };
4830 QualType Result;
4831 if (isComparison)
4832 Result = Context.BoolTy;
4833 else {
4834 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
4835 Result = *Vec1;
4836 else
4837 Result = *Vec2;
4838 }
4839
4840 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4841 }
4842
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004843 break;
4844
4845 case OO_Percent:
Douglas Gregor74253732008-11-19 15:42:04 +00004846 BinaryAmp:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004847 case OO_Caret:
4848 case OO_Pipe:
4849 case OO_LessLess:
4850 case OO_GreaterGreater:
4851 // C++ [over.built]p17:
4852 //
4853 // For every pair of promoted integral types L and R, there
4854 // exist candidate operator functions of the form
4855 //
4856 // LR operator%(L, R);
4857 // LR operator&(L, R);
4858 // LR operator^(L, R);
4859 // LR operator|(L, R);
4860 // L operator<<(L, R);
4861 // L operator>>(L, R);
4862 //
4863 // where LR is the result of the usual arithmetic conversions
4864 // between types L and R.
Mike Stump1eb44332009-09-09 15:08:12 +00004865 for (unsigned Left = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004866 Left < LastPromotedIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004867 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004868 Right < LastPromotedIntegralType; ++Right) {
4869 QualType LandR[2] = { ArithmeticTypes[Left], ArithmeticTypes[Right] };
4870 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
4871 ? LandR[0]
Eli Friedmana95d7572009-08-19 07:44:53 +00004872 : Context.UsualArithmeticConversionsType(LandR[0], LandR[1]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004873 AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
4874 }
4875 }
4876 break;
4877
4878 case OO_Equal:
4879 // C++ [over.built]p20:
4880 //
4881 // For every pair (T, VQ), where T is an enumeration or
Douglas Gregor19b7b152009-08-24 13:43:27 +00004882 // pointer to member type and VQ is either volatile or
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004883 // empty, there exist candidate operator functions of the form
4884 //
4885 // VQ T& operator=(VQ T&, T);
Douglas Gregor19b7b152009-08-24 13:43:27 +00004886 for (BuiltinCandidateTypeSet::iterator
4887 Enum = CandidateTypes.enumeration_begin(),
4888 EnumEnd = CandidateTypes.enumeration_end();
4889 Enum != EnumEnd; ++Enum)
Mike Stump1eb44332009-09-09 15:08:12 +00004890 AddBuiltinAssignmentOperatorCandidates(*this, *Enum, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004891 CandidateSet);
4892 for (BuiltinCandidateTypeSet::iterator
4893 MemPtr = CandidateTypes.member_pointer_begin(),
4894 MemPtrEnd = CandidateTypes.member_pointer_end();
4895 MemPtr != MemPtrEnd; ++MemPtr)
Mike Stump1eb44332009-09-09 15:08:12 +00004896 AddBuiltinAssignmentOperatorCandidates(*this, *MemPtr, Args, 2,
Douglas Gregor19b7b152009-08-24 13:43:27 +00004897 CandidateSet);
Douglas Gregor26bcf672010-05-19 03:21:00 +00004898
4899 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004900
4901 case OO_PlusEqual:
4902 case OO_MinusEqual:
4903 // C++ [over.built]p19:
4904 //
4905 // For every pair (T, VQ), where T is any type and VQ is either
4906 // volatile or empty, there exist candidate operator functions
4907 // of the form
4908 //
4909 // T*VQ& operator=(T*VQ&, T*);
4910 //
4911 // C++ [over.built]p21:
4912 //
4913 // For every pair (T, VQ), where T is a cv-qualified or
4914 // cv-unqualified object type and VQ is either volatile or
4915 // empty, there exist candidate operator functions of the form
4916 //
4917 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
4918 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
4919 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
4920 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
4921 QualType ParamTypes[2];
4922 ParamTypes[1] = (Op == OO_Equal)? *Ptr : Context.getPointerDiffType();
4923
4924 // non-volatile version
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004925 ParamTypes[0] = Context.getLValueReferenceType(*Ptr);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004926 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4927 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004928
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004929 if (!Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4930 VisibleTypeConversionsQuals.hasVolatile()) {
Douglas Gregor74253732008-11-19 15:42:04 +00004931 // volatile version
John McCall0953e762009-09-24 19:53:00 +00004932 ParamTypes[0]
4933 = Context.getLValueReferenceType(Context.getVolatileType(*Ptr));
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004934 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4935 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregor74253732008-11-19 15:42:04 +00004936 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004937 }
4938 // Fall through.
4939
4940 case OO_StarEqual:
4941 case OO_SlashEqual:
4942 // C++ [over.built]p18:
4943 //
4944 // For every triple (L, VQ, R), where L is an arithmetic type,
4945 // VQ is either volatile or empty, and R is a promoted
4946 // arithmetic type, there exist candidate operator functions of
4947 // the form
4948 //
4949 // VQ L& operator=(VQ L&, R);
4950 // VQ L& operator*=(VQ L&, R);
4951 // VQ L& operator/=(VQ L&, R);
4952 // VQ L& operator+=(VQ L&, R);
4953 // VQ L& operator-=(VQ L&, R);
4954 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00004955 for (unsigned Right = FirstPromotedArithmeticType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004956 Right < LastPromotedArithmeticType; ++Right) {
4957 QualType ParamTypes[2];
4958 ParamTypes[1] = ArithmeticTypes[Right];
4959
4960 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004961 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregor88b4bf22009-01-13 00:52:54 +00004962 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4963 /*IsAssigmentOperator=*/Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004964
4965 // Add this built-in operator as a candidate (VQ is 'volatile').
Fariborz Jahanian8621d012009-10-19 21:30:45 +00004966 if (VisibleTypeConversionsQuals.hasVolatile()) {
4967 ParamTypes[0] = Context.getVolatileType(ArithmeticTypes[Left]);
4968 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4969 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4970 /*IsAssigmentOperator=*/Op == OO_Equal);
4971 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004972 }
4973 }
Douglas Gregor26bcf672010-05-19 03:21:00 +00004974
4975 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
4976 for (BuiltinCandidateTypeSet::iterator Vec1 = CandidateTypes.vector_begin(),
4977 Vec1End = CandidateTypes.vector_end();
4978 Vec1 != Vec1End; ++Vec1)
4979 for (BuiltinCandidateTypeSet::iterator
4980 Vec2 = CandidateTypes.vector_begin(),
4981 Vec2End = CandidateTypes.vector_end();
4982 Vec2 != Vec2End; ++Vec2) {
4983 QualType ParamTypes[2];
4984 ParamTypes[1] = *Vec2;
4985 // Add this built-in operator as a candidate (VQ is empty).
4986 ParamTypes[0] = Context.getLValueReferenceType(*Vec1);
4987 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4988 /*IsAssigmentOperator=*/Op == OO_Equal);
4989
4990 // Add this built-in operator as a candidate (VQ is 'volatile').
4991 if (VisibleTypeConversionsQuals.hasVolatile()) {
4992 ParamTypes[0] = Context.getVolatileType(*Vec1);
4993 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
4994 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4995 /*IsAssigmentOperator=*/Op == OO_Equal);
4996 }
4997 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00004998 break;
4999
5000 case OO_PercentEqual:
5001 case OO_LessLessEqual:
5002 case OO_GreaterGreaterEqual:
5003 case OO_AmpEqual:
5004 case OO_CaretEqual:
5005 case OO_PipeEqual:
5006 // C++ [over.built]p22:
5007 //
5008 // For every triple (L, VQ, R), where L is an integral type, VQ
5009 // is either volatile or empty, and R is a promoted integral
5010 // type, there exist candidate operator functions of the form
5011 //
5012 // VQ L& operator%=(VQ L&, R);
5013 // VQ L& operator<<=(VQ L&, R);
5014 // VQ L& operator>>=(VQ L&, R);
5015 // VQ L& operator&=(VQ L&, R);
5016 // VQ L& operator^=(VQ L&, R);
5017 // VQ L& operator|=(VQ L&, R);
5018 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
Mike Stump1eb44332009-09-09 15:08:12 +00005019 for (unsigned Right = FirstPromotedIntegralType;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005020 Right < LastPromotedIntegralType; ++Right) {
5021 QualType ParamTypes[2];
5022 ParamTypes[1] = ArithmeticTypes[Right];
5023
5024 // Add this built-in operator as a candidate (VQ is empty).
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005025 ParamTypes[0] = Context.getLValueReferenceType(ArithmeticTypes[Left]);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005026 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
Fariborz Jahanian035c46f2009-10-20 00:04:40 +00005027 if (VisibleTypeConversionsQuals.hasVolatile()) {
5028 // Add this built-in operator as a candidate (VQ is 'volatile').
5029 ParamTypes[0] = ArithmeticTypes[Left];
5030 ParamTypes[0] = Context.getVolatileType(ParamTypes[0]);
5031 ParamTypes[0] = Context.getLValueReferenceType(ParamTypes[0]);
5032 AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5033 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005034 }
5035 }
5036 break;
5037
Douglas Gregor74253732008-11-19 15:42:04 +00005038 case OO_Exclaim: {
5039 // C++ [over.operator]p23:
5040 //
5041 // There also exist candidate operator functions of the form
5042 //
Mike Stump1eb44332009-09-09 15:08:12 +00005043 // bool operator!(bool);
Douglas Gregor74253732008-11-19 15:42:04 +00005044 // bool operator&&(bool, bool); [BELOW]
5045 // bool operator||(bool, bool); [BELOW]
5046 QualType ParamTy = Context.BoolTy;
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005047 AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5048 /*IsAssignmentOperator=*/false,
5049 /*NumContextualBoolArguments=*/1);
Douglas Gregor74253732008-11-19 15:42:04 +00005050 break;
5051 }
5052
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005053 case OO_AmpAmp:
5054 case OO_PipePipe: {
5055 // C++ [over.operator]p23:
5056 //
5057 // There also exist candidate operator functions of the form
5058 //
Douglas Gregor74253732008-11-19 15:42:04 +00005059 // bool operator!(bool); [ABOVE]
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005060 // bool operator&&(bool, bool);
5061 // bool operator||(bool, bool);
5062 QualType ParamTypes[2] = { Context.BoolTy, Context.BoolTy };
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005063 AddBuiltinCandidate(Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5064 /*IsAssignmentOperator=*/false,
5065 /*NumContextualBoolArguments=*/2);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005066 break;
5067 }
5068
5069 case OO_Subscript:
5070 // C++ [over.built]p13:
5071 //
5072 // For every cv-qualified or cv-unqualified object type T there
5073 // exist candidate operator functions of the form
Mike Stump1eb44332009-09-09 15:08:12 +00005074 //
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005075 // T* operator+(T*, ptrdiff_t); [ABOVE]
5076 // T& operator[](T*, ptrdiff_t);
5077 // T* operator-(T*, ptrdiff_t); [ABOVE]
5078 // T* operator+(ptrdiff_t, T*); [ABOVE]
5079 // T& operator[](ptrdiff_t, T*);
5080 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin();
5081 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5082 QualType ParamTypes[2] = { *Ptr, Context.getPointerDiffType() };
Ted Kremenek6217b802009-07-29 21:53:49 +00005083 QualType PointeeType = (*Ptr)->getAs<PointerType>()->getPointeeType();
Sebastian Redl7c80bd62009-03-16 23:22:08 +00005084 QualType ResultTy = Context.getLValueReferenceType(PointeeType);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005085
5086 // T& operator[](T*, ptrdiff_t)
5087 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5088
5089 // T& operator[](ptrdiff_t, T*);
5090 ParamTypes[0] = ParamTypes[1];
5091 ParamTypes[1] = *Ptr;
5092 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
Douglas Gregor26bcf672010-05-19 03:21:00 +00005093 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005094 break;
5095
5096 case OO_ArrowStar:
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005097 // C++ [over.built]p11:
5098 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5099 // C1 is the same type as C2 or is a derived class of C2, T is an object
5100 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5101 // there exist candidate operator functions of the form
5102 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5103 // where CV12 is the union of CV1 and CV2.
5104 {
5105 for (BuiltinCandidateTypeSet::iterator Ptr =
5106 CandidateTypes.pointer_begin();
5107 Ptr != CandidateTypes.pointer_end(); ++Ptr) {
5108 QualType C1Ty = (*Ptr);
5109 QualType C1;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00005110 QualifierCollector Q1;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005111 if (const PointerType *PointerTy = C1Ty->getAs<PointerType>()) {
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00005112 C1 = QualType(Q1.strip(PointerTy->getPointeeType()), 0);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005113 if (!isa<RecordType>(C1))
5114 continue;
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005115 // heuristic to reduce number of builtin candidates in the set.
5116 // Add volatile/restrict version only if there are conversions to a
5117 // volatile/restrict type.
5118 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5119 continue;
5120 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5121 continue;
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005122 }
5123 for (BuiltinCandidateTypeSet::iterator
5124 MemPtr = CandidateTypes.member_pointer_begin(),
5125 MemPtrEnd = CandidateTypes.member_pointer_end();
5126 MemPtr != MemPtrEnd; ++MemPtr) {
5127 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5128 QualType C2 = QualType(mptr->getClass(), 0);
Fariborz Jahanian43036972009-10-07 16:56:50 +00005129 C2 = C2.getUnqualifiedType();
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005130 if (C1 != C2 && !IsDerivedFrom(C1, C2))
5131 break;
5132 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5133 // build CV12 T&
5134 QualType T = mptr->getPointeeType();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005135 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5136 T.isVolatileQualified())
5137 continue;
5138 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5139 T.isRestrictQualified())
5140 continue;
Fariborz Jahanian5ecd5392009-10-09 16:34:40 +00005141 T = Q1.apply(T);
Fariborz Jahanian4657a992009-10-06 23:08:05 +00005142 QualType ResultTy = Context.getLValueReferenceType(T);
5143 AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5144 }
5145 }
5146 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005147 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005148
5149 case OO_Conditional:
5150 // Note that we don't consider the first argument, since it has been
5151 // contextually converted to bool long ago. The candidates below are
5152 // therefore added as binary.
5153 //
5154 // C++ [over.built]p24:
5155 // For every type T, where T is a pointer or pointer-to-member type,
5156 // there exist candidate operator functions of the form
5157 //
5158 // T operator?(bool, T, T);
5159 //
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005160 for (BuiltinCandidateTypeSet::iterator Ptr = CandidateTypes.pointer_begin(),
5161 E = CandidateTypes.pointer_end(); Ptr != E; ++Ptr) {
5162 QualType ParamTypes[2] = { *Ptr, *Ptr };
5163 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5164 }
Sebastian Redl78eb8742009-04-19 21:53:20 +00005165 for (BuiltinCandidateTypeSet::iterator Ptr =
5166 CandidateTypes.member_pointer_begin(),
5167 E = CandidateTypes.member_pointer_end(); Ptr != E; ++Ptr) {
5168 QualType ParamTypes[2] = { *Ptr, *Ptr };
5169 AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5170 }
Sebastian Redl3201f6b2009-04-16 17:51:27 +00005171 goto Conditional;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005172 }
5173}
5174
Douglas Gregorfa047642009-02-04 00:32:51 +00005175/// \brief Add function candidates found via argument-dependent lookup
5176/// to the set of overloading candidates.
5177///
5178/// This routine performs argument-dependent name lookup based on the
5179/// given function name (which may also be an operator name) and adds
5180/// all of the overload candidates found by ADL to the overload
5181/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00005182void
Douglas Gregorfa047642009-02-04 00:32:51 +00005183Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00005184 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00005185 Expr **Args, unsigned NumArgs,
John McCalld5532b62009-11-23 01:53:49 +00005186 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005187 OverloadCandidateSet& CandidateSet,
5188 bool PartialOverloading) {
John McCall7edb5fd2010-01-26 07:16:45 +00005189 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00005190
John McCalla113e722010-01-26 06:04:06 +00005191 // FIXME: This approach for uniquing ADL results (and removing
5192 // redundant candidates from the set) relies on pointer-equality,
5193 // which means we need to key off the canonical decl. However,
5194 // always going back to the canonical decl might not get us the
5195 // right set of default arguments. What default arguments are
5196 // we supposed to consider on ADL candidates, anyway?
5197
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005198 // FIXME: Pass in the explicit template arguments?
John McCall7edb5fd2010-01-26 07:16:45 +00005199 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregorfa047642009-02-04 00:32:51 +00005200
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005201 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005202 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5203 CandEnd = CandidateSet.end();
5204 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00005205 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00005206 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00005207 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00005208 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00005209 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00005210
5211 // For each of the ADL candidates we found, add it to the overload
5212 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00005213 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00005214 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00005215 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00005216 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005217 continue;
5218
John McCall9aa472c2010-03-19 07:35:19 +00005219 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00005220 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00005221 } else
John McCall6e266892010-01-26 03:27:55 +00005222 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00005223 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00005224 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00005225 }
Douglas Gregorfa047642009-02-04 00:32:51 +00005226}
5227
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005228/// isBetterOverloadCandidate - Determines whether the first overload
5229/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00005230bool
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005231Sema::isBetterOverloadCandidate(const OverloadCandidate& Cand1,
John McCall5769d612010-02-08 23:07:23 +00005232 const OverloadCandidate& Cand2,
5233 SourceLocation Loc) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005234 // Define viable functions to be better candidates than non-viable
5235 // functions.
5236 if (!Cand2.Viable)
5237 return Cand1.Viable;
5238 else if (!Cand1.Viable)
5239 return false;
5240
Douglas Gregor88a35142008-12-22 05:46:06 +00005241 // C++ [over.match.best]p1:
5242 //
5243 // -- if F is a static member function, ICS1(F) is defined such
5244 // that ICS1(F) is neither better nor worse than ICS1(G) for
5245 // any function G, and, symmetrically, ICS1(G) is neither
5246 // better nor worse than ICS1(F).
5247 unsigned StartArg = 0;
5248 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5249 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005250
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005251 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00005252 // A viable function F1 is defined to be a better function than another
5253 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005254 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005255 unsigned NumArgs = Cand1.Conversions.size();
5256 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5257 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005258 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005259 switch (CompareImplicitConversionSequences(Cand1.Conversions[ArgIdx],
5260 Cand2.Conversions[ArgIdx])) {
5261 case ImplicitConversionSequence::Better:
5262 // Cand1 has a better conversion sequence.
5263 HasBetterConversion = true;
5264 break;
5265
5266 case ImplicitConversionSequence::Worse:
5267 // Cand1 can't be better than Cand2.
5268 return false;
5269
5270 case ImplicitConversionSequence::Indistinguishable:
5271 // Do nothing.
5272 break;
5273 }
5274 }
5275
Mike Stump1eb44332009-09-09 15:08:12 +00005276 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005277 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005278 if (HasBetterConversion)
5279 return true;
5280
Mike Stump1eb44332009-09-09 15:08:12 +00005281 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005282 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00005283 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005284 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5285 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00005286
5287 // -- F1 and F2 are function template specializations, and the function
5288 // template for F1 is more specialized than the template for F2
5289 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00005290 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00005291 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
5292 Cand2.Function && Cand2.Function->getPrimaryTemplate())
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005293 if (FunctionTemplateDecl *BetterTemplate
5294 = getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5295 Cand2.Function->getPrimaryTemplate(),
John McCall5769d612010-02-08 23:07:23 +00005296 Loc,
Douglas Gregor5d7d3752009-09-14 23:02:14 +00005297 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
5298 : TPOC_Call))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005299 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005300
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005301 // -- the context is an initialization by user-defined conversion
5302 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5303 // from the return type of F1 to the destination type (i.e.,
5304 // the type of the entity being initialized) is a better
5305 // conversion sequence than the standard conversion sequence
5306 // from the return type of F2 to the destination type.
Mike Stump1eb44332009-09-09 15:08:12 +00005307 if (Cand1.Function && Cand2.Function &&
5308 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005309 isa<CXXConversionDecl>(Cand2.Function)) {
5310 switch (CompareStandardConversionSequences(Cand1.FinalConversion,
5311 Cand2.FinalConversion)) {
5312 case ImplicitConversionSequence::Better:
5313 // Cand1 has a better conversion sequence.
5314 return true;
5315
5316 case ImplicitConversionSequence::Worse:
5317 // Cand1 can't be better than Cand2.
5318 return false;
5319
5320 case ImplicitConversionSequence::Indistinguishable:
5321 // Do nothing
5322 break;
5323 }
5324 }
5325
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005326 return false;
5327}
5328
Mike Stump1eb44332009-09-09 15:08:12 +00005329/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00005330/// within an overload candidate set.
5331///
5332/// \param CandidateSet the set of candidate functions.
5333///
5334/// \param Loc the location of the function name (or operator symbol) for
5335/// which overload resolution occurs.
5336///
Mike Stump1eb44332009-09-09 15:08:12 +00005337/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00005338/// function, Best points to the candidate function found.
5339///
5340/// \returns The result of overload resolution.
Douglas Gregor20093b42009-12-09 23:02:17 +00005341OverloadingResult Sema::BestViableFunction(OverloadCandidateSet& CandidateSet,
5342 SourceLocation Loc,
5343 OverloadCandidateSet::iterator& Best) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005344 // Find the best viable function.
5345 Best = CandidateSet.end();
5346 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5347 Cand != CandidateSet.end(); ++Cand) {
5348 if (Cand->Viable) {
John McCall5769d612010-02-08 23:07:23 +00005349 if (Best == CandidateSet.end() ||
5350 isBetterOverloadCandidate(*Cand, *Best, Loc))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005351 Best = Cand;
5352 }
5353 }
5354
5355 // If we didn't find any viable functions, abort.
5356 if (Best == CandidateSet.end())
5357 return OR_No_Viable_Function;
5358
5359 // Make sure that this function is better than every other viable
5360 // function. If not, we have an ambiguity.
5361 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
5362 Cand != CandidateSet.end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00005363 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005364 Cand != Best &&
John McCall5769d612010-02-08 23:07:23 +00005365 !isBetterOverloadCandidate(*Best, *Cand, Loc)) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005366 Best = CandidateSet.end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005367 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005368 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005369 }
Mike Stump1eb44332009-09-09 15:08:12 +00005370
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005371 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005372 if (Best->Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00005373 (Best->Function->isDeleted() ||
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00005374 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00005375 return OR_Deleted;
5376
Douglas Gregore0762c92009-06-19 23:52:42 +00005377 // C++ [basic.def.odr]p2:
5378 // An overloaded function is used if it is selected by overload resolution
Mike Stump1eb44332009-09-09 15:08:12 +00005379 // when referred to from a potentially-evaluated expression. [Note: this
5380 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregore0762c92009-06-19 23:52:42 +00005381 // (clause 13), user-defined conversions (12.3.2), allocation function for
5382 // placement new (5.3.4), as well as non-default initialization (8.5).
5383 if (Best->Function)
5384 MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00005385 return OR_Success;
5386}
5387
John McCall3c80f572010-01-12 02:15:36 +00005388namespace {
5389
5390enum OverloadCandidateKind {
5391 oc_function,
5392 oc_method,
5393 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00005394 oc_function_template,
5395 oc_method_template,
5396 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00005397 oc_implicit_default_constructor,
5398 oc_implicit_copy_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00005399 oc_implicit_copy_assignment
John McCall3c80f572010-01-12 02:15:36 +00005400};
5401
John McCall220ccbf2010-01-13 00:25:19 +00005402OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
5403 FunctionDecl *Fn,
5404 std::string &Description) {
5405 bool isTemplate = false;
5406
5407 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
5408 isTemplate = true;
5409 Description = S.getTemplateArgumentBindingsText(
5410 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
5411 }
John McCallb1622a12010-01-06 09:43:14 +00005412
5413 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00005414 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00005415 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00005416
John McCall3c80f572010-01-12 02:15:36 +00005417 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
5418 : oc_implicit_default_constructor;
John McCallb1622a12010-01-06 09:43:14 +00005419 }
5420
5421 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
5422 // This actually gets spelled 'candidate function' for now, but
5423 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00005424 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00005425 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00005426
5427 assert(Meth->isCopyAssignment()
5428 && "implicit method is not copy assignment operator?");
John McCall3c80f572010-01-12 02:15:36 +00005429 return oc_implicit_copy_assignment;
5430 }
5431
John McCall220ccbf2010-01-13 00:25:19 +00005432 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00005433}
5434
5435} // end anonymous namespace
5436
5437// Notes the location of an overload candidate.
5438void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCall220ccbf2010-01-13 00:25:19 +00005439 std::string FnDesc;
5440 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
5441 Diag(Fn->getLocation(), diag::note_ovl_candidate)
5442 << (unsigned) K << FnDesc;
John McCallb1622a12010-01-06 09:43:14 +00005443}
5444
John McCall1d318332010-01-12 00:44:57 +00005445/// Diagnoses an ambiguous conversion. The partial diagnostic is the
5446/// "lead" diagnostic; it will be given two arguments, the source and
5447/// target types of the conversion.
5448void Sema::DiagnoseAmbiguousConversion(const ImplicitConversionSequence &ICS,
5449 SourceLocation CaretLoc,
5450 const PartialDiagnostic &PDiag) {
5451 Diag(CaretLoc, PDiag)
5452 << ICS.Ambiguous.getFromType() << ICS.Ambiguous.getToType();
5453 for (AmbiguousConversionSequence::const_iterator
5454 I = ICS.Ambiguous.begin(), E = ICS.Ambiguous.end(); I != E; ++I) {
5455 NoteOverloadCandidate(*I);
5456 }
John McCall81201622010-01-08 04:41:39 +00005457}
5458
John McCall1d318332010-01-12 00:44:57 +00005459namespace {
5460
John McCalladbb8f82010-01-13 09:16:55 +00005461void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
5462 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
5463 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00005464 assert(Cand->Function && "for now, candidate must be a function");
5465 FunctionDecl *Fn = Cand->Function;
5466
5467 // There's a conversion slot for the object argument if this is a
5468 // non-constructor method. Note that 'I' corresponds the
5469 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00005470 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00005471 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00005472 if (I == 0)
5473 isObjectArgument = true;
5474 else
5475 I--;
John McCall220ccbf2010-01-13 00:25:19 +00005476 }
5477
John McCall220ccbf2010-01-13 00:25:19 +00005478 std::string FnDesc;
5479 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
5480
John McCalladbb8f82010-01-13 09:16:55 +00005481 Expr *FromExpr = Conv.Bad.FromExpr;
5482 QualType FromTy = Conv.Bad.getFromType();
5483 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00005484
John McCall5920dbb2010-02-02 02:42:52 +00005485 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00005486 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00005487 Expr *E = FromExpr->IgnoreParens();
5488 if (isa<UnaryOperator>(E))
5489 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00005490 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00005491
5492 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
5493 << (unsigned) FnKind << FnDesc
5494 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5495 << ToTy << Name << I+1;
5496 return;
5497 }
5498
John McCall258b2032010-01-23 08:10:49 +00005499 // Do some hand-waving analysis to see if the non-viability is due
5500 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00005501 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
5502 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
5503 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
5504 CToTy = RT->getPointeeType();
5505 else {
5506 // TODO: detect and diagnose the full richness of const mismatches.
5507 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
5508 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
5509 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
5510 }
5511
5512 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
5513 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
5514 // It is dumb that we have to do this here.
5515 while (isa<ArrayType>(CFromTy))
5516 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
5517 while (isa<ArrayType>(CToTy))
5518 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
5519
5520 Qualifiers FromQs = CFromTy.getQualifiers();
5521 Qualifiers ToQs = CToTy.getQualifiers();
5522
5523 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
5524 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
5525 << (unsigned) FnKind << FnDesc
5526 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5527 << FromTy
5528 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
5529 << (unsigned) isObjectArgument << I+1;
5530 return;
5531 }
5532
5533 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
5534 assert(CVR && "unexpected qualifiers mismatch");
5535
5536 if (isObjectArgument) {
5537 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
5538 << (unsigned) FnKind << FnDesc
5539 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5540 << FromTy << (CVR - 1);
5541 } else {
5542 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
5543 << (unsigned) FnKind << FnDesc
5544 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5545 << FromTy << (CVR - 1) << I+1;
5546 }
5547 return;
5548 }
5549
John McCall258b2032010-01-23 08:10:49 +00005550 // Diagnose references or pointers to incomplete types differently,
5551 // since it's far from impossible that the incompleteness triggered
5552 // the failure.
5553 QualType TempFromTy = FromTy.getNonReferenceType();
5554 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
5555 TempFromTy = PTy->getPointeeType();
5556 if (TempFromTy->isIncompleteType()) {
5557 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
5558 << (unsigned) FnKind << FnDesc
5559 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
5560 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
5561 return;
5562 }
5563
Douglas Gregor85789812010-06-30 23:01:39 +00005564 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005565 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00005566 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
5567 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
5568 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5569 FromPtrTy->getPointeeType()) &&
5570 !FromPtrTy->getPointeeType()->isIncompleteType() &&
5571 !ToPtrTy->getPointeeType()->isIncompleteType() &&
5572 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
5573 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005574 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00005575 }
5576 } else if (const ObjCObjectPointerType *FromPtrTy
5577 = FromTy->getAs<ObjCObjectPointerType>()) {
5578 if (const ObjCObjectPointerType *ToPtrTy
5579 = ToTy->getAs<ObjCObjectPointerType>())
5580 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
5581 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
5582 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
5583 FromPtrTy->getPointeeType()) &&
5584 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005585 BaseToDerivedConversion = 2;
5586 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
5587 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
5588 !FromTy->isIncompleteType() &&
5589 !ToRefTy->getPointeeType()->isIncompleteType() &&
5590 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
5591 BaseToDerivedConversion = 3;
5592 }
5593
5594 if (BaseToDerivedConversion) {
Douglas Gregor85789812010-06-30 23:01:39 +00005595 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005596 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00005597 << (unsigned) FnKind << FnDesc
5598 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00005599 << (BaseToDerivedConversion - 1)
Douglas Gregor85789812010-06-30 23:01:39 +00005600 << FromTy << ToTy << I+1;
5601 return;
5602 }
5603
John McCall651f3ee2010-01-14 03:28:57 +00005604 // TODO: specialize more based on the kind of mismatch
John McCall220ccbf2010-01-13 00:25:19 +00005605 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
5606 << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00005607 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalle81e15e2010-01-14 00:56:20 +00005608 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCalladbb8f82010-01-13 09:16:55 +00005609}
5610
5611void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
5612 unsigned NumFormalArgs) {
5613 // TODO: treat calls to a missing default constructor as a special case
5614
5615 FunctionDecl *Fn = Cand->Function;
5616 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
5617
5618 unsigned MinParams = Fn->getMinRequiredArguments();
5619
5620 // at least / at most / exactly
Douglas Gregora18592e2010-05-08 18:13:28 +00005621 // FIXME: variadic templates "at most" should account for parameter packs
John McCalladbb8f82010-01-13 09:16:55 +00005622 unsigned mode, modeCount;
5623 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00005624 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
5625 (Cand->FailureKind == ovl_fail_bad_deduction &&
5626 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
John McCalladbb8f82010-01-13 09:16:55 +00005627 if (MinParams != FnTy->getNumArgs() || FnTy->isVariadic())
5628 mode = 0; // "at least"
5629 else
5630 mode = 2; // "exactly"
5631 modeCount = MinParams;
5632 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00005633 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
5634 (Cand->FailureKind == ovl_fail_bad_deduction &&
5635 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00005636 if (MinParams != FnTy->getNumArgs())
5637 mode = 1; // "at most"
5638 else
5639 mode = 2; // "exactly"
5640 modeCount = FnTy->getNumArgs();
5641 }
5642
5643 std::string Description;
5644 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
5645
5646 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregora18592e2010-05-08 18:13:28 +00005647 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
5648 << modeCount << NumFormalArgs;
John McCall220ccbf2010-01-13 00:25:19 +00005649}
5650
John McCall342fec42010-02-01 18:53:26 +00005651/// Diagnose a failed template-argument deduction.
5652void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
5653 Expr **Args, unsigned NumArgs) {
5654 FunctionDecl *Fn = Cand->Function; // pattern
5655
Douglas Gregora9333192010-05-08 17:41:32 +00005656 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00005657 NamedDecl *ParamD;
5658 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
5659 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
5660 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00005661 switch (Cand->DeductionFailure.Result) {
5662 case Sema::TDK_Success:
5663 llvm_unreachable("TDK_success while diagnosing bad deduction");
5664
5665 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00005666 assert(ParamD && "no parameter found for incomplete deduction result");
5667 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
5668 << ParamD->getDeclName();
5669 return;
5670 }
5671
John McCall57e97782010-08-05 09:05:08 +00005672 case Sema::TDK_Underqualified: {
5673 assert(ParamD && "no parameter found for bad qualifiers deduction result");
5674 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
5675
5676 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
5677
5678 // Param will have been canonicalized, but it should just be a
5679 // qualified version of ParamD, so move the qualifiers to that.
5680 QualifierCollector Qs(S.Context);
5681 Qs.strip(Param);
5682 QualType NonCanonParam = Qs.apply(TParam->getTypeForDecl());
5683 assert(S.Context.hasSameType(Param, NonCanonParam));
5684
5685 // Arg has also been canonicalized, but there's nothing we can do
5686 // about that. It also doesn't matter as much, because it won't
5687 // have any template parameters in it (because deduction isn't
5688 // done on dependent types).
5689 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
5690
5691 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
5692 << ParamD->getDeclName() << Arg << NonCanonParam;
5693 return;
5694 }
5695
5696 case Sema::TDK_Inconsistent: {
Douglas Gregorf1a84452010-05-08 19:15:54 +00005697 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00005698 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00005699 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00005700 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00005701 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00005702 which = 1;
5703 else {
Douglas Gregora9333192010-05-08 17:41:32 +00005704 which = 2;
5705 }
5706
5707 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
5708 << which << ParamD->getDeclName()
5709 << *Cand->DeductionFailure.getFirstArg()
5710 << *Cand->DeductionFailure.getSecondArg();
5711 return;
5712 }
Douglas Gregora18592e2010-05-08 18:13:28 +00005713
Douglas Gregorf1a84452010-05-08 19:15:54 +00005714 case Sema::TDK_InvalidExplicitArguments:
5715 assert(ParamD && "no parameter found for invalid explicit arguments");
5716 if (ParamD->getDeclName())
5717 S.Diag(Fn->getLocation(),
5718 diag::note_ovl_candidate_explicit_arg_mismatch_named)
5719 << ParamD->getDeclName();
5720 else {
5721 int index = 0;
5722 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
5723 index = TTP->getIndex();
5724 else if (NonTypeTemplateParmDecl *NTTP
5725 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
5726 index = NTTP->getIndex();
5727 else
5728 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
5729 S.Diag(Fn->getLocation(),
5730 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
5731 << (index + 1);
5732 }
5733 return;
5734
Douglas Gregora18592e2010-05-08 18:13:28 +00005735 case Sema::TDK_TooManyArguments:
5736 case Sema::TDK_TooFewArguments:
5737 DiagnoseArityMismatch(S, Cand, NumArgs);
5738 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00005739
5740 case Sema::TDK_InstantiationDepth:
5741 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
5742 return;
5743
5744 case Sema::TDK_SubstitutionFailure: {
5745 std::string ArgString;
5746 if (TemplateArgumentList *Args
5747 = Cand->DeductionFailure.getTemplateArgumentList())
5748 ArgString = S.getTemplateArgumentBindingsText(
5749 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
5750 *Args);
5751 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
5752 << ArgString;
5753 return;
5754 }
Douglas Gregora9333192010-05-08 17:41:32 +00005755
John McCall342fec42010-02-01 18:53:26 +00005756 // TODO: diagnose these individually, then kill off
5757 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00005758 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00005759 case Sema::TDK_FailedOverloadResolution:
5760 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
5761 return;
5762 }
5763}
5764
5765/// Generates a 'note' diagnostic for an overload candidate. We've
5766/// already generated a primary error at the call site.
5767///
5768/// It really does need to be a single diagnostic with its caret
5769/// pointed at the candidate declaration. Yes, this creates some
5770/// major challenges of technical writing. Yes, this makes pointing
5771/// out problems with specific arguments quite awkward. It's still
5772/// better than generating twenty screens of text for every failed
5773/// overload.
5774///
5775/// It would be great to be able to express per-candidate problems
5776/// more richly for those diagnostic clients that cared, but we'd
5777/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00005778void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
5779 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00005780 FunctionDecl *Fn = Cand->Function;
5781
John McCall81201622010-01-08 04:41:39 +00005782 // Note deleted candidates, but only if they're viable.
John McCall3c80f572010-01-12 02:15:36 +00005783 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCall220ccbf2010-01-13 00:25:19 +00005784 std::string FnDesc;
5785 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00005786
5787 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00005788 << FnKind << FnDesc << Fn->isDeleted();
John McCalla1d7d622010-01-08 00:58:21 +00005789 return;
John McCall81201622010-01-08 04:41:39 +00005790 }
5791
John McCall220ccbf2010-01-13 00:25:19 +00005792 // We don't really have anything else to say about viable candidates.
5793 if (Cand->Viable) {
5794 S.NoteOverloadCandidate(Fn);
5795 return;
5796 }
John McCall1d318332010-01-12 00:44:57 +00005797
John McCalladbb8f82010-01-13 09:16:55 +00005798 switch (Cand->FailureKind) {
5799 case ovl_fail_too_many_arguments:
5800 case ovl_fail_too_few_arguments:
5801 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00005802
John McCalladbb8f82010-01-13 09:16:55 +00005803 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00005804 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
5805
John McCall717e8912010-01-23 05:17:32 +00005806 case ovl_fail_trivial_conversion:
5807 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00005808 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00005809 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00005810
John McCallb1bdc622010-02-25 01:37:24 +00005811 case ovl_fail_bad_conversion: {
5812 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
5813 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00005814 if (Cand->Conversions[I].isBad())
5815 return DiagnoseBadConversion(S, Cand, I);
5816
5817 // FIXME: this currently happens when we're called from SemaInit
5818 // when user-conversion overload fails. Figure out how to handle
5819 // those conditions and diagnose them well.
5820 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00005821 }
John McCallb1bdc622010-02-25 01:37:24 +00005822 }
John McCalla1d7d622010-01-08 00:58:21 +00005823}
5824
5825void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
5826 // Desugar the type of the surrogate down to a function type,
5827 // retaining as many typedefs as possible while still showing
5828 // the function type (and, therefore, its parameter types).
5829 QualType FnType = Cand->Surrogate->getConversionType();
5830 bool isLValueReference = false;
5831 bool isRValueReference = false;
5832 bool isPointer = false;
5833 if (const LValueReferenceType *FnTypeRef =
5834 FnType->getAs<LValueReferenceType>()) {
5835 FnType = FnTypeRef->getPointeeType();
5836 isLValueReference = true;
5837 } else if (const RValueReferenceType *FnTypeRef =
5838 FnType->getAs<RValueReferenceType>()) {
5839 FnType = FnTypeRef->getPointeeType();
5840 isRValueReference = true;
5841 }
5842 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
5843 FnType = FnTypePtr->getPointeeType();
5844 isPointer = true;
5845 }
5846 // Desugar down to a function type.
5847 FnType = QualType(FnType->getAs<FunctionType>(), 0);
5848 // Reconstruct the pointer/reference as appropriate.
5849 if (isPointer) FnType = S.Context.getPointerType(FnType);
5850 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
5851 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
5852
5853 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
5854 << FnType;
5855}
5856
5857void NoteBuiltinOperatorCandidate(Sema &S,
5858 const char *Opc,
5859 SourceLocation OpLoc,
5860 OverloadCandidate *Cand) {
5861 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
5862 std::string TypeStr("operator");
5863 TypeStr += Opc;
5864 TypeStr += "(";
5865 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
5866 if (Cand->Conversions.size() == 1) {
5867 TypeStr += ")";
5868 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
5869 } else {
5870 TypeStr += ", ";
5871 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
5872 TypeStr += ")";
5873 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
5874 }
5875}
5876
5877void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
5878 OverloadCandidate *Cand) {
5879 unsigned NoOperands = Cand->Conversions.size();
5880 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
5881 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00005882 if (ICS.isBad()) break; // all meaningless after first invalid
5883 if (!ICS.isAmbiguous()) continue;
5884
5885 S.DiagnoseAmbiguousConversion(ICS, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00005886 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00005887 }
5888}
5889
John McCall1b77e732010-01-15 23:32:50 +00005890SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
5891 if (Cand->Function)
5892 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00005893 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00005894 return Cand->Surrogate->getLocation();
5895 return SourceLocation();
5896}
5897
John McCallbf65c0b2010-01-12 00:48:53 +00005898struct CompareOverloadCandidatesForDisplay {
5899 Sema &S;
5900 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00005901
5902 bool operator()(const OverloadCandidate *L,
5903 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00005904 // Fast-path this check.
5905 if (L == R) return false;
5906
John McCall81201622010-01-08 04:41:39 +00005907 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00005908 if (L->Viable) {
5909 if (!R->Viable) return true;
5910
5911 // TODO: introduce a tri-valued comparison for overload
5912 // candidates. Would be more worthwhile if we had a sort
5913 // that could exploit it.
John McCall5769d612010-02-08 23:07:23 +00005914 if (S.isBetterOverloadCandidate(*L, *R, SourceLocation())) return true;
5915 if (S.isBetterOverloadCandidate(*R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00005916 } else if (R->Viable)
5917 return false;
John McCall81201622010-01-08 04:41:39 +00005918
John McCall1b77e732010-01-15 23:32:50 +00005919 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00005920
John McCall1b77e732010-01-15 23:32:50 +00005921 // Criteria by which we can sort non-viable candidates:
5922 if (!L->Viable) {
5923 // 1. Arity mismatches come after other candidates.
5924 if (L->FailureKind == ovl_fail_too_many_arguments ||
5925 L->FailureKind == ovl_fail_too_few_arguments)
5926 return false;
5927 if (R->FailureKind == ovl_fail_too_many_arguments ||
5928 R->FailureKind == ovl_fail_too_few_arguments)
5929 return true;
John McCall81201622010-01-08 04:41:39 +00005930
John McCall717e8912010-01-23 05:17:32 +00005931 // 2. Bad conversions come first and are ordered by the number
5932 // of bad conversions and quality of good conversions.
5933 if (L->FailureKind == ovl_fail_bad_conversion) {
5934 if (R->FailureKind != ovl_fail_bad_conversion)
5935 return true;
5936
5937 // If there's any ordering between the defined conversions...
5938 // FIXME: this might not be transitive.
5939 assert(L->Conversions.size() == R->Conversions.size());
5940
5941 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00005942 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
5943 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall717e8912010-01-23 05:17:32 +00005944 switch (S.CompareImplicitConversionSequences(L->Conversions[I],
5945 R->Conversions[I])) {
5946 case ImplicitConversionSequence::Better:
5947 leftBetter++;
5948 break;
5949
5950 case ImplicitConversionSequence::Worse:
5951 leftBetter--;
5952 break;
5953
5954 case ImplicitConversionSequence::Indistinguishable:
5955 break;
5956 }
5957 }
5958 if (leftBetter > 0) return true;
5959 if (leftBetter < 0) return false;
5960
5961 } else if (R->FailureKind == ovl_fail_bad_conversion)
5962 return false;
5963
John McCall1b77e732010-01-15 23:32:50 +00005964 // TODO: others?
5965 }
5966
5967 // Sort everything else by location.
5968 SourceLocation LLoc = GetLocationForCandidate(L);
5969 SourceLocation RLoc = GetLocationForCandidate(R);
5970
5971 // Put candidates without locations (e.g. builtins) at the end.
5972 if (LLoc.isInvalid()) return false;
5973 if (RLoc.isInvalid()) return true;
5974
5975 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00005976 }
5977};
5978
John McCall717e8912010-01-23 05:17:32 +00005979/// CompleteNonViableCandidate - Normally, overload resolution only
5980/// computes up to the first
5981void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
5982 Expr **Args, unsigned NumArgs) {
5983 assert(!Cand->Viable);
5984
5985 // Don't do anything on failures other than bad conversion.
5986 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
5987
5988 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00005989 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCall717e8912010-01-23 05:17:32 +00005990 unsigned ConvCount = Cand->Conversions.size();
5991 while (true) {
5992 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
5993 ConvIdx++;
5994 if (Cand->Conversions[ConvIdx - 1].isBad())
5995 break;
5996 }
5997
5998 if (ConvIdx == ConvCount)
5999 return;
6000
John McCallb1bdc622010-02-25 01:37:24 +00006001 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6002 "remaining conversion is initialized?");
6003
Douglas Gregor23ef6c02010-04-16 17:45:54 +00006004 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00006005 // operation somehow.
6006 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00006007
6008 const FunctionProtoType* Proto;
6009 unsigned ArgIdx = ConvIdx;
6010
6011 if (Cand->IsSurrogate) {
6012 QualType ConvType
6013 = Cand->Surrogate->getConversionType().getNonReferenceType();
6014 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6015 ConvType = ConvPtrType->getPointeeType();
6016 Proto = ConvType->getAs<FunctionProtoType>();
6017 ArgIdx--;
6018 } else if (Cand->Function) {
6019 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6020 if (isa<CXXMethodDecl>(Cand->Function) &&
6021 !isa<CXXConstructorDecl>(Cand->Function))
6022 ArgIdx--;
6023 } else {
6024 // Builtin binary operator with a bad first conversion.
6025 assert(ConvCount <= 3);
6026 for (; ConvIdx != ConvCount; ++ConvIdx)
6027 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006028 = TryCopyInitialization(S, Args[ConvIdx],
6029 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6030 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00006031 /*InOverloadResolution*/ true);
John McCall717e8912010-01-23 05:17:32 +00006032 return;
6033 }
6034
6035 // Fill in the rest of the conversions.
6036 unsigned NumArgsInProto = Proto->getNumArgs();
6037 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6038 if (ArgIdx < NumArgsInProto)
6039 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00006040 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6041 SuppressUserConversions,
Douglas Gregor74eb6582010-04-16 17:51:22 +00006042 /*InOverloadResolution=*/true);
John McCall717e8912010-01-23 05:17:32 +00006043 else
6044 Cand->Conversions[ConvIdx].setEllipsis();
6045 }
6046}
6047
John McCalla1d7d622010-01-08 00:58:21 +00006048} // end anonymous namespace
6049
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006050/// PrintOverloadCandidates - When overload resolution fails, prints
6051/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00006052/// set.
Mike Stump1eb44332009-09-09 15:08:12 +00006053void
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006054Sema::PrintOverloadCandidates(OverloadCandidateSet& CandidateSet,
John McCall81201622010-01-08 04:41:39 +00006055 OverloadCandidateDisplayKind OCD,
John McCallcbce6062010-01-12 07:18:19 +00006056 Expr **Args, unsigned NumArgs,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00006057 const char *Opc,
Fariborz Jahanian16a5eac2009-10-09 00:13:15 +00006058 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00006059 // Sort the candidates by viability and position. Sorting directly would
6060 // be prohibitive, so we make a set of pointers and sort those.
6061 llvm::SmallVector<OverloadCandidate*, 32> Cands;
6062 if (OCD == OCD_AllCandidates) Cands.reserve(CandidateSet.size());
6063 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6064 LastCand = CandidateSet.end();
John McCall717e8912010-01-23 05:17:32 +00006065 Cand != LastCand; ++Cand) {
6066 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00006067 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00006068 else if (OCD == OCD_AllCandidates) {
6069 CompleteNonViableCandidate(*this, Cand, Args, NumArgs);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006070 if (Cand->Function || Cand->IsSurrogate)
6071 Cands.push_back(Cand);
6072 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6073 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00006074 }
6075 }
6076
John McCallbf65c0b2010-01-12 00:48:53 +00006077 std::sort(Cands.begin(), Cands.end(),
6078 CompareOverloadCandidatesForDisplay(*this));
John McCall81201622010-01-08 04:41:39 +00006079
John McCall1d318332010-01-12 00:44:57 +00006080 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00006081
John McCall81201622010-01-08 04:41:39 +00006082 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006083 const Diagnostic::OverloadsShown ShowOverloads = Diags.getShowOverloads();
6084 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00006085 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6086 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00006087
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006088 // Set an arbitrary limit on the number of candidate functions we'll spam
6089 // the user with. FIXME: This limit should depend on details of the
6090 // candidate list.
6091 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6092 break;
6093 }
6094 ++CandsShown;
6095
John McCalla1d7d622010-01-08 00:58:21 +00006096 if (Cand->Function)
John McCall220ccbf2010-01-13 00:25:19 +00006097 NoteFunctionCandidate(*this, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00006098 else if (Cand->IsSurrogate)
6099 NoteSurrogateCandidate(*this, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006100 else {
6101 assert(Cand->Viable &&
6102 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00006103 // Generally we only see ambiguities including viable builtin
6104 // operators if overload resolution got screwed up by an
6105 // ambiguous user-defined conversion.
6106 //
6107 // FIXME: It's quite possible for different conversions to see
6108 // different ambiguities, though.
6109 if (!ReportedAmbiguousConversions) {
6110 NoteAmbiguousUserConversions(*this, OpLoc, Cand);
6111 ReportedAmbiguousConversions = true;
6112 }
John McCalla1d7d622010-01-08 00:58:21 +00006113
John McCall1d318332010-01-12 00:44:57 +00006114 // If this is a viable builtin, print it.
John McCalla1d7d622010-01-08 00:58:21 +00006115 NoteBuiltinOperatorCandidate(*this, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006116 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006117 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00006118
6119 if (I != E)
Jeffrey Yasskin258de302010-06-11 06:58:43 +00006120 Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006121}
6122
John McCall9aa472c2010-03-19 07:35:19 +00006123static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCallc373d482010-01-27 01:50:18 +00006124 if (isa<UnresolvedLookupExpr>(E))
John McCall9aa472c2010-03-19 07:35:19 +00006125 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00006126
John McCall9aa472c2010-03-19 07:35:19 +00006127 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCallc373d482010-01-27 01:50:18 +00006128}
6129
Douglas Gregor904eed32008-11-10 20:40:00 +00006130/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6131/// an overloaded function (C++ [over.over]), where @p From is an
6132/// expression with overloaded function type and @p ToType is the type
6133/// we're trying to resolve to. For example:
6134///
6135/// @code
6136/// int f(double);
6137/// int f(int);
Mike Stump1eb44332009-09-09 15:08:12 +00006138///
Douglas Gregor904eed32008-11-10 20:40:00 +00006139/// int (*pfd)(double) = f; // selects f(double)
6140/// @endcode
6141///
6142/// This routine returns the resulting FunctionDecl if it could be
6143/// resolved, and NULL otherwise. When @p Complain is true, this
6144/// routine will emit diagnostics if there is an error.
6145FunctionDecl *
Sebastian Redl33b399a2009-02-04 21:23:32 +00006146Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall6bb80172010-03-30 21:47:33 +00006147 bool Complain,
6148 DeclAccessPair &FoundResult) {
Douglas Gregor904eed32008-11-10 20:40:00 +00006149 QualType FunctionType = ToType;
Sebastian Redl33b399a2009-02-04 21:23:32 +00006150 bool IsMember = false;
Ted Kremenek6217b802009-07-29 21:53:49 +00006151 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregor904eed32008-11-10 20:40:00 +00006152 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00006153 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarbb710012009-02-26 19:13:44 +00006154 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00006155 else if (const MemberPointerType *MemTypePtr =
Ted Kremenek6217b802009-07-29 21:53:49 +00006156 ToType->getAs<MemberPointerType>()) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00006157 FunctionType = MemTypePtr->getPointeeType();
6158 IsMember = true;
6159 }
Douglas Gregor904eed32008-11-10 20:40:00 +00006160
Douglas Gregor904eed32008-11-10 20:40:00 +00006161 // C++ [over.over]p1:
6162 // [...] [Note: any redundant set of parentheses surrounding the
6163 // overloaded function name is ignored (5.1). ]
Douglas Gregor904eed32008-11-10 20:40:00 +00006164 // C++ [over.over]p1:
6165 // [...] The overloaded function name can be preceded by the &
6166 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00006167 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
6168 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6169 if (OvlExpr->hasExplicitTemplateArgs()) {
6170 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6171 ExplicitTemplateArgs = &ETABuffer;
Douglas Gregor904eed32008-11-10 20:40:00 +00006172 }
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006173
6174 // We expect a pointer or reference to function, or a function pointer.
6175 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6176 if (!FunctionType->isFunctionType()) {
6177 if (Complain)
6178 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6179 << OvlExpr->getName() << ToType;
6180
6181 return 0;
6182 }
6183
6184 assert(From->getType() == Context.OverloadTy);
Douglas Gregor904eed32008-11-10 20:40:00 +00006185
Douglas Gregor904eed32008-11-10 20:40:00 +00006186 // Look through all of the overloaded functions, searching for one
6187 // whose type matches exactly.
John McCall9aa472c2010-03-19 07:35:19 +00006188 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb7a09262010-04-01 18:32:35 +00006189 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
6190
Douglas Gregor00aeb522009-07-08 23:33:52 +00006191 bool FoundNonTemplateFunction = false;
John McCall7bb12da2010-02-02 06:20:04 +00006192 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6193 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthbd647292009-12-29 06:17:27 +00006194 // Look through any using declarations to find the underlying function.
6195 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6196
Douglas Gregor904eed32008-11-10 20:40:00 +00006197 // C++ [over.over]p3:
6198 // Non-member functions and static member functions match
Sebastian Redl0defd762009-02-05 12:33:33 +00006199 // targets of type "pointer-to-function" or "reference-to-function."
6200 // Nonstatic member functions match targets of
Sebastian Redl33b399a2009-02-04 21:23:32 +00006201 // type "pointer-to-member-function."
6202 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor83314aa2009-07-08 20:55:45 +00006203
Mike Stump1eb44332009-09-09 15:08:12 +00006204 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthbd647292009-12-29 06:17:27 +00006205 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump1eb44332009-09-09 15:08:12 +00006206 if (CXXMethodDecl *Method
Douglas Gregor00aeb522009-07-08 23:33:52 +00006207 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump1eb44332009-09-09 15:08:12 +00006208 // Skip non-static function templates when converting to pointer, and
Douglas Gregor00aeb522009-07-08 23:33:52 +00006209 // static when converting to member pointer.
6210 if (Method->isStatic() == IsMember)
6211 continue;
6212 } else if (IsMember)
6213 continue;
Mike Stump1eb44332009-09-09 15:08:12 +00006214
Douglas Gregor00aeb522009-07-08 23:33:52 +00006215 // C++ [over.over]p2:
Mike Stump1eb44332009-09-09 15:08:12 +00006216 // If the name is a function template, template argument deduction is
6217 // done (14.8.2.2), and if the argument deduction succeeds, the
6218 // resulting template argument list is used to generate a single
6219 // function template specialization, which is added to the set of
Douglas Gregor00aeb522009-07-08 23:33:52 +00006220 // overloaded functions considered.
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00006221 // FIXME: We don't really want to build the specialization here, do we?
Douglas Gregor83314aa2009-07-08 20:55:45 +00006222 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00006223 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor83314aa2009-07-08 20:55:45 +00006224 if (TemplateDeductionResult Result
John McCall7bb12da2010-02-02 06:20:04 +00006225 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor83314aa2009-07-08 20:55:45 +00006226 FunctionType, Specialization, Info)) {
6227 // FIXME: make a note of the failed deduction for diagnostics.
6228 (void)Result;
6229 } else {
Douglas Gregorb9aa6b22009-09-24 23:14:47 +00006230 // FIXME: If the match isn't exact, shouldn't we just drop this as
6231 // a candidate? Find a testcase before changing the code.
Mike Stump1eb44332009-09-09 15:08:12 +00006232 assert(FunctionType
Douglas Gregor83314aa2009-07-08 20:55:45 +00006233 == Context.getCanonicalType(Specialization->getType()));
John McCall9aa472c2010-03-19 07:35:19 +00006234 Matches.push_back(std::make_pair(I.getPair(),
6235 cast<FunctionDecl>(Specialization->getCanonicalDecl())));
Douglas Gregor83314aa2009-07-08 20:55:45 +00006236 }
John McCallba135432009-11-21 08:51:07 +00006237
6238 continue;
Douglas Gregor83314aa2009-07-08 20:55:45 +00006239 }
Mike Stump1eb44332009-09-09 15:08:12 +00006240
Chandler Carruthbd647292009-12-29 06:17:27 +00006241 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00006242 // Skip non-static functions when converting to pointer, and static
6243 // when converting to member pointer.
6244 if (Method->isStatic() == IsMember)
Douglas Gregor904eed32008-11-10 20:40:00 +00006245 continue;
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006246
6247 // If we have explicit template arguments, skip non-templates.
John McCall7bb12da2010-02-02 06:20:04 +00006248 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00006249 continue;
Douglas Gregor00aeb522009-07-08 23:33:52 +00006250 } else if (IsMember)
Sebastian Redl33b399a2009-02-04 21:23:32 +00006251 continue;
Douglas Gregor904eed32008-11-10 20:40:00 +00006252
Chandler Carruthbd647292009-12-29 06:17:27 +00006253 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00006254 QualType ResultTy;
6255 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6256 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6257 ResultTy)) {
John McCall9aa472c2010-03-19 07:35:19 +00006258 Matches.push_back(std::make_pair(I.getPair(),
6259 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00006260 FoundNonTemplateFunction = true;
6261 }
Mike Stump1eb44332009-09-09 15:08:12 +00006262 }
Douglas Gregor904eed32008-11-10 20:40:00 +00006263 }
6264
Douglas Gregor00aeb522009-07-08 23:33:52 +00006265 // If there were 0 or 1 matches, we're done.
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006266 if (Matches.empty()) {
6267 if (Complain) {
6268 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6269 << OvlExpr->getName() << FunctionType;
6270 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6271 E = OvlExpr->decls_end();
6272 I != E; ++I)
6273 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6274 NoteOverloadCandidate(F);
6275 }
6276
Douglas Gregor00aeb522009-07-08 23:33:52 +00006277 return 0;
Douglas Gregor1a8cf732010-04-14 23:11:21 +00006278 } else if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00006279 FunctionDecl *Result = Matches[0].second;
John McCall6bb80172010-03-30 21:47:33 +00006280 FoundResult = Matches[0].first;
Sebastian Redl07ab2022009-10-17 21:12:09 +00006281 MarkDeclarationReferenced(From->getLocStart(), Result);
John McCallc373d482010-01-27 01:50:18 +00006282 if (Complain)
John McCall6bb80172010-03-30 21:47:33 +00006283 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Sebastian Redl07ab2022009-10-17 21:12:09 +00006284 return Result;
6285 }
Douglas Gregor00aeb522009-07-08 23:33:52 +00006286
6287 // C++ [over.over]p4:
6288 // If more than one function is selected, [...]
Douglas Gregor312a2022009-09-26 03:56:17 +00006289 if (!FoundNonTemplateFunction) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006290 // [...] and any given function template specialization F1 is
6291 // eliminated if the set contains a second function template
6292 // specialization whose function template is more specialized
6293 // than the function template of F1 according to the partial
6294 // ordering rules of 14.5.5.2.
6295
6296 // The algorithm specified above is quadratic. We instead use a
6297 // two-pass algorithm (similar to the one used to identify the
6298 // best viable function in an overload set) that identifies the
6299 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00006300
6301 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6302 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6303 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCallc373d482010-01-27 01:50:18 +00006304
6305 UnresolvedSetIterator Result =
John McCall9aa472c2010-03-19 07:35:19 +00006306 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Sebastian Redl07ab2022009-10-17 21:12:09 +00006307 TPOC_Other, From->getLocStart(),
6308 PDiag(),
6309 PDiag(diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00006310 << Matches[0].second->getDeclName(),
John McCall220ccbf2010-01-13 00:25:19 +00006311 PDiag(diag::note_ovl_candidate)
6312 << (unsigned) oc_function_template);
John McCall9aa472c2010-03-19 07:35:19 +00006313 assert(Result != MatchesCopy.end() && "no most-specialized template");
John McCallc373d482010-01-27 01:50:18 +00006314 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall6bb80172010-03-30 21:47:33 +00006315 FoundResult = Matches[Result - MatchesCopy.begin()].first;
John McCallb697e082010-05-06 18:15:07 +00006316 if (Complain) {
John McCall6bb80172010-03-30 21:47:33 +00006317 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCallb697e082010-05-06 18:15:07 +00006318 DiagnoseUseOfDecl(FoundResult, OvlExpr->getNameLoc());
6319 }
John McCallc373d482010-01-27 01:50:18 +00006320 return cast<FunctionDecl>(*Result);
Douglas Gregor00aeb522009-07-08 23:33:52 +00006321 }
Mike Stump1eb44332009-09-09 15:08:12 +00006322
Douglas Gregor312a2022009-09-26 03:56:17 +00006323 // [...] any function template specializations in the set are
6324 // eliminated if the set also contains a non-template function, [...]
John McCallc373d482010-01-27 01:50:18 +00006325 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCall9aa472c2010-03-19 07:35:19 +00006326 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCallc373d482010-01-27 01:50:18 +00006327 ++I;
6328 else {
John McCall9aa472c2010-03-19 07:35:19 +00006329 Matches[I] = Matches[--N];
6330 Matches.set_size(N);
John McCallc373d482010-01-27 01:50:18 +00006331 }
6332 }
Douglas Gregor312a2022009-09-26 03:56:17 +00006333
Mike Stump1eb44332009-09-09 15:08:12 +00006334 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregor00aeb522009-07-08 23:33:52 +00006335 // selected function.
John McCallc373d482010-01-27 01:50:18 +00006336 if (Matches.size() == 1) {
John McCall9aa472c2010-03-19 07:35:19 +00006337 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall6bb80172010-03-30 21:47:33 +00006338 FoundResult = Matches[0].first;
John McCallb697e082010-05-06 18:15:07 +00006339 if (Complain) {
John McCall9aa472c2010-03-19 07:35:19 +00006340 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
John McCallb697e082010-05-06 18:15:07 +00006341 DiagnoseUseOfDecl(Matches[0].first, OvlExpr->getNameLoc());
6342 }
John McCall9aa472c2010-03-19 07:35:19 +00006343 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redl07ab2022009-10-17 21:12:09 +00006344 }
Mike Stump1eb44332009-09-09 15:08:12 +00006345
Douglas Gregor00aeb522009-07-08 23:33:52 +00006346 // FIXME: We should probably return the same thing that BestViableFunction
6347 // returns (even if we issue the diagnostics here).
6348 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
John McCall9aa472c2010-03-19 07:35:19 +00006349 << Matches[0].second->getDeclName();
6350 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6351 NoteOverloadCandidate(Matches[I].second);
Douglas Gregor904eed32008-11-10 20:40:00 +00006352 return 0;
6353}
6354
Douglas Gregor4b52e252009-12-21 23:17:24 +00006355/// \brief Given an expression that refers to an overloaded function, try to
6356/// resolve that overloaded function expression down to a single function.
6357///
6358/// This routine can only resolve template-ids that refer to a single function
6359/// template, where that template-id refers to a single template whose template
6360/// arguments are either provided by the template-id or have defaults,
6361/// as described in C++0x [temp.arg.explicit]p3.
6362FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
6363 // C++ [over.over]p1:
6364 // [...] [Note: any redundant set of parentheses surrounding the
6365 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00006366 // C++ [over.over]p1:
6367 // [...] The overloaded function name can be preceded by the &
6368 // operator.
John McCall7bb12da2010-02-02 06:20:04 +00006369
6370 if (From->getType() != Context.OverloadTy)
6371 return 0;
6372
6373 OverloadExpr *OvlExpr = OverloadExpr::find(From).getPointer();
Douglas Gregor4b52e252009-12-21 23:17:24 +00006374
6375 // If we didn't actually find any template-ids, we're done.
John McCall7bb12da2010-02-02 06:20:04 +00006376 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00006377 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00006378
6379 TemplateArgumentListInfo ExplicitTemplateArgs;
6380 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor4b52e252009-12-21 23:17:24 +00006381
6382 // Look through all of the overloaded functions, searching for one
6383 // whose type matches exactly.
6384 FunctionDecl *Matched = 0;
John McCall7bb12da2010-02-02 06:20:04 +00006385 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6386 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00006387 // C++0x [temp.arg.explicit]p3:
6388 // [...] In contexts where deduction is done and fails, or in contexts
6389 // where deduction is not done, if a template argument list is
6390 // specified and it, along with any default template arguments,
6391 // identifies a single function template specialization, then the
6392 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00006393 FunctionTemplateDecl *FunctionTemplate
6394 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor4b52e252009-12-21 23:17:24 +00006395
6396 // C++ [over.over]p2:
6397 // If the name is a function template, template argument deduction is
6398 // done (14.8.2.2), and if the argument deduction succeeds, the
6399 // resulting template argument list is used to generate a single
6400 // function template specialization, which is added to the set of
6401 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00006402 FunctionDecl *Specialization = 0;
John McCall5769d612010-02-08 23:07:23 +00006403 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00006404 if (TemplateDeductionResult Result
6405 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
6406 Specialization, Info)) {
6407 // FIXME: make a note of the failed deduction for diagnostics.
6408 (void)Result;
6409 continue;
6410 }
6411
6412 // Multiple matches; we can't resolve to a single declaration.
6413 if (Matched)
6414 return 0;
6415
6416 Matched = Specialization;
6417 }
6418
6419 return Matched;
6420}
6421
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006422/// \brief Add a single candidate to the overload set.
6423static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00006424 DeclAccessPair FoundDecl,
John McCalld5532b62009-11-23 01:53:49 +00006425 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006426 Expr **Args, unsigned NumArgs,
6427 OverloadCandidateSet &CandidateSet,
6428 bool PartialOverloading) {
John McCall9aa472c2010-03-19 07:35:19 +00006429 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00006430 if (isa<UsingShadowDecl>(Callee))
6431 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
6432
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006433 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCalld5532b62009-11-23 01:53:49 +00006434 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCall9aa472c2010-03-19 07:35:19 +00006435 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00006436 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006437 return;
John McCallba135432009-11-21 08:51:07 +00006438 }
6439
6440 if (FunctionTemplateDecl *FuncTemplate
6441 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00006442 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
6443 ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00006444 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00006445 return;
6446 }
6447
6448 assert(false && "unhandled case in overloaded call candidate");
6449
6450 // do nothing?
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006451}
6452
6453/// \brief Add the overload candidates named by callee and/or found by argument
6454/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00006455void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006456 Expr **Args, unsigned NumArgs,
6457 OverloadCandidateSet &CandidateSet,
6458 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00006459
6460#ifndef NDEBUG
6461 // Verify that ArgumentDependentLookup is consistent with the rules
6462 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006463 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006464 // Let X be the lookup set produced by unqualified lookup (3.4.1)
6465 // and let Y be the lookup set produced by argument dependent
6466 // lookup (defined as follows). If X contains
6467 //
6468 // -- a declaration of a class member, or
6469 //
6470 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00006471 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006472 //
6473 // -- a declaration that is neither a function or a function
6474 // template
6475 //
6476 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00006477
John McCall3b4294e2009-12-16 12:17:52 +00006478 if (ULE->requiresADL()) {
6479 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6480 E = ULE->decls_end(); I != E; ++I) {
6481 assert(!(*I)->getDeclContext()->isRecord());
6482 assert(isa<UsingShadowDecl>(*I) ||
6483 !(*I)->getDeclContext()->isFunctionOrMethod());
6484 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00006485 }
6486 }
6487#endif
6488
John McCall3b4294e2009-12-16 12:17:52 +00006489 // It would be nice to avoid this copy.
6490 TemplateArgumentListInfo TABuffer;
6491 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6492 if (ULE->hasExplicitTemplateArgs()) {
6493 ULE->copyTemplateArgumentsInto(TABuffer);
6494 ExplicitTemplateArgs = &TABuffer;
6495 }
6496
6497 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
6498 E = ULE->decls_end(); I != E; ++I)
John McCall9aa472c2010-03-19 07:35:19 +00006499 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00006500 Args, NumArgs, CandidateSet,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006501 PartialOverloading);
John McCallba135432009-11-21 08:51:07 +00006502
John McCall3b4294e2009-12-16 12:17:52 +00006503 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00006504 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
6505 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006506 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006507 CandidateSet,
6508 PartialOverloading);
6509}
John McCall578b69b2009-12-16 08:11:27 +00006510
6511/// Attempts to recover from a call where no functions were found.
6512///
6513/// Returns true if new candidates were found.
John McCall3b4294e2009-12-16 12:17:52 +00006514static Sema::OwningExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006515BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00006516 UnresolvedLookupExpr *ULE,
6517 SourceLocation LParenLoc,
6518 Expr **Args, unsigned NumArgs,
6519 SourceLocation *CommaLocs,
6520 SourceLocation RParenLoc) {
John McCall578b69b2009-12-16 08:11:27 +00006521
6522 CXXScopeSpec SS;
6523 if (ULE->getQualifier()) {
6524 SS.setScopeRep(ULE->getQualifier());
6525 SS.setRange(ULE->getQualifierRange());
6526 }
6527
John McCall3b4294e2009-12-16 12:17:52 +00006528 TemplateArgumentListInfo TABuffer;
6529 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
6530 if (ULE->hasExplicitTemplateArgs()) {
6531 ULE->copyTemplateArgumentsInto(TABuffer);
6532 ExplicitTemplateArgs = &TABuffer;
6533 }
6534
John McCall578b69b2009-12-16 08:11:27 +00006535 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
6536 Sema::LookupOrdinaryName);
Douglas Gregor91f7ac72010-05-18 16:14:23 +00006537 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
Douglas Gregorff331c12010-07-25 18:17:45 +00006538 return SemaRef.ExprError();
John McCall578b69b2009-12-16 08:11:27 +00006539
John McCall3b4294e2009-12-16 12:17:52 +00006540 assert(!R.empty() && "lookup results empty despite recovery");
6541
6542 // Build an implicit member call if appropriate. Just drop the
6543 // casts and such from the call, we don't really care.
6544 Sema::OwningExprResult NewFn = SemaRef.ExprError();
6545 if ((*R.begin())->isCXXClassMember())
6546 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R, ExplicitTemplateArgs);
6547 else if (ExplicitTemplateArgs)
6548 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
6549 else
6550 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
6551
6552 if (NewFn.isInvalid())
Douglas Gregorff331c12010-07-25 18:17:45 +00006553 return SemaRef.ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00006554
6555 // This shouldn't cause an infinite loop because we're giving it
6556 // an expression with non-empty lookup results, which should never
6557 // end up here.
6558 return SemaRef.ActOnCallExpr(/*Scope*/ 0, move(NewFn), LParenLoc,
6559 Sema::MultiExprArg(SemaRef, (void**) Args, NumArgs),
6560 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00006561}
Douglas Gregord7a95972010-06-08 17:35:15 +00006562
Douglas Gregorf6b89692008-11-26 05:54:23 +00006563/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00006564/// (which eventually refers to the declaration Func) and the call
6565/// arguments Args/NumArgs, attempt to resolve the function call down
6566/// to a specific function. If overload resolution succeeds, returns
6567/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00006568/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00006569/// arguments and Fn, and returns NULL.
John McCall3b4294e2009-12-16 12:17:52 +00006570Sema::OwningExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006571Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00006572 SourceLocation LParenLoc,
6573 Expr **Args, unsigned NumArgs,
6574 SourceLocation *CommaLocs,
6575 SourceLocation RParenLoc) {
6576#ifndef NDEBUG
6577 if (ULE->requiresADL()) {
6578 // To do ADL, we must have found an unqualified name.
6579 assert(!ULE->getQualifier() && "qualified name with ADL");
6580
6581 // We don't perform ADL for implicit declarations of builtins.
6582 // Verify that this was correctly set up.
6583 FunctionDecl *F;
6584 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
6585 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
6586 F->getBuiltinID() && F->isImplicit())
6587 assert(0 && "performing ADL for builtin");
6588
6589 // We don't perform ADL in C.
6590 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
6591 }
6592#endif
6593
John McCall5769d612010-02-08 23:07:23 +00006594 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00006595
John McCall3b4294e2009-12-16 12:17:52 +00006596 // Add the functions denoted by the callee to the set of candidate
6597 // functions, including those from argument-dependent lookup.
6598 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00006599
6600 // If we found nothing, try to recover.
6601 // AddRecoveryCallCandidates diagnoses the error itself, so we just
6602 // bailout out if it fails.
John McCall3b4294e2009-12-16 12:17:52 +00006603 if (CandidateSet.empty())
Douglas Gregor1aae80b2010-04-14 20:27:54 +00006604 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
John McCall3b4294e2009-12-16 12:17:52 +00006605 CommaLocs, RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00006606
Douglas Gregorf6b89692008-11-26 05:54:23 +00006607 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006608 switch (BestViableFunction(CandidateSet, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00006609 case OR_Success: {
6610 FunctionDecl *FDecl = Best->Function;
John McCall9aa472c2010-03-19 07:35:19 +00006611 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00006612 DiagnoseUseOfDecl(Best->FoundDecl, ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00006613 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
John McCall3b4294e2009-12-16 12:17:52 +00006614 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc);
6615 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00006616
6617 case OR_No_Viable_Function:
Chris Lattner4330d652009-02-17 07:29:20 +00006618 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00006619 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00006620 << ULE->getName() << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006621 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00006622 break;
6623
6624 case OR_Ambiguous:
6625 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00006626 << ULE->getName() << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006627 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00006628 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006629
6630 case OR_Deleted:
6631 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
6632 << Best->Function->isDeleted()
John McCall3b4294e2009-12-16 12:17:52 +00006633 << ULE->getName()
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006634 << Fn->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006635 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006636 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00006637 }
6638
Douglas Gregorff331c12010-07-25 18:17:45 +00006639 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00006640 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00006641}
6642
John McCall6e266892010-01-26 03:27:55 +00006643static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00006644 return Functions.size() > 1 ||
6645 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
6646}
6647
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006648/// \brief Create a unary operation that may resolve to an overloaded
6649/// operator.
6650///
6651/// \param OpLoc The location of the operator itself (e.g., '*').
6652///
6653/// \param OpcIn The UnaryOperator::Opcode that describes this
6654/// operator.
6655///
6656/// \param Functions The set of non-member functions that will be
6657/// considered by overload resolution. The caller needs to build this
6658/// set based on the context using, e.g.,
6659/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6660/// set should not contain any member functions; those will be added
6661/// by CreateOverloadedUnaryOp().
6662///
6663/// \param input The input argument.
John McCall6e266892010-01-26 03:27:55 +00006664Sema::OwningExprResult
6665Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
6666 const UnresolvedSetImpl &Fns,
6667 ExprArg input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006668 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
6669 Expr *Input = (Expr *)input.get();
6670
6671 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
6672 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
6673 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00006674 // TODO: provide better source location info.
6675 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006676
6677 Expr *Args[2] = { Input, 0 };
6678 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00006679
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006680 // For post-increment and post-decrement, add the implicit '0' as
6681 // the second argument, so that we know this is a post-increment or
6682 // post-decrement.
6683 if (Opc == UnaryOperator::PostInc || Opc == UnaryOperator::PostDec) {
6684 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Mike Stump1eb44332009-09-09 15:08:12 +00006685 Args[1] = new (Context) IntegerLiteral(Zero, Context.IntTy,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006686 SourceLocation());
6687 NumArgs = 2;
6688 }
6689
6690 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00006691 if (Fns.empty())
6692 return Owned(new (Context) UnaryOperator(input.takeAs<Expr>(),
6693 Opc,
6694 Context.DependentTy,
6695 OpLoc));
6696
John McCallc373d482010-01-27 01:50:18 +00006697 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00006698 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00006699 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00006700 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00006701 /*ADL*/ true, IsOverloaded(Fns),
6702 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006703 input.release();
6704 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
6705 &Args[0], NumArgs,
6706 Context.DependentTy,
6707 OpLoc));
6708 }
6709
6710 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00006711 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006712
6713 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00006714 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006715
6716 // Add operator candidates that are member functions.
6717 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
6718
John McCall6e266892010-01-26 03:27:55 +00006719 // Add candidates from ADL.
6720 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregordc81c882010-02-05 05:15:43 +00006721 Args, NumArgs,
John McCall6e266892010-01-26 03:27:55 +00006722 /*ExplicitTemplateArgs*/ 0,
6723 CandidateSet);
6724
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006725 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00006726 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006727
6728 // Perform overload resolution.
6729 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006730 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006731 case OR_Success: {
6732 // We found a built-in operator or an overloaded operator.
6733 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00006734
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006735 if (FnDecl) {
6736 // We matched an overloaded operator. Build a call to that
6737 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00006738
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006739 // Convert the arguments.
6740 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00006741 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00006742
John McCall6bb80172010-03-30 21:47:33 +00006743 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
6744 Best->FoundDecl, Method))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006745 return ExprError();
6746 } else {
6747 // Convert the arguments.
Douglas Gregore1a5c172009-12-23 17:40:29 +00006748 OwningExprResult InputInit
6749 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Douglas Gregorbaecfed2009-12-23 00:02:00 +00006750 FnDecl->getParamDecl(0)),
Douglas Gregore1a5c172009-12-23 17:40:29 +00006751 SourceLocation(),
6752 move(input));
6753 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006754 return ExprError();
Douglas Gregorbaecfed2009-12-23 00:02:00 +00006755
Douglas Gregore1a5c172009-12-23 17:40:29 +00006756 input = move(InputInit);
Douglas Gregorbaecfed2009-12-23 00:02:00 +00006757 Input = (Expr *)input.get();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006758 }
6759
John McCallb697e082010-05-06 18:15:07 +00006760 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6761
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006762 // Determine the result type
Douglas Gregor5291c3c2010-07-13 08:18:22 +00006763 QualType ResultTy = FnDecl->getCallResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00006764
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006765 // Build the actual expression node.
6766 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
6767 SourceLocation());
6768 UsualUnaryConversions(FnExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00006769
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006770 input.release();
Eli Friedman4c3b8962009-11-18 03:58:17 +00006771 Args[0] = Input;
Anders Carlsson26a2a072009-10-13 21:19:37 +00006772 ExprOwningPtr<CallExpr> TheCall(this,
6773 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
Eli Friedman4c3b8962009-11-18 03:58:17 +00006774 Args, NumArgs, ResultTy, OpLoc));
John McCallb697e082010-05-06 18:15:07 +00006775
Anders Carlsson26a2a072009-10-13 21:19:37 +00006776 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6777 FnDecl))
6778 return ExprError();
6779
6780 return MaybeBindToTemporary(TheCall.release());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006781 } else {
6782 // We matched a built-in operator. Convert the arguments, then
6783 // break out so that we will build the appropriate built-in
6784 // operator node.
6785 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00006786 Best->Conversions[0], AA_Passing))
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006787 return ExprError();
6788
6789 break;
6790 }
6791 }
6792
6793 case OR_No_Viable_Function:
6794 // No viable function; fall through to handling this as a
6795 // built-in operator, which will produce an error message for us.
6796 break;
6797
6798 case OR_Ambiguous:
6799 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
6800 << UnaryOperator::getOpcodeStr(Opc)
6801 << Input->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006802 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00006803 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006804 return ExprError();
6805
6806 case OR_Deleted:
6807 Diag(OpLoc, diag::err_ovl_deleted_oper)
6808 << Best->Function->isDeleted()
6809 << UnaryOperator::getOpcodeStr(Opc)
6810 << Input->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00006811 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006812 return ExprError();
6813 }
6814
6815 // Either we found no viable overloaded operator or we matched a
6816 // built-in operator. In either case, fall through to trying to
6817 // build a built-in operation.
6818 input.release();
6819 return CreateBuiltinUnaryOp(OpLoc, Opc, Owned(Input));
6820}
6821
Douglas Gregor063daf62009-03-13 18:40:31 +00006822/// \brief Create a binary operation that may resolve to an overloaded
6823/// operator.
6824///
6825/// \param OpLoc The location of the operator itself (e.g., '+').
6826///
6827/// \param OpcIn The BinaryOperator::Opcode that describes this
6828/// operator.
6829///
6830/// \param Functions The set of non-member functions that will be
6831/// considered by overload resolution. The caller needs to build this
6832/// set based on the context using, e.g.,
6833/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
6834/// set should not contain any member functions; those will be added
6835/// by CreateOverloadedBinOp().
6836///
6837/// \param LHS Left-hand argument.
6838/// \param RHS Right-hand argument.
Mike Stump1eb44332009-09-09 15:08:12 +00006839Sema::OwningExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00006840Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00006841 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00006842 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00006843 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00006844 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006845 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00006846
6847 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
6848 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
6849 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
6850
6851 // If either side is type-dependent, create an appropriate dependent
6852 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006853 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00006854 if (Fns.empty()) {
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00006855 // If there are no functions to store, just build a dependent
6856 // BinaryOperator or CompoundAssignment.
6857 if (Opc <= BinaryOperator::Assign || Opc > BinaryOperator::OrAssign)
6858 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
6859 Context.DependentTy, OpLoc));
6860
6861 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
6862 Context.DependentTy,
6863 Context.DependentTy,
6864 Context.DependentTy,
6865 OpLoc));
6866 }
John McCall6e266892010-01-26 03:27:55 +00006867
6868 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00006869 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00006870 // TODO: provide better source location info in DNLoc component.
6871 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +00006872 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00006873 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00006874 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00006875 /*ADL*/ true, IsOverloaded(Fns),
6876 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00006877 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00006878 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00006879 Context.DependentTy,
6880 OpLoc));
6881 }
6882
6883 // If this is the .* operator, which is not overloadable, just
6884 // create a built-in binary operator.
6885 if (Opc == BinaryOperator::PtrMemD)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006886 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00006887
Sebastian Redl275c2b42009-11-18 23:10:33 +00006888 // If this is the assignment operator, we only perform overload resolution
6889 // if the left-hand side is a class or enumeration type. This is actually
6890 // a hack. The standard requires that we do overload resolution between the
6891 // various built-in candidates, but as DR507 points out, this can lead to
6892 // problems. So we do it this way, which pretty much follows what GCC does.
6893 // Note that we go the traditional code path for compound assignment forms.
6894 if (Opc==BinaryOperator::Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006895 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00006896
Douglas Gregorbc736fc2009-03-13 23:49:33 +00006897 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00006898 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00006899
6900 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00006901 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00006902
6903 // Add operator candidates that are member functions.
6904 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
6905
John McCall6e266892010-01-26 03:27:55 +00006906 // Add candidates from ADL.
6907 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
6908 Args, 2,
6909 /*ExplicitTemplateArgs*/ 0,
6910 CandidateSet);
6911
Douglas Gregor063daf62009-03-13 18:40:31 +00006912 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00006913 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00006914
6915 // Perform overload resolution.
6916 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00006917 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00006918 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00006919 // We found a built-in operator or an overloaded operator.
6920 FunctionDecl *FnDecl = Best->Function;
6921
6922 if (FnDecl) {
6923 // We matched an overloaded operator. Build a call to that
6924 // operator.
6925
6926 // Convert the arguments.
6927 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00006928 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +00006929 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00006930
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006931 OwningExprResult Arg1
6932 = PerformCopyInitialization(
6933 InitializedEntity::InitializeParameter(
6934 FnDecl->getParamDecl(0)),
6935 SourceLocation(),
6936 Owned(Args[1]));
6937 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00006938 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006939
Douglas Gregor5fccd362010-03-03 23:55:11 +00006940 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00006941 Best->FoundDecl, Method))
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006942 return ExprError();
6943
6944 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00006945 } else {
6946 // Convert the arguments.
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006947 OwningExprResult Arg0
6948 = PerformCopyInitialization(
6949 InitializedEntity::InitializeParameter(
6950 FnDecl->getParamDecl(0)),
6951 SourceLocation(),
6952 Owned(Args[0]));
6953 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00006954 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00006955
6956 OwningExprResult Arg1
6957 = PerformCopyInitialization(
6958 InitializedEntity::InitializeParameter(
6959 FnDecl->getParamDecl(1)),
6960 SourceLocation(),
6961 Owned(Args[1]));
6962 if (Arg1.isInvalid())
6963 return ExprError();
6964 Args[0] = LHS = Arg0.takeAs<Expr>();
6965 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00006966 }
6967
John McCallb697e082010-05-06 18:15:07 +00006968 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
6969
Douglas Gregor063daf62009-03-13 18:40:31 +00006970 // Determine the result type
6971 QualType ResultTy
Douglas Gregor5291c3c2010-07-13 08:18:22 +00006972 = FnDecl->getType()->getAs<FunctionType>()
6973 ->getCallResultType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +00006974
6975 // Build the actual expression node.
6976 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
Argyrios Kyrtzidis81273092009-07-14 03:19:38 +00006977 OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00006978 UsualUnaryConversions(FnExpr);
6979
Anders Carlsson15ea3782009-10-13 22:43:21 +00006980 ExprOwningPtr<CXXOperatorCallExpr>
6981 TheCall(this, new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
6982 Args, 2, ResultTy,
6983 OpLoc));
6984
6985 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall.get(),
6986 FnDecl))
6987 return ExprError();
6988
6989 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor063daf62009-03-13 18:40:31 +00006990 } else {
6991 // We matched a built-in operator. Convert the arguments, then
6992 // break out so that we will build the appropriate built-in
6993 // operator node.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006994 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00006995 Best->Conversions[0], AA_Passing) ||
Douglas Gregorc3384cb2009-08-26 17:08:25 +00006996 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00006997 Best->Conversions[1], AA_Passing))
Douglas Gregor063daf62009-03-13 18:40:31 +00006998 return ExprError();
6999
7000 break;
7001 }
7002 }
7003
Douglas Gregor33074752009-09-30 21:46:01 +00007004 case OR_No_Viable_Function: {
7005 // C++ [over.match.oper]p9:
7006 // If the operator is the operator , [...] and there are no
7007 // viable functions, then the operator is assumed to be the
7008 // built-in operator and interpreted according to clause 5.
7009 if (Opc == BinaryOperator::Comma)
7010 break;
7011
Sebastian Redl8593c782009-05-21 11:50:50 +00007012 // For class as left operand for assignment or compound assigment operator
7013 // do not fall through to handling in built-in, but report that no overloaded
7014 // assignment operator found
Douglas Gregor33074752009-09-30 21:46:01 +00007015 OwningExprResult Result = ExprError();
7016 if (Args[0]->getType()->isRecordType() &&
7017 Opc >= BinaryOperator::Assign && Opc <= BinaryOperator::OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00007018 Diag(OpLoc, diag::err_ovl_no_viable_oper)
7019 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007020 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00007021 } else {
7022 // No viable function; try to create a built-in operation, which will
7023 // produce an error. Then, show the non-viable candidates.
7024 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00007025 }
Douglas Gregor33074752009-09-30 21:46:01 +00007026 assert(Result.isInvalid() &&
7027 "C++ binary operator overloading is missing candidates!");
7028 if (Result.isInvalid())
John McCallcbce6062010-01-12 07:18:19 +00007029 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00007030 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00007031 return move(Result);
7032 }
Douglas Gregor063daf62009-03-13 18:40:31 +00007033
7034 case OR_Ambiguous:
7035 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
7036 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007037 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007038 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Fariborz Jahanian2ebe7eb2009-10-12 20:11:40 +00007039 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00007040 return ExprError();
7041
7042 case OR_Deleted:
7043 Diag(OpLoc, diag::err_ovl_deleted_oper)
7044 << Best->Function->isDeleted()
7045 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007046 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007047 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2);
Douglas Gregor063daf62009-03-13 18:40:31 +00007048 return ExprError();
John McCall1d318332010-01-12 00:44:57 +00007049 }
Douglas Gregor063daf62009-03-13 18:40:31 +00007050
Douglas Gregor33074752009-09-30 21:46:01 +00007051 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00007052 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00007053}
7054
Sebastian Redlf322ed62009-10-29 20:17:01 +00007055Action::OwningExprResult
7056Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7057 SourceLocation RLoc,
7058 ExprArg Base, ExprArg Idx) {
7059 Expr *Args[2] = { static_cast<Expr*>(Base.get()),
7060 static_cast<Expr*>(Idx.get()) };
7061 DeclarationName OpName =
7062 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7063
7064 // If either side is type-dependent, create an appropriate dependent
7065 // expression.
7066 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7067
John McCallc373d482010-01-27 01:50:18 +00007068 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00007069 // CHECKME: no 'operator' keyword?
7070 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7071 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +00007072 UnresolvedLookupExpr *Fn
John McCallc373d482010-01-27 01:50:18 +00007073 = UnresolvedLookupExpr::Create(Context, /*Dependent*/ true, NamingClass,
Abramo Bagnara25777432010-08-11 22:01:17 +00007074 0, SourceRange(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00007075 /*ADL*/ true, /*Overloaded*/ false,
7076 UnresolvedSetIterator(),
7077 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +00007078 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00007079
7080 Base.release();
7081 Idx.release();
7082 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7083 Args, 2,
7084 Context.DependentTy,
7085 RLoc));
7086 }
7087
7088 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00007089 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007090
7091 // Subscript can only be overloaded as a member function.
7092
7093 // Add operator candidates that are member functions.
7094 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7095
7096 // Add builtin operator candidates.
7097 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7098
7099 // Perform overload resolution.
7100 OverloadCandidateSet::iterator Best;
7101 switch (BestViableFunction(CandidateSet, LLoc, Best)) {
7102 case OR_Success: {
7103 // We found a built-in operator or an overloaded operator.
7104 FunctionDecl *FnDecl = Best->Function;
7105
7106 if (FnDecl) {
7107 // We matched an overloaded operator. Build a call to that
7108 // operator.
7109
John McCall9aa472c2010-03-19 07:35:19 +00007110 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007111 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +00007112
Sebastian Redlf322ed62009-10-29 20:17:01 +00007113 // Convert the arguments.
7114 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007115 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007116 Best->FoundDecl, Method))
Sebastian Redlf322ed62009-10-29 20:17:01 +00007117 return ExprError();
7118
Anders Carlsson38f88ab2010-01-29 18:37:50 +00007119 // Convert the arguments.
7120 OwningExprResult InputInit
7121 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7122 FnDecl->getParamDecl(0)),
7123 SourceLocation(),
7124 Owned(Args[1]));
7125 if (InputInit.isInvalid())
7126 return ExprError();
7127
7128 Args[1] = InputInit.takeAs<Expr>();
7129
Sebastian Redlf322ed62009-10-29 20:17:01 +00007130 // Determine the result type
7131 QualType ResultTy
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007132 = FnDecl->getType()->getAs<FunctionType>()
7133 ->getCallResultType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007134
7135 // Build the actual expression node.
7136 Expr *FnExpr = new (Context) DeclRefExpr(FnDecl, FnDecl->getType(),
7137 LLoc);
7138 UsualUnaryConversions(FnExpr);
7139
7140 Base.release();
7141 Idx.release();
7142 ExprOwningPtr<CXXOperatorCallExpr>
7143 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7144 FnExpr, Args, 2,
7145 ResultTy, RLoc));
7146
7147 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall.get(),
7148 FnDecl))
7149 return ExprError();
7150
7151 return MaybeBindToTemporary(TheCall.release());
7152 } else {
7153 // We matched a built-in operator. Convert the arguments, then
7154 // break out so that we will build the appropriate built-in
7155 // operator node.
7156 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor68647482009-12-16 03:45:30 +00007157 Best->Conversions[0], AA_Passing) ||
Sebastian Redlf322ed62009-10-29 20:17:01 +00007158 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor68647482009-12-16 03:45:30 +00007159 Best->Conversions[1], AA_Passing))
Sebastian Redlf322ed62009-10-29 20:17:01 +00007160 return ExprError();
7161
7162 break;
7163 }
7164 }
7165
7166 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00007167 if (CandidateSet.empty())
7168 Diag(LLoc, diag::err_ovl_no_oper)
7169 << Args[0]->getType() << /*subscript*/ 0
7170 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7171 else
7172 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7173 << Args[0]->getType()
7174 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007175 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall1eb3e102010-01-07 02:04:15 +00007176 "[]", LLoc);
7177 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00007178 }
7179
7180 case OR_Ambiguous:
7181 Diag(LLoc, diag::err_ovl_ambiguous_oper)
7182 << "[]" << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007183 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, 2,
Sebastian Redlf322ed62009-10-29 20:17:01 +00007184 "[]", LLoc);
7185 return ExprError();
7186
7187 case OR_Deleted:
7188 Diag(LLoc, diag::err_ovl_deleted_oper)
7189 << Best->Function->isDeleted() << "[]"
7190 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007191 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, 2,
John McCall81201622010-01-08 04:41:39 +00007192 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00007193 return ExprError();
7194 }
7195
7196 // We matched a built-in operator; build it.
7197 Base.release();
7198 Idx.release();
7199 return CreateBuiltinArraySubscriptExpr(Owned(Args[0]), LLoc,
7200 Owned(Args[1]), RLoc);
7201}
7202
Douglas Gregor88a35142008-12-22 05:46:06 +00007203/// BuildCallToMemberFunction - Build a call to a member
7204/// function. MemExpr is the expression that refers to the member
7205/// function (and includes the object parameter), Args/NumArgs are the
7206/// arguments to the function call (not including the object
7207/// parameter). The caller needs to validate that the member
7208/// expression refers to a member function or an overloaded member
7209/// function.
John McCallaa81e162009-12-01 22:10:20 +00007210Sema::OwningExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00007211Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7212 SourceLocation LParenLoc, Expr **Args,
Douglas Gregor88a35142008-12-22 05:46:06 +00007213 unsigned NumArgs, SourceLocation *CommaLocs,
7214 SourceLocation RParenLoc) {
7215 // Dig out the member expression. This holds both the object
7216 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00007217 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7218
John McCall129e2df2009-11-30 22:42:35 +00007219 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00007220 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +00007221 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007222 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +00007223 if (isa<MemberExpr>(NakedMemExpr)) {
7224 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00007225 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +00007226 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +00007227 Qualifier = MemExpr->getQualifier();
John McCall129e2df2009-11-30 22:42:35 +00007228 } else {
7229 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +00007230 Qualifier = UnresExpr->getQualifier();
7231
John McCall701c89e2009-12-03 04:06:58 +00007232 QualType ObjectType = UnresExpr->getBaseType();
John McCall129e2df2009-11-30 22:42:35 +00007233
Douglas Gregor88a35142008-12-22 05:46:06 +00007234 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +00007235 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00007236
John McCallaa81e162009-12-01 22:10:20 +00007237 // FIXME: avoid copy.
7238 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7239 if (UnresExpr->hasExplicitTemplateArgs()) {
7240 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7241 TemplateArgs = &TemplateArgsBuffer;
7242 }
7243
John McCall129e2df2009-11-30 22:42:35 +00007244 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7245 E = UnresExpr->decls_end(); I != E; ++I) {
7246
John McCall701c89e2009-12-03 04:06:58 +00007247 NamedDecl *Func = *I;
7248 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7249 if (isa<UsingShadowDecl>(Func))
7250 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7251
John McCall129e2df2009-11-30 22:42:35 +00007252 if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00007253 // If explicit template arguments were provided, we can't call a
7254 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00007255 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00007256 continue;
7257
John McCall9aa472c2010-03-19 07:35:19 +00007258 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCall86820f52010-01-26 01:37:31 +00007259 Args, NumArgs,
John McCall701c89e2009-12-03 04:06:58 +00007260 CandidateSet, /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00007261 } else {
John McCall129e2df2009-11-30 22:42:35 +00007262 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +00007263 I.getPair(), ActingDC, TemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00007264 ObjectType, Args, NumArgs,
Douglas Gregordec06662009-08-21 18:42:58 +00007265 CandidateSet,
7266 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00007267 }
Douglas Gregordec06662009-08-21 18:42:58 +00007268 }
Mike Stump1eb44332009-09-09 15:08:12 +00007269
John McCall129e2df2009-11-30 22:42:35 +00007270 DeclarationName DeclName = UnresExpr->getMemberName();
7271
Douglas Gregor88a35142008-12-22 05:46:06 +00007272 OverloadCandidateSet::iterator Best;
John McCall129e2df2009-11-30 22:42:35 +00007273 switch (BestViableFunction(CandidateSet, UnresExpr->getLocStart(), Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00007274 case OR_Success:
7275 Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00007276 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +00007277 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007278 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +00007279 break;
7280
7281 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00007282 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00007283 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00007284 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007285 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00007286 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007287 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007288
7289 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00007290 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00007291 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007292 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00007293 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007294 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007295
7296 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00007297 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007298 << Best->Function->isDeleted()
Douglas Gregor6b906862009-08-21 00:16:32 +00007299 << DeclName << MemExprE->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007300 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007301 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00007302 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007303 }
7304
John McCall6bb80172010-03-30 21:47:33 +00007305 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +00007306
John McCallaa81e162009-12-01 22:10:20 +00007307 // If overload resolution picked a static member, build a
7308 // non-member call based on that function.
7309 if (Method->isStatic()) {
7310 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7311 Args, NumArgs, RParenLoc);
7312 }
7313
John McCall129e2df2009-11-30 22:42:35 +00007314 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00007315 }
7316
7317 assert(Method && "Member call to something that isn't a method?");
Mike Stump1eb44332009-09-09 15:08:12 +00007318 ExprOwningPtr<CXXMemberCallExpr>
John McCallaa81e162009-12-01 22:10:20 +00007319 TheCall(this, new (Context) CXXMemberCallExpr(Context, MemExprE, Args,
Mike Stump1eb44332009-09-09 15:08:12 +00007320 NumArgs,
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007321 Method->getCallResultType(),
Douglas Gregor88a35142008-12-22 05:46:06 +00007322 RParenLoc));
7323
Anders Carlssoneed3e692009-10-10 00:06:20 +00007324 // Check for a valid return type.
7325 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
7326 TheCall.get(), Method))
John McCallaa81e162009-12-01 22:10:20 +00007327 return ExprError();
Anders Carlssoneed3e692009-10-10 00:06:20 +00007328
Douglas Gregor88a35142008-12-22 05:46:06 +00007329 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +00007330 // We only need to do this if there was actually an overload; otherwise
7331 // it was done at lookup.
John McCallaa81e162009-12-01 22:10:20 +00007332 Expr *ObjectArg = MemExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00007333 if (!Method->isStatic() &&
John McCall6bb80172010-03-30 21:47:33 +00007334 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
7335 FoundDecl, Method))
John McCallaa81e162009-12-01 22:10:20 +00007336 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007337 MemExpr->setBase(ObjectArg);
7338
7339 // Convert the rest of the arguments
Douglas Gregor5f970ee2010-05-04 18:18:31 +00007340 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Mike Stump1eb44332009-09-09 15:08:12 +00007341 if (ConvertArgumentsForCall(&*TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00007342 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00007343 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00007344
Anders Carlssond406bf02009-08-16 01:56:34 +00007345 if (CheckFunctionCall(Method, TheCall.get()))
John McCallaa81e162009-12-01 22:10:20 +00007346 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00007347
John McCallaa81e162009-12-01 22:10:20 +00007348 return MaybeBindToTemporary(TheCall.release());
Douglas Gregor88a35142008-12-22 05:46:06 +00007349}
7350
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007351/// BuildCallToObjectOfClassType - Build a call to an object of class
7352/// type (C++ [over.call.object]), which can end up invoking an
7353/// overloaded function call operator (@c operator()) or performing a
7354/// user-defined conversion on the object argument.
Mike Stump1eb44332009-09-09 15:08:12 +00007355Sema::ExprResult
7356Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregor5c37de72008-12-06 00:22:45 +00007357 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007358 Expr **Args, unsigned NumArgs,
Mike Stump1eb44332009-09-09 15:08:12 +00007359 SourceLocation *CommaLocs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007360 SourceLocation RParenLoc) {
7361 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenek6217b802009-07-29 21:53:49 +00007362 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00007363
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007364 // C++ [over.call.object]p1:
7365 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00007366 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007367 // candidate functions includes at least the function call
7368 // operators of T. The function call operators of T are obtained by
7369 // ordinary lookup of the name operator() in the context of
7370 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +00007371 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00007372 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00007373
7374 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007375 PDiag(diag::err_incomplete_object_call)
Douglas Gregor593564b2009-11-15 07:48:03 +00007376 << Object->getSourceRange()))
7377 return true;
7378
John McCalla24dc2e2009-11-17 02:14:36 +00007379 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
7380 LookupQualifiedName(R, Record->getDecl());
7381 R.suppressDiagnostics();
7382
Douglas Gregor593564b2009-11-15 07:48:03 +00007383 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00007384 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00007385 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCall86820f52010-01-26 01:37:31 +00007386 Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00007387 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00007388 }
Douglas Gregor4a27d702009-10-21 06:18:39 +00007389
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007390 // C++ [over.call.object]p2:
7391 // In addition, for each conversion function declared in T of the
7392 // form
7393 //
7394 // operator conversion-type-id () cv-qualifier;
7395 //
7396 // where cv-qualifier is the same cv-qualification as, or a
7397 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00007398 // denotes the type "pointer to function of (P1,...,Pn) returning
7399 // R", or the type "reference to pointer to function of
7400 // (P1,...,Pn) returning R", or the type "reference to function
7401 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007402 // is also considered as a candidate function. Similarly,
7403 // surrogate call functions are added to the set of candidate
7404 // functions for each conversion function declared in an
7405 // accessible base class provided the function is not hidden
7406 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +00007407 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00007408 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00007409 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00007410 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00007411 NamedDecl *D = *I;
7412 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
7413 if (isa<UsingShadowDecl>(D))
7414 D = cast<UsingShadowDecl>(D)->getTargetDecl();
7415
Douglas Gregor4a27d702009-10-21 06:18:39 +00007416 // Skip over templated conversion functions; they aren't
7417 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00007418 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00007419 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007420
John McCall701c89e2009-12-03 04:06:58 +00007421 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCallba135432009-11-21 08:51:07 +00007422
Douglas Gregor4a27d702009-10-21 06:18:39 +00007423 // Strip the reference type (if any) and then the pointer type (if
7424 // any) to get down to what might be a function type.
7425 QualType ConvType = Conv->getConversionType().getNonReferenceType();
7426 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7427 ConvType = ConvPtrType->getPointeeType();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007428
Douglas Gregor4a27d702009-10-21 06:18:39 +00007429 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCall9aa472c2010-03-19 07:35:19 +00007430 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall701c89e2009-12-03 04:06:58 +00007431 Object->getType(), Args, NumArgs,
7432 CandidateSet);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007433 }
Mike Stump1eb44332009-09-09 15:08:12 +00007434
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007435 // Perform overload resolution.
7436 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00007437 switch (BestViableFunction(CandidateSet, Object->getLocStart(), Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007438 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007439 // Overload resolution succeeded; we'll build the appropriate call
7440 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007441 break;
7442
7443 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00007444 if (CandidateSet.empty())
7445 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
7446 << Object->getType() << /*call*/ 1
7447 << Object->getSourceRange();
7448 else
7449 Diag(Object->getSourceRange().getBegin(),
7450 diag::err_ovl_no_viable_object_call)
7451 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007452 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007453 break;
7454
7455 case OR_Ambiguous:
7456 Diag(Object->getSourceRange().getBegin(),
7457 diag::err_ovl_ambiguous_object_call)
Chris Lattnerd1625842008-11-24 06:25:27 +00007458 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007459 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007460 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007461
7462 case OR_Deleted:
7463 Diag(Object->getSourceRange().getBegin(),
7464 diag::err_ovl_deleted_object_call)
7465 << Best->Function->isDeleted()
7466 << Object->getType() << Object->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007467 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007468 break;
Mike Stump1eb44332009-09-09 15:08:12 +00007469 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007470
Douglas Gregorff331c12010-07-25 18:17:45 +00007471 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007472 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007473
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007474 if (Best->Function == 0) {
7475 // Since there is no function declaration, this is one of the
7476 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00007477 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007478 = cast<CXXConversionDecl>(
7479 Best->Conversions[0].UserDefined.ConversionFunction);
7480
John McCall9aa472c2010-03-19 07:35:19 +00007481 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007482 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00007483
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007484 // We selected one of the surrogate functions that converts the
7485 // object parameter to a function pointer. Perform the conversion
7486 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00007487
7488 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00007489 // and then call it.
John McCall6bb80172010-03-30 21:47:33 +00007490 CXXMemberCallExpr *CE = BuildCXXMemberCallExpr(Object, Best->FoundDecl,
7491 Conv);
Fariborz Jahanianb7400232009-09-28 23:23:40 +00007492
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00007493 return ActOnCallExpr(S, ExprArg(*this, CE), LParenLoc,
Sebastian Redl0eb23302009-01-19 00:08:26 +00007494 MultiExprArg(*this, (ExprTy**)Args, NumArgs),
Douglas Gregoraa0be172010-04-13 15:50:39 +00007495 CommaLocs, RParenLoc).result();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007496 }
7497
John McCall9aa472c2010-03-19 07:35:19 +00007498 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007499 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00007500
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007501 // We found an overloaded operator(). Build a CXXOperatorCallExpr
7502 // that calls this method, using Object for the implicit object
7503 // parameter and passing along the remaining arguments.
7504 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall183700f2009-09-21 23:43:11 +00007505 const FunctionProtoType *Proto = Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007506
7507 unsigned NumArgsInProto = Proto->getNumArgs();
7508 unsigned NumArgsToCheck = NumArgs;
7509
7510 // Build the full argument list for the method call (the
7511 // implicit object parameter is placed at the beginning of the
7512 // list).
7513 Expr **MethodArgs;
7514 if (NumArgs < NumArgsInProto) {
7515 NumArgsToCheck = NumArgsInProto;
7516 MethodArgs = new Expr*[NumArgsInProto + 1];
7517 } else {
7518 MethodArgs = new Expr*[NumArgs + 1];
7519 }
7520 MethodArgs[0] = Object;
7521 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
7522 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00007523
7524 Expr *NewFn = new (Context) DeclRefExpr(Method, Method->getType(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00007525 SourceLocation());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007526 UsualUnaryConversions(NewFn);
7527
7528 // Once we've built TheCall, all of the expressions are properly
7529 // owned.
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007530 QualType ResultTy = Method->getCallResultType();
Mike Stump1eb44332009-09-09 15:08:12 +00007531 ExprOwningPtr<CXXOperatorCallExpr>
7532 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
Douglas Gregor063daf62009-03-13 18:40:31 +00007533 MethodArgs, NumArgs + 1,
Ted Kremenek8189cde2009-02-07 01:47:29 +00007534 ResultTy, RParenLoc));
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007535 delete [] MethodArgs;
7536
Anders Carlsson07d68f12009-10-13 21:49:31 +00007537 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall.get(),
7538 Method))
7539 return true;
7540
Douglas Gregor518fda12009-01-13 05:10:00 +00007541 // We may have default arguments. If so, we need to allocate more
7542 // slots in the call for them.
7543 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00007544 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00007545 else if (NumArgs > NumArgsInProto)
7546 NumArgsToCheck = NumArgsInProto;
7547
Chris Lattner312531a2009-04-12 08:11:20 +00007548 bool IsError = false;
7549
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007550 // Initialize the implicit object parameter.
Douglas Gregor5fccd362010-03-03 23:55:11 +00007551 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall6bb80172010-03-30 21:47:33 +00007552 Best->FoundDecl, Method);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007553 TheCall->setArg(0, Object);
7554
Chris Lattner312531a2009-04-12 08:11:20 +00007555
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007556 // Check the argument types.
7557 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007558 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00007559 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007560 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00007561
Douglas Gregor518fda12009-01-13 05:10:00 +00007562 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +00007563
7564 OwningExprResult InputInit
7565 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
7566 Method->getParamDecl(i)),
7567 SourceLocation(), Owned(Arg));
7568
7569 IsError |= InputInit.isInvalid();
7570 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00007571 } else {
Douglas Gregord47c47d2009-11-09 19:27:57 +00007572 OwningExprResult DefArg
7573 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
7574 if (DefArg.isInvalid()) {
7575 IsError = true;
7576 break;
7577 }
7578
7579 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00007580 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007581
7582 TheCall->setArg(i + 1, Arg);
7583 }
7584
7585 // If this is a variadic call, handle args passed through "...".
7586 if (Proto->isVariadic()) {
7587 // Promote the arguments (C99 6.5.2.2p7).
7588 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
7589 Expr *Arg = Args[i];
Chris Lattner40378332010-05-16 04:01:30 +00007590 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007591 TheCall->setArg(i + 1, Arg);
7592 }
7593 }
7594
Chris Lattner312531a2009-04-12 08:11:20 +00007595 if (IsError) return true;
7596
Anders Carlssond406bf02009-08-16 01:56:34 +00007597 if (CheckFunctionCall(Method, TheCall.get()))
7598 return true;
7599
Douglas Gregoraa0be172010-04-13 15:50:39 +00007600 return MaybeBindToTemporary(TheCall.release()).result();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00007601}
7602
Douglas Gregor8ba10742008-11-20 16:27:02 +00007603/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00007604/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00007605/// @c Member is the name of the member we're trying to find.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007606Sema::OwningExprResult
7607Sema::BuildOverloadedArrowExpr(Scope *S, ExprArg BaseIn, SourceLocation OpLoc) {
7608 Expr *Base = static_cast<Expr *>(BaseIn.get());
Douglas Gregor8ba10742008-11-20 16:27:02 +00007609 assert(Base->getType()->isRecordType() && "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00007610
John McCall5769d612010-02-08 23:07:23 +00007611 SourceLocation Loc = Base->getExprLoc();
7612
Douglas Gregor8ba10742008-11-20 16:27:02 +00007613 // C++ [over.ref]p1:
7614 //
7615 // [...] An expression x->m is interpreted as (x.operator->())->m
7616 // for a class object x of type T if T::operator->() exists and if
7617 // the operator is selected as the best match function by the
7618 // overload resolution mechanism (13.3).
Douglas Gregor8ba10742008-11-20 16:27:02 +00007619 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +00007620 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +00007621 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007622
John McCall5769d612010-02-08 23:07:23 +00007623 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +00007624 PDiag(diag::err_typecheck_incomplete_tag)
7625 << Base->getSourceRange()))
7626 return ExprError();
7627
John McCalla24dc2e2009-11-17 02:14:36 +00007628 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
7629 LookupQualifiedName(R, BaseRecord->getDecl());
7630 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00007631
7632 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00007633 Oper != OperEnd; ++Oper) {
John McCall9aa472c2010-03-19 07:35:19 +00007634 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregor8ba10742008-11-20 16:27:02 +00007635 /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00007636 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00007637
7638 // Perform overload resolution.
7639 OverloadCandidateSet::iterator Best;
Douglas Gregore0762c92009-06-19 23:52:42 +00007640 switch (BestViableFunction(CandidateSet, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00007641 case OR_Success:
7642 // Overload resolution succeeded; we'll build the call below.
7643 break;
7644
7645 case OR_No_Viable_Function:
7646 if (CandidateSet.empty())
7647 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007648 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007649 else
7650 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007651 << "operator->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007652 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007653 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007654
7655 case OR_Ambiguous:
7656 Diag(OpLoc, diag::err_ovl_ambiguous_oper)
Anders Carlssone30572a2009-09-10 23:18:36 +00007657 << "->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007658 PrintOverloadCandidates(CandidateSet, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007659 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007660
7661 case OR_Deleted:
7662 Diag(OpLoc, diag::err_ovl_deleted_oper)
7663 << Best->Function->isDeleted()
Anders Carlssone30572a2009-09-10 23:18:36 +00007664 << "->" << Base->getSourceRange();
John McCallcbce6062010-01-12 07:18:19 +00007665 PrintOverloadCandidates(CandidateSet, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007666 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007667 }
7668
John McCall9aa472c2010-03-19 07:35:19 +00007669 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00007670 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +00007671
Douglas Gregor8ba10742008-11-20 16:27:02 +00007672 // Convert the object parameter.
7673 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall6bb80172010-03-30 21:47:33 +00007674 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
7675 Best->FoundDecl, Method))
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007676 return ExprError();
Douglas Gregorfc195ef2008-11-21 03:04:22 +00007677
7678 // No concerns about early exits now.
Douglas Gregorfe85ced2009-08-06 03:17:00 +00007679 BaseIn.release();
Douglas Gregor8ba10742008-11-20 16:27:02 +00007680
7681 // Build the operator call.
Ted Kremenek8189cde2009-02-07 01:47:29 +00007682 Expr *FnExpr = new (Context) DeclRefExpr(Method, Method->getType(),
7683 SourceLocation());
Douglas Gregor8ba10742008-11-20 16:27:02 +00007684 UsualUnaryConversions(FnExpr);
Anders Carlsson15ea3782009-10-13 22:43:21 +00007685
Douglas Gregor5291c3c2010-07-13 08:18:22 +00007686 QualType ResultTy = Method->getCallResultType();
Anders Carlsson15ea3782009-10-13 22:43:21 +00007687 ExprOwningPtr<CXXOperatorCallExpr>
7688 TheCall(this, new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
7689 &Base, 1, ResultTy, OpLoc));
7690
7691 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall.get(),
7692 Method))
7693 return ExprError();
7694 return move(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +00007695}
7696
Douglas Gregor904eed32008-11-10 20:40:00 +00007697/// FixOverloadedFunctionReference - E is an expression that refers to
7698/// a C++ overloaded function (possibly with some parentheses and
7699/// perhaps a '&' around it). We have resolved the overloaded function
7700/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +00007701/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +00007702Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +00007703 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +00007704 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00007705 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
7706 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00007707 if (SubExpr == PE->getSubExpr())
7708 return PE->Retain();
7709
7710 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
7711 }
7712
7713 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +00007714 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
7715 Found, Fn);
Douglas Gregor097bfb12009-10-23 22:18:25 +00007716 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +00007717 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +00007718 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +00007719 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +00007720 if (SubExpr == ICE->getSubExpr())
7721 return ICE->Retain();
7722
John McCallf871d0c2010-08-07 06:22:56 +00007723 return ImplicitCastExpr::Create(Context, ICE->getType(),
7724 ICE->getCastKind(),
7725 SubExpr, 0,
7726 ICE->getCategory());
Douglas Gregor699ee522009-11-20 19:42:02 +00007727 }
7728
7729 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
Mike Stump1eb44332009-09-09 15:08:12 +00007730 assert(UnOp->getOpcode() == UnaryOperator::AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +00007731 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +00007732 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7733 if (Method->isStatic()) {
7734 // Do nothing: static member functions aren't any different
7735 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +00007736 } else {
John McCallf7a1a742009-11-24 19:00:30 +00007737 // Fix the sub expression, which really has to be an
7738 // UnresolvedLookupExpr holding an overloaded member function
7739 // or template.
John McCall6bb80172010-03-30 21:47:33 +00007740 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7741 Found, Fn);
John McCallba135432009-11-21 08:51:07 +00007742 if (SubExpr == UnOp->getSubExpr())
7743 return UnOp->Retain();
Douglas Gregor699ee522009-11-20 19:42:02 +00007744
John McCallba135432009-11-21 08:51:07 +00007745 assert(isa<DeclRefExpr>(SubExpr)
7746 && "fixed to something other than a decl ref");
7747 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
7748 && "fixed to a member ref with no nested name qualifier");
7749
7750 // We have taken the address of a pointer to member
7751 // function. Perform the computation here so that we get the
7752 // appropriate pointer to member type.
7753 QualType ClassType
7754 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
7755 QualType MemPtrType
7756 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
7757
7758 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7759 MemPtrType, UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +00007760 }
7761 }
John McCall6bb80172010-03-30 21:47:33 +00007762 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
7763 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +00007764 if (SubExpr == UnOp->getSubExpr())
7765 return UnOp->Retain();
Anders Carlsson96ad5332009-10-21 17:16:23 +00007766
Douglas Gregor699ee522009-11-20 19:42:02 +00007767 return new (Context) UnaryOperator(SubExpr, UnaryOperator::AddrOf,
7768 Context.getPointerType(SubExpr->getType()),
7769 UnOp->getOperatorLoc());
Douglas Gregor699ee522009-11-20 19:42:02 +00007770 }
John McCallba135432009-11-21 08:51:07 +00007771
7772 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +00007773 // FIXME: avoid copy.
7774 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +00007775 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +00007776 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
7777 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +00007778 }
7779
John McCallba135432009-11-21 08:51:07 +00007780 return DeclRefExpr::Create(Context,
7781 ULE->getQualifier(),
7782 ULE->getQualifierRange(),
7783 Fn,
7784 ULE->getNameLoc(),
John McCallaa81e162009-12-01 22:10:20 +00007785 Fn->getType(),
7786 TemplateArgs);
John McCallba135432009-11-21 08:51:07 +00007787 }
7788
John McCall129e2df2009-11-30 22:42:35 +00007789 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +00007790 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +00007791 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7792 if (MemExpr->hasExplicitTemplateArgs()) {
7793 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7794 TemplateArgs = &TemplateArgsBuffer;
7795 }
John McCalld5532b62009-11-23 01:53:49 +00007796
John McCallaa81e162009-12-01 22:10:20 +00007797 Expr *Base;
7798
7799 // If we're filling in
7800 if (MemExpr->isImplicitAccess()) {
7801 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
7802 return DeclRefExpr::Create(Context,
7803 MemExpr->getQualifier(),
7804 MemExpr->getQualifierRange(),
7805 Fn,
7806 MemExpr->getMemberLoc(),
7807 Fn->getType(),
7808 TemplateArgs);
Douglas Gregor828a1972010-01-07 23:12:05 +00007809 } else {
7810 SourceLocation Loc = MemExpr->getMemberLoc();
7811 if (MemExpr->getQualifier())
7812 Loc = MemExpr->getQualifierRange().getBegin();
7813 Base = new (Context) CXXThisExpr(Loc,
7814 MemExpr->getBaseType(),
7815 /*isImplicit=*/true);
7816 }
John McCallaa81e162009-12-01 22:10:20 +00007817 } else
7818 Base = MemExpr->getBase()->Retain();
7819
7820 return MemberExpr::Create(Context, Base,
Douglas Gregor699ee522009-11-20 19:42:02 +00007821 MemExpr->isArrow(),
7822 MemExpr->getQualifier(),
7823 MemExpr->getQualifierRange(),
7824 Fn,
John McCall6bb80172010-03-30 21:47:33 +00007825 Found,
Abramo Bagnara25777432010-08-11 22:01:17 +00007826 MemExpr->getMemberNameInfo(),
John McCallaa81e162009-12-01 22:10:20 +00007827 TemplateArgs,
Douglas Gregor699ee522009-11-20 19:42:02 +00007828 Fn->getType());
7829 }
7830
Douglas Gregor699ee522009-11-20 19:42:02 +00007831 assert(false && "Invalid reference to overloaded function");
7832 return E->Retain();
Douglas Gregor904eed32008-11-10 20:40:00 +00007833}
7834
Douglas Gregor20093b42009-12-09 23:02:17 +00007835Sema::OwningExprResult Sema::FixOverloadedFunctionReference(OwningExprResult E,
John McCall161755a2010-04-06 21:38:20 +00007836 DeclAccessPair Found,
Douglas Gregor20093b42009-12-09 23:02:17 +00007837 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +00007838 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +00007839}
7840
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007841} // end namespace clang